requireAudience with multiple valid audiences

95 views Asked by At

I have been working back-end JWT validation and I've been using the JJWT library.

When building the JwtsParser we can call

.requireAudience("audience")

And this will attempt to match the audience claim in the JWT token and verify it or not depending on the result.

I have a situation where I have multiple audiences (two different front-ends) and I am trying to match the audience to either front-end 1 or front-end 2. However, when I add

.requireAudience("FE1")
.requireAudience("FE2")

it attempts to match both of those values.

Is there any way to achieve this functionality with the library or should I just write my own audience verify method?

1

There are 1 answers

1
الرحمن الرحیم On

try following changes:

public boolean verifyAudience(String jwt, String requiredAudience) {
    JwtParser jwtParser = Jwts.parser().setSigningKey(yourSigningKey);

    try {
        Claims claims = jwtParser.parseClaimsJws(jwt).getBody();
        List<String> audienceList = claims.getAudience();
        return audienceList.contains(requiredAudience);
    } catch (JwtException e) {
        // Handle JWT verification error
        return false;
    }
}

// Usage:
if (verifyAudience(yourJwt, "FE1") || verifyAudience(yourJwt, "FE2")) {
    // JWT contains either "FE1" or "FE2"
}

and then:

{
    "aud": ["FE1", "FE2"],
    // other claims
}