Auth0 with Kotlin Ktor

I have a regular web application


I managed it to work properly with Spring Boot

I also created an API:

Following some article, I implemented Auth0 module on my ktor server

fun validateCreds(credential: JWTCredential, permission: String? = null): JWTPrincipal? {
    val containsAudience = credential.payload.audience.contains(System.getenv("AUDIENCE"))
    val containsScope = permission.isNullOrBlank() ||
            credential.payload.claims["permissions"]?.asArray(String::class.java)?.contains(permission) == true

    if (containsAudience && containsScope) {
        return JWTPrincipal(credential.payload)
    }

    return null
}
fun Application.configureAuth0() {

    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) }
        }
        jwt("auth0-admin") {
            verifier(jwkProvider, System.getenv("ISSUER"))
            validate { credential -> validateCreds(credential, "read:admin-messages") }
        }
    }
}```
Also, config the routing
```kotlin
routing{
     authenticate("auth0") {
            get("/api/messages/protected") {
                call.respondText(
                    """{"message": "The API successfully validated your access token."}""",
                    contentType = ContentType.Application.Json
                )
            }
        }
}

The problem is that I can’t reach restricted endpoints, any response I get is UNAUTHORIZED.
I took the token from my Spring Boot application oidcUser.getIdToken().getTokenValue();
and I add it to the postman request as bearer token, but it just doesn’t work. I’m pretty sure that it should be enough, authorize in fronted app and send the request to the backend server with the bearer token. Is my approach right? What can cause this problem?
This is my configuration:

I tried to follow this article: Adding Auth0 Authorization to a Ktor HTTP API

Hey there @zwo7ak !

Thanks for the detailed description of the issue you’re running into.

You’ll need to pass an access token to your Ktor API as opposed to the ID token. I believe that should do the trick as your API code looks correct to me.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.