Search code examples
kotlinjwtnimbus-jose-jwt

Nimbus JOSE JWT expected audience claim to be any of a multiple


When validating a JWT I have the scenario that I have a list of allowed client-ids. I put the client-id as audience claim into the JWT but then when verifying I need need to compare against the list.

I tried the following:

val allowedClients = listof("client1", "client2")
val validClaims= JWTClaimsSet.Builder()
        .issuer("myIssuer")
        .audience(allowedClients)
        .build()

val jwtProcessor: ConfigurableJWTProcessor<SecurityContext> = DefaultJWTProcessor()
jwtProcessor.jwsKeySelector = keySelector

jwtProcessor.jwtClaimsSetVerifier = DefaultJWTClaimsVerifier(
        //exact match claims
        validClaims,
        //Required claims
        HashSet(listOf("exp", "iss")))
jwtProcessor.jwsKeySelector = keySelector

But if now a JWT is issued with only one client-id which I was doing then the verification fails with

com.nimbusds.jwt.proc.BadJWTException: JWT aud claim has value [client2], must be [client1, client2]

What I can I do such that the Verifier expect any of the client-ids to be in the audience claim but not the full list? Of course an alternative would to add a client-ids to the audience claim to the beginning but I would like to avoid this.


Solution

  • You can define the accepted audience in the verifier. (doc is from nimbus-jose-jwt v9.20)

    /**
     * Creates new default JWT claims verifier. The expiration ("exp") and
     * not-before ("nbf") claims will be checked only if they are present
     * and parsed successfully; add them to the required claims if they are
     * mandatory.
     *
     * @param acceptedAudience The accepted JWT audience values,
     *                         {@code null} if not specified. A
     *                         {@code null} value in the set allows JWTs
     *                         with no audience.
     * @param exactMatchClaims The JWT claims that must match exactly,
     *                         {@code null} if none.
     * @param requiredClaims   The names of the JWT claims that must be
     *                         present, empty set or {@code null} if none.
     * @param prohibitedClaims The names of the JWT claims that must not be
     *                         present, empty set or {@code null} if none.
     */
    public DefaultJWTClaimsVerifier(final Set<String> acceptedAudience,
                    final JWTClaimsSet exactMatchClaims,
                    final Set<String> requiredClaims,
                    final Set<String> prohibitedClaims) {