Search code examples
jwtjjwt

io.jsonwebtoken decode JWT claims before validating the signature


Assuming I have multiple clients, I'm expecting from my "clientA" to provide a JWT token created with it's privateKeyClientA, like

String jwtToken = Jwts.builder()
        .claims()
        .issuer("ClientA")
        .expiration(expirationDate)
        .and()
        .signWith(privateKeyClientA)
        .compact() ;

to decode the claims, I can use

claims = Jwts.parser()
         .verifyWith(publicKeyClientA)  
         .build()
         .parseClaimsJws(jwtToken)
         .getBody();
         

But, how do you identify "clientA", so, publicKeyClientA before validating the JWT's signature in an "elegant way"?

p.s. I must use "JJWT :: API" (io.jsonwebtoken)


Solution

  • Two approaches:

    • use the key id in the header to identify the correct key.
    • parse the JWT body and extract the issuer field.

    If there is no io.jsonwebtoken support for parsing before validating, try another library.

    Doing this yourself can be like so:

    • parse b from "Bearer a.b.c"
    • base64 decode (url safe)
      • note: some libs also use compression for b
    • parse the resulting JSON document
      • preferably using pull parser, issuer is probably the first field
      • extract issuer field value

    For header just parse a instead.