Provide programmatic access to specific reasons for JWT invalidity

Issue #76 closed
Brian Campbell repo owner created an issue

Comments (7)

  1. Keith Gregory

    As a particular use case: token expiration should be handled differently than any other failure -- ie, I want to attempt a refresh if the token has expired, but not if the issuer (or other claim) is incorrect. Although, in practice if the signature is valid and we're not checking the subject, then the only thing that it could be is an expired token.

  2. Keith Gregory

    Right. I commented and voted so that you'd know people are interested in the feature.

    Optimally, I'd like to see a "silentProcess" method, and an "isValid" on the JwtClaims object. Then I could log some of the claims if it's invalid.

  3. Brian Campbell reporter

    Fair enough, interest noted. I just wanted you to be aware of the workaround approach, if you weren't already.

  4. Brian Campbell reporter
    • edited description
    • changed status to resolved

    done with 1ff420d "address issue #76 by providing programatic access to (some) specific reasons for JWT invalidity through error codes on InvalidJwtException"

    With this change, you can do things like the following:

     try
        {
            //  Validate the JWT and process it to the Claims
            JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
            System.out.println("JWT validation succeeded! " + jwtClaims);
        }
        catch (InvalidJwtException e)
        {
            // InvalidJwtException will be thrown, if the JWT failed processing or validation in anyway.
            // Hopefully with meaningful explanations(s) about what went wrong.
            System.out.println("Invalid JWT! " + e);
    
            // Programmatic access to (some) specific reasons for JWT invalidity is also possible
            // should you want different error handling behavior for certain conditions.
    
            // Whether or not the JWT has expired being one common reason for invalidity
            if (e.hasExpired())
            {
                System.out.println("JWT expired at " + e.getJwtContext().getJwtClaims().getExpirationTime());
            }
    
            // Or maybe the audience was invalid
            if (e.hasErrorCode(ErrorCodes.AUDIENCE_INVALID))
            {
                System.out.println("JWT had wrong audience: " + e.getJwtContext().getJwtClaims().getAudience());
            }
        }
    
  5. Log in to comment