How can I set the "alg" header? #876
-
I am trying to implement a token generator using JJWT and Java 21. But I can't seem to figure out, how to set the "alg" header. Everything else works just fine. I can add other headers, custom headers and claims. But as soon es I try to set a custom header to {"alg": "EC512"} it just sets the "alg" header top "none". I also can't find an option to set this header directly like for example the type or keyID. Any advice is highly appreciated! This is the code in question:
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Good question! I'm assuming The Jwts.builder()
.signWIth(key) // JJWT implicitly chooses the appropriate algorithm based on the key type and size, or:
//.signWith(key, aSecureDigestAlgorithm) // you explicitly set the algorithm, usually via a Jwts.SIG.**** constant
... JJWT will automatically set the JWS For example, if a JWT was signed with the ES512 algorithm: assert Jwts.SIG.ES512.getId().equals(aJws.getHeader().getAlgorithm()); Similarly, for JWEs, using assert Jwts.KEY.RSA_OAEP_256.getId().equals(aJwe.getHeader().getAlgorithm()); So if you want the Jwts.builder()
.signWith(key, myEc512AlgorithmInstance)
... But since Jwts.parser()
.sig().add(myEc512AlgorithmInstance).and()
... And then the parser will use your algorithm for signature verification when encountering JWSs with an If no signature or key management algorithm is specified via Finally, note that the I hope that helps! |
Beta Was this translation helpful? Give feedback.
-
P.S. Note that the JWT specifications suggest that you do not need set the JWT The type header is only really necessary if:
It's not valuable for standalone compact (Base64Url period-delimited) strings, because nothing in the string can be inspected to know it's a JWT. You have to be reasonably sure it's a compact JWT first before you pass it to a JWT parser, at which point you don't need the |
Beta Was this translation helpful? Give feedback.
Good question!
I'm assuming
EC512
is not a typo for the RFC standardES512
algorithm (ECDSA using P-521 and SHA-512), which JJWT natively supports via theJwts.SIG.ES512
constant. So this implies that you're trying to implement your own custom signature (or key management) algorithm with a non-standardEC512
identifier. Based on that assumption:The
alg
header is set automatically by JJWT based on the signature algorithm (for signed JWTs, aka JWSs) or key management algorithm (for encrypted JWTs, aka JWEs) specified during JWT building. For example, for JWSs: