https://kotlinlang.org logo
#ktor
Title
# ktor
y

Yash

10/09/2023, 2:04 AM
When using ktor-auth how does
call.user
get populated? I am adding 2 auth mechanisms using jwt. While
call.user
works normally,
call.merchant
is not working.
Copy code
fun AuthenticationConfig.authenticationModule(
        merchantApi: MerchantApi,
        userApi: UserApi,
        databaseProvider: DatabaseProviderContract,
        tokenVerifier: JWTVerifier
) {
    /**
     * Setup the JWT authentication to be used in [Routing]. If the token is valid, the
     * corresponding [User] is fetched from the database. The [User] can then be accessed in each
     * [ApplicationCall].
     */
    jwt("user") {
        verifier(tokenVerifier)
        realm = Settings.jwtRealm
        validate {
            if (it.payload.getClaim("type").asString() == Settings.user) {
                it.payload.getClaim("id").asInt()?.let { userId ->
                    // do database query to find Principal subclass
                    databaseProvider.dbQuery { userApi.getUserById(userId) }
                }
            } else {
                null
            }
        }
    }

    jwt("merchant") {
        verifier(tokenVerifier)
        realm = Settings.jwtRealm
        validate {
            if (it.payload.getClaim("type").asString() == Settings.merchant) {
                it.payload.getClaim("id").asInt()?.let { merchantId ->
                    // do database query to find Principal subclass
                    databaseProvider.dbQuery { merchantApi.getMerchantById(merchantId) }
                }
            } else {
                null
            }
        }
    }
}
a

Aleksei Tirman [JB]

10/09/2023, 7:02 AM
You can pass the name of the provider to the
call.principal
method to get the respective principal:
Copy code
call.principal<Principal>("merchant")
1
🙌 1