2

I'm reading the overview of the jjwt library:

Building the token is done as following:

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.crypto.MacProvider;
import java.security.Key;

// We need a signing key, so we'll create one just for this example. Usually
// the key would be read from your application configuration instead.
Key key = MacProvider.generateKey();

String compactJws = Jwts.builder()
  .setSubject("Joe")
  .signWith(SignatureAlgorithm.HS512, key)
  .compact();

And the token is verified as:

try {

    Jwts.parser().setSigningKey(key).parseClaimsJws(compactJws);

    //OK, we can trust this JWT

} catch (SignatureException e) {

    //don't trust the JWT!
}

SignatureAlgorithm.HS512 is not used on the second snippet. How is it inferred? Or is it not necessary?

Les Hazlewood
  • 18,480
  • 13
  • 68
  • 76
Alexander Suraphel
  • 10,103
  • 10
  • 55
  • 90

2 Answers2

3

Because JWT includes the algorithm in the header, so the validator knows which algorithm need to use simply decoding the first part of the token

For example, if you decode the first part of this token (test at https://jwt.io/)

eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.O8YgYdD1YxficWfO_06nDsm_YgDdXmgMM4CN3bLor5c

corresponds to

{
  "alg": "HS512",
  "typ": "JWT"
}
pedrofb
  • 37,271
  • 5
  • 94
  • 142
3

As @pedrofb mentions the algorithm is conveniently included in the header, and in case of an asymmetric algorithm you can also find the key that was used via the kid header parameter.

Heads up that you should be very careful to only allow the algorithms that you expect when decoding. Otherwise you might accept a token that was signed with alg=none, essentially bypassing any verification.

Most decoders have support for this (and if they don't, they should). Your particular example though seems worrisome as

//OK, we can trust this JWT

might not be true if your parser also accepts alg=none. So take care!

Pieter Ennes
  • 2,301
  • 19
  • 21