Hi all, we need to secure a ktor web api with Micr...
# ktor
a
Hi all, we need to secure a ktor web api with Microsoft identity platform We are getting a bearer token from the client, as described here: https://learn.microsoft.com/en-us/entra/msal/java/getting-started/using-the-acquired-token-to-call-a-protected-web-api But on the ktor server side, we need to figure out what to do with that token There is a spring boot example here: https://github.com/Azure-Samples/ms-identity-msal-java-samples/tree/main/4-spring-web-app/3-Authorization-II/protect-web-api#protecting[…]reradapter We need to do exactly that same thing in ktor. Has anybody else tried to do this already?
a
a
we hope so. our plan is to try with the jwt token authentication and see whether it works out of the box when we configure the verifier.
a
to setup jwt authentication I do something like that
Copy code
import com.auth0.jwk.JwkProviderBuilder
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import java.net.URL
import java.util.concurrent.TimeUnit

fun Application.configureSecurity() {

    val keysUri = URL(environment.config.property("jwt.keysUri").getString())
    val issuer = environment.config.property("jwt.issuer").getString()
    val audience = environment.config.propertyOrNull("jwt.audience")?.getString()
    val jwkProvider = JwkProviderBuilder(keysUri)
        .cached(10, 24, TimeUnit.HOURS)
        .rateLimited(10, 1, TimeUnit.MINUTES)
        .build()
    authentication {
        jwt {
            realm = "Secure Area"
            verifier(jwkProvider, issuer) {
                withIssuer(issuer)
                if (audience != null)
                    withAudience(audience)
                acceptLeeway(10)
            }
            validate { credential ->
                JWTPrincipal(credential.payload)
            }
        }
    }

}
in configuration you can set the properties like that
Copy code
jwt {
    keysUri = ${JWKS_URI}
    issuer = ${JWT_ISSUER_URI}
    audience = ${JWT_AUDIENCE}
}
and use environment variables like: JWKS_URI=https://login.microsoftonline.com/[your_tenant_id]/discovery/v2.0/keys JWT_ISSUER_URI=https://login.microsoftonline.com/[your_tenant_id]/v2.0 JWT_AUDIENCE=[your_client_id]