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?
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"
}