Hi, all. I’m developing a Ktor single-page web app and I intend to integrate Auth0 with it but I haven’t found enough documentation for Auth0 with Kotlin so far. I’m following the steps described on Adding Auth0 Authorization to a Ktor HTTP API, but I’m struggling to connect our web app to my Auth0 API and App. I really hope I could get some help from you.
Below is an extract of the main parts of the code. I’m getting “HTTP ERROR 401” when trying http://localhost:8080/api/messages/protected.
fun Route.homepage() {
get("/api/messages/public") {
call.respondText(
"""{"message": "The API doesn't require an access token to share this message."}""",
contentType = ContentType.Application.Json
)
}
authenticate("auth0") {
get("/api/messages/protected") {
call.respondText(
"""{"message": "The API successfully validated your access token."}""",
contentType = ContentType.Application.Json
)
}
}
}
fun validateCreds(credential: JWTCredential): JWTPrincipal? {
val containsAudience = credential.payload.audience.contains(System.getenv("AUDIENCE"))
if (containsAudience) {
return JWTPrincipal(credential.payload)
}
return null
}
fun Application.module() {
install(ContentNegotiation) {
json()
}
install(CORS) {
method(HttpMethod.Get)
method(HttpMethod.Post)
method(HttpMethod.Delete)
header(HttpHeaders.ContentType)
//anyHost()
method(HttpMethod.Options)
method(HttpMethod.Get)
header("authorization")
allowCredentials = true
allowNonSimpleContentTypes = true
}
val jwkProvider = JwkProviderBuilder(System.getenv("ISSUER"))
.cached(10, 24, TimeUnit.HOURS)
.rateLimited(10, 1, TimeUnit.MINUTES)
.build()
install(Authentication) {
jwt("auth0") {
verifier(jwkProvider, System.getenv("ISSUER"))
validate { credential -> validateCreds(credential) }
}
}
install(Compression) {
gzip()
}
routing {
homepage()
}
}
I’ve set ISSUER and AUDIENCE as environment variables