java-jwt icon indicating copy to clipboard operation
java-jwt copied to clipboard

Fine-grained verification exception handling

Open yuanzhou opened this issue 10 years ago • 2 comments

I'm using this JWT library in my API authentication. I don't see many examples in the README. And I wanted to handle the verification exceptions in a fine-grained level. Based on the documented example, instead of just telling API consumers "Invalid Token", I wanted to verify the issuer and expiration time separately.

try {
    final JWTVerifier verifier = new JWTVerifier("{{secret used for signing}}", "{{my-audience}}", "{{my-issuer}}");
    final Map<String, Object> claims= verifier.verify(jwt);
} catch (JWTVerifyException e) {
    // Invalid Token
}

Can anyone provide any examples? Thanks!

yuanzhou avatar Oct 07 '16 14:10 yuanzhou

@yuanzhou You can use the type of exception.

  • If it's an algorithm problem: AlgorithmMismatchException
  • If it's a signature problem: SignatureVerificationException
  • If it's the claims: InvalidClaimException

ensonik avatar Dec 16 '16 16:12 ensonik

Hi @yuanzhou. You should do as @ensonik suggested and check the type of the exception. This also works for v3 where JWTVerificationException is thrown but the cause is wrapped as follows:

  • SignatureVerificationException: the signature is invalid
  • AlgorithmMismatchException: algorithm is not the specified
  • InvalidClaimException: value is not the expected one

lbalmaceda avatar Dec 19 '16 17:12 lbalmaceda