hey, I have a problem about using jwt to authentic...
# ktor
k
hey, I have a problem about using jwt to authenticate, for example, I intercept the
Call
phase
Copy code
fun Application.configureRouting() {
    intercept(ApplicationCallPipeline.Call) {
        val authentication = call.request.headers["Authentication"]
            ?: throw BadRequestException("no uid field in the request header")

        if (!authentication.startsWith("Bearer")) {
            throw BadRequestException("invalid authentication token format")
        }
    }
}
in this case, I will checkout if there is "Authentication" field in the call.request and check if the field startsWith "Bearer " but in the
authentication
block, I don't know how to remove this
Bearer
when parsing the token, (if I don't use the
Bearer
, can it works ?)
Copy code
authentication {
        jwt("auth-jwt") {
            this.realm = realm
            verifier(
                JWT
                    .require(Algorithm.HMAC256(secret))
                    .withAudience(audience)
                    .withIssuer(domain)
                    .build()
            )

            validate { credential ->
                if (credential.payload.audience.contains(audience)) {
                    JWTPrincipal(credential.payload)
                } else {
                    null
                }
            }

            challenge { defaultScheme, realm ->
                call.respond(HttpStatusCode.Unauthorized, Response.Err("token is not valid or has expired"))
            }

            skipWhen { call ->
                call.request.httpMethod == <http://HttpMethod.Post|HttpMethod.Post> &&
                        (call.request.path().endsWith("/login") || call.request.path().endsWith("/register"))
            }
        }
    }
a
You can redefine the parsing of the
Authorization
method using the
authHeader
method. You can find an example here.
🙌 1
k
eh, by the way, when the closure in
authHeader
return null, what will happen ?
a
The JWT authentication will fail.
k
then will the
challenge
be called ?
Copy code
challenge { defaultScheme, realm ->
                call.respond(HttpStatusCode.Unauthorized, Response.Err("token is not valid or has expired"))
            }
a
Yes, it should be called then.