-
Notifications
You must be signed in to change notification settings - Fork 1k
/
AuthWithPlugins.kt
59 lines (51 loc) · 1.65 KB
/
AuthWithPlugins.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.tests.auth
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.serialization.jackson.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import kotlin.test.*
class AuthWithPlugins {
@Test
fun testFormAuthWithJackson() = testApplication {
install(ContentNegotiation) {
jackson()
}
install(Authentication) {
form {
challenge("/unauthorized")
validate { credentials ->
if (credentials.name == credentials.password) {
UserIdPrincipal(credentials.name)
} else {
null
}
}
}
}
routing {
get("/unauthorized") {
call.respond(HttpStatusCode.Unauthorized, "Unauthorized")
}
authenticate {
post("/test") {
call.respondText("OK")
}
}
}
val response = client.post("/test") {
header(HttpHeaders.ContentType, ContentType.Application.Json)
setBody("{}")
}
assertEquals(HttpStatusCode.Found, response.status)
val location = response.headers[HttpHeaders.Location] ?: fail("Location header is missing")
assertEquals("/unauthorized", location)
}
}