Skip to content

Commit 0beebb9

Browse files
authored
KTOR-678 Add test for Auth with Jackson (#3154)
1 parent 4657cb2 commit 0beebb9

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

ktor-server/ktor-server-plugins/ktor-server-auth/build.gradle.kts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,5 +26,11 @@ kotlin {
2626
api(project(":ktor-server:ktor-server-test-host"))
2727
}
2828
}
29+
jvmTest {
30+
dependencies {
31+
api(project(":ktor-server:ktor-server-plugins:ktor-server-content-negotiation"))
32+
api(project(":ktor-shared:ktor-serialization:ktor-serialization-jackson"))
33+
}
34+
}
2935
}
3036
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
3+
*/
4+
5+
package io.ktor.tests.auth
6+
7+
import io.ktor.client.request.*
8+
import io.ktor.http.*
9+
import io.ktor.serialization.jackson.*
10+
import io.ktor.server.application.*
11+
import io.ktor.server.auth.*
12+
import io.ktor.server.plugins.contentnegotiation.*
13+
import io.ktor.server.response.*
14+
import io.ktor.server.routing.*
15+
import io.ktor.server.testing.*
16+
import kotlin.test.*
17+
18+
class AuthWithPlugins {
19+
20+
@Test
21+
fun testFormAuthWithJackson() = testApplication {
22+
install(ContentNegotiation) {
23+
jackson()
24+
}
25+
install(Authentication) {
26+
form {
27+
challenge("/unauthorized")
28+
validate { credentials ->
29+
if (credentials.name == credentials.password) {
30+
UserIdPrincipal(credentials.name)
31+
} else {
32+
null
33+
}
34+
}
35+
}
36+
}
37+
38+
routing {
39+
get("/unauthorized") {
40+
call.respond(HttpStatusCode.Unauthorized, "Unauthorized")
41+
}
42+
authenticate {
43+
post("/test") {
44+
call.respondText("OK")
45+
}
46+
}
47+
}
48+
49+
val response = client.post("/test") {
50+
header(HttpHeaders.ContentType, ContentType.Application.Json)
51+
setBody("{}")
52+
}
53+
54+
assertEquals(HttpStatusCode.Found, response.status)
55+
56+
val location = response.headers[HttpHeaders.Location] ?: fail("Location header is missing")
57+
assertEquals("/unauthorized", location)
58+
}
59+
}

0 commit comments

Comments
 (0)