public interface JwtBuilder extends ClaimsMutator<JwtBuilder>
Modifier and Type | Interface and Description |
---|---|
static interface |
JwtBuilder.BuilderClaims
Claims for use with a
JwtBuilder that supports method chaining for standard JWT Claims parameters. |
static interface |
JwtBuilder.BuilderHeader
Header for use with a
JwtBuilder that supports method chaining for
standard JWT, JWS and JWE header parameters. |
ClaimsMutator.AudienceCollection<P>
Modifier and Type | Method and Description |
---|---|
JwtBuilder |
addClaims(Map<String,?> claims)
|
JwtBuilder |
b64Url(Encoder<OutputStream,OutputStream> encoder)
Perform Base64Url encoding during
compaction with the specified OutputStream Encoder. |
JwtBuilder |
base64UrlEncodeWith(Encoder<byte[],String> base64UrlEncoder)
Deprecated.
since 0.12.0 in favor of
b64Url(Encoder) . |
JwtBuilder |
claim(String name,
Object value)
Sets a JWT claim, overwriting any existing claim with the same name.
|
JwtBuilder.BuilderClaims |
claims()
Returns the JWT
Claims payload to modify as desired. |
JwtBuilder |
claims(Map<String,?> claims)
Adds all given name/value pairs to the JSON Claims in the payload, overwriting any existing claims
with the same names.
|
String |
compact()
Actually builds the JWT and serializes it to a compact, URL-safe string according to the
JWT Compact Serialization
rules.
|
JwtBuilder |
compressWith(CompressionAlgorithm alg)
Compresses the JWT payload using the specified
CompressionAlgorithm . |
JwtBuilder |
content(byte[] content)
Sets the JWT payload to be the specified content byte array.
|
JwtBuilder |
content(byte[] content,
String cty)
Sets the JWT payload to be the specified byte array, and also sets the
contentType header value to a compact cty IANA Media Type
identifier to indicate the data format of the byte array. |
JwtBuilder |
content(InputStream in)
Sets the JWT payload to be the bytes in the specified content stream.
|
JwtBuilder |
content(InputStream content,
String cty)
Sets the JWT payload to be the specified content byte stream and also sets the
contentType header value to a compact cty IANA Media Type
identifier to indicate the data format of the byte array. |
JwtBuilder |
content(String content)
Sets the JWT payload to be the specified string's UTF-8 bytes.
|
JwtBuilder |
content(String content,
String cty)
Sets the JWT payload to be the specified String's UTF-8 bytes, and also sets the
contentType header value to a compact cty IANA Media Type
identifier to indicate the data format of the resulting byte array. |
JwtBuilder |
encodePayload(boolean b64)
Enables RFC 7797: JSON Web Signature (JWS)
Unencoded Payload Option if
false , or standard JWT/JWS/JWE payload encoding otherwise. |
<K extends Key> |
encryptWith(K key,
KeyAlgorithm<? super K,?> keyAlg,
AeadAlgorithm enc)
Encrypts the constructed JWT using the specified
enc algorithm with the symmetric key produced by the
keyAlg when invoked with the given key , producing a JWE. |
JwtBuilder |
encryptWith(SecretKey key,
AeadAlgorithm enc)
Encrypts the constructed JWT with the specified symmetric
key using the provided enc ryption
algorithm, producing a JWE. |
JwtBuilder |
expiration(Date exp)
Sets the JWT Claims
exp (expiration) claim. |
JwtBuilder.BuilderHeader |
header()
Returns the
Header to use to modify the constructed JWT's header name/value pairs as desired. |
JwtBuilder |
id(String jti)
Sets the JWT Claims
jti (JWT ID) claim. |
JwtBuilder |
issuedAt(Date iat)
Sets the JWT Claims
iat (issued at) claim. |
JwtBuilder |
issuer(String iss)
Sets the JWT Claims
iss (issuer) claim. |
JwtBuilder |
json(Serializer<Map<String,?>> serializer)
Perform Map-to-JSON serialization with the specified Serializer.
|
JwtBuilder |
notBefore(Date nbf)
Sets the JWT Claims
nbf (not before) claim. |
JwtBuilder |
provider(Provider provider)
Sets the JCA Provider to use during cryptographic signing or encryption operations, or
null if the
JCA subsystem preferred provider should be used. |
JwtBuilder |
random(SecureRandom secureRandom)
Sets the
SecureRandom to use during cryptographic signing or encryption operations, or null if
a default SecureRandom should be used. |
JwtBuilder |
serializeToJsonWith(Serializer<Map<String,?>> serializer)
Deprecated.
since 0.12.0 in favor of
json(Serializer) |
JwtBuilder |
setClaims(Map<String,?> claims)
Deprecated.
since 0.12.0 in favor of using the
claims() builder. |
JwtBuilder |
setHeader(Map<String,?> map)
|
JwtBuilder |
setHeaderParam(String name,
Object value)
Deprecated.
since 0.12.0 in favor of
.
This method will be removed before the 1.0 release. |
JwtBuilder |
setHeaderParams(Map<String,?> params)
|
JwtBuilder |
setPayload(String payload)
Deprecated.
since 0.12.0 in favor of
content(String)
because both Claims and Content are technically 'payloads', so this method name is misleading. This method will
be removed before the 1.0 release. |
JwtBuilder |
signWith(Key key)
Signs the constructed JWT with the specified key using the key's recommended signature algorithm
as defined below, producing a JWS.
|
JwtBuilder |
signWith(Key key,
SignatureAlgorithm alg)
Deprecated.
since 0.12.0 to use the more flexible
signWith(Key, SecureDigestAlgorithm) . |
<K extends Key> |
signWith(K key,
SecureDigestAlgorithm<? super K,?> alg)
Signs the constructed JWT with the specified key using the specified algorithm, producing a JWS.
|
JwtBuilder |
signWith(SignatureAlgorithm alg,
byte[] secretKey)
Deprecated.
as of 0.10.0: use
Keys .hmacShaKeyFor(bytes) to
obtain the Key and then invoke signWith(Key) or
signWith(Key, SecureDigestAlgorithm) .
This method will be removed in the 1.0 release. |
JwtBuilder |
signWith(SignatureAlgorithm alg,
Key key)
Deprecated.
since 0.10.0. Use
signWith(Key, SecureDigestAlgorithm) instead.
This method will be removed before the 1.0 release. |
JwtBuilder |
signWith(SignatureAlgorithm alg,
String base64EncodedSecretKey)
Deprecated.
as of 0.10.0: use
signWith(Key) or signWith(Key, SignatureAlgorithm) instead. This
method will be removed in the 1.0 release. |
JwtBuilder |
subject(String sub)
Sets the JWT Claims
sub (subject) claim. |
audience, setAudience, setExpiration, setId, setIssuedAt, setIssuer, setNotBefore, setSubject
JwtBuilder provider(Provider provider)
null
if the
JCA subsystem preferred provider should be used.provider
- the JCA Provider to use during cryptographic signing or encryption operations, or null
if the
JCA subsystem preferred provider should be used.JwtBuilder random(SecureRandom secureRandom)
SecureRandom
to use during cryptographic signing or encryption operations, or null
if
a default SecureRandom
should be used.secureRandom
- the SecureRandom
to use during cryptographic signing or encryption operations, or
null
if a default SecureRandom
should be used.JwtBuilder.BuilderHeader header()
Header
to use to modify the constructed JWT's header name/value pairs as desired.
When finished, callers may return to JWT construction via the and()
method.
For example:
String jwt = Jwts.builder() .header() .keyId("keyId") .add("aName", aValue) .add(myHeaderMap) // ... etc ... .and()
//return back to the JwtBuilder .subject("Joe") // resume JwtBuilder calls // ... etc ... .compact();
JwtBuilder.BuilderHeader
to use for header construction.@Deprecated JwtBuilder setHeader(Map<String,?> map)
header()
.empty()
.add(map)
.and()
(to replace all header parameters) or
header()
.add(map)
.and()
to only append the map
entries. This method will be removed before the 1.0 release.header()
.empty()
.add(map)
.and()
If you do not want to replace the existing header and only want to append to it,
call
instead.header()
.add(map)
.and()
map
- the name/value pairs to set as (and potentially replace) the constructed JWT header.@Deprecated JwtBuilder setHeaderParams(Map<String,?> params)
header()
.add(map)
.and()
.
This method will be removed before the 1.0 release.header()
.add(map)
.and()
params
- the header name/value pairs to append to the header.@Deprecated JwtBuilder setHeaderParam(String name, Object value)
header()
.add(name, value)
.and()
.
This method will be removed before the 1.0 release.null
or empty, the parameter will
be removed from the header entirely. This is a wrapper method for:
header()
.add(name, value)
.and()
name
- the header parameter namevalue
- the header parameter value@Deprecated JwtBuilder setPayload(String payload)
content(String)
because both Claims and Content are technically 'payloads', so this method name is misleading. This method will
be removed before the 1.0 release.content(String)
. This method will be removed
before the 1.0 release.payload
- the string used to set UTF-8-encoded bytes as the JWT payload.content(String)
JwtBuilder content(String content)
content
(payload.getBytes(StandardCharsets.UTF_8))
Content Type Recommendation
Unless you are confident that the JWT recipient will always know to convert the payload bytes
to a UTF-8 string without additional metadata, it is strongly recommended to use the
content(String, String)
method instead of this one. That method ensures that a JWT recipient can
inspect the cty
header to know how to handle the payload bytes without ambiguity.
Mutually Exclusive Claims and Content
This method is mutually exclusive of the claim(String, Object)
and claims()
methods. Either claims
or content
method variants may be used, but not both. If you want the
JWT payload to be JSON claims, use the claim(String, Object)
or claims()
methods instead.
content
- the content string to use for the JWT payloadcontent(String, String)
,
content(byte[], String)
,
content(InputStream, String)
JwtBuilder content(byte[] content)
content
(new ByteArrayInputStream(content))
Content Type Recommendation
Unless you are confident that the JWT recipient will always know how to use the payload bytes
without additional metadata, it is strongly recommended to also set the
contentType
header. For example:
content(bytes).header()
.contentType(cty)
.and()
This ensures a JWT recipient can inspect the cty
header to know how to handle the payload bytes
without ambiguity.
Mutually Exclusive Claims and Content
This method is mutually exclusive of the claim(String, Object)
and claims()
methods. Either claims
or content
method variants may be used, but not both. If you want the
JWT payload to be JSON claims, use the claim(String, Object)
or claims()
methods instead.
content
- the content byte array to use as the JWT payloadcontent(byte[], String)
JwtBuilder content(InputStream in)
Content Type Recommendation
Unless you are confident that the JWT recipient will always know how to use the payload bytes
without additional metadata, it is strongly recommended to also set the
contentType
header. For example:
content(in).header()
.contentType(cty)
.and()
This ensures a JWT recipient can inspect the cty
header to know how to handle the payload bytes
without ambiguity.
Mutually Exclusive Claims and Content
This method is mutually exclusive of the claim(String, Object)
and claims()
methods. Either claims
or content
method variants may be used, but not both. If you want the
JWT payload to be JSON claims, use the claim(String, Object)
or claims()
methods instead.
in
- the input stream containing the bytes to use as the JWT payloadcontent(byte[], String)
JwtBuilder content(String content, String cty) throws IllegalArgumentException
contentType
header value to a compact cty
IANA Media Type
identifier to indicate the data format of the resulting byte array. The JWT recipient can inspect the
cty
value to determine how to convert the byte array to the final content type as desired. This is a
convenience method semantically equivalent to:
content(content)
.header()
.contentType(cty)
.and()
Compact Media Type Identifier
This method will automatically remove any application/
prefix from the
cty
string if possible according to the rules defined in the last paragraph of
RFC 7517, Section 4.1.10:
To keep messages compact in common situations, it is RECOMMENDED that producers omit an "application/" prefix of a media type value in a "cty" Header Parameter when no other '/' appears in the media type value. A recipient using the media type value MUST treat it as if "application/" were prepended to any "cty" value not containing a '/'. For instance, a "cty" value of "example" SHOULD be used to represent the "application/example" media type, whereas the media type "application/example;part="1/2"" cannot be shortened to "example;part="1/2"".
JJWT performs the reverse during JWT parsing: Header.getContentType()
will automatically prepend the
application/
prefix if the parsed cty
value does not contain a '/
' character (as
mandated by the RFC language above). This ensures application developers can use and read standard IANA Media
Type identifiers without needing JWT-specific prefix conditional logic in application code.
Mutually Exclusive Claims and Content
This method is mutually exclusive of the claim(String, Object)
and claims()
methods. Either claims
or content
method variants may be used, but not both. If you want the
JWT payload to be JSON claims, use the claim(String, Object)
or claims()
methods instead.
content
- the content byte array that will be the JWT payload. Cannot be null or empty.cty
- the content type (media type) identifier attributed to the byte array. Cannot be null or empty.IllegalArgumentException
- if either content
or cty
are null or empty.JwtBuilder content(byte[] content, String cty) throws IllegalArgumentException
contentType
header value to a compact cty
IANA Media Type
identifier to indicate the data format of the byte array. The JWT recipient can inspect the
cty
value to determine how to convert the byte array to the final content type as desired. This is a
convenience method semantically equivalent to:
content(content)
.header()
.contentType(cty)
.and()
Compact Media Type Identifier
This method will automatically remove any application/
prefix from the
cty
string if possible according to the rules defined in the last paragraph of
RFC 7517, Section 4.1.10:
To keep messages compact in common situations, it is RECOMMENDED that producers omit an "application/" prefix of a media type value in a "cty" Header Parameter when no other '/' appears in the media type value. A recipient using the media type value MUST treat it as if "application/" were prepended to any "cty" value not containing a '/'. For instance, a "cty" value of "example" SHOULD be used to represent the "application/example" media type, whereas the media type "application/example;part="1/2"" cannot be shortened to "example;part="1/2"".
JJWT performs the reverse during JWT parsing: Header.getContentType()
will automatically prepend the
application/
prefix if the parsed cty
value does not contain a '/
' character (as
mandated by the RFC language above). This ensures application developers can use and read standard IANA Media
Type identifiers without needing JWT-specific prefix conditional logic in application code.
Mutually Exclusive Claims and Content
This method is mutually exclusive of the claim(String, Object)
and claims()
methods. Either claims
or content
method variants may be used, but not both. If you want the
JWT payload to be JSON claims, use the claim(String, Object)
or claims()
methods instead.
content
- the content byte array that will be the JWT payload. Cannot be null or empty.cty
- the content type (media type) identifier attributed to the byte array. Cannot be null or empty.IllegalArgumentException
- if either content
or cty
are null or empty.JwtBuilder content(InputStream content, String cty) throws IllegalArgumentException
contentType
header value to a compact cty
IANA Media Type
identifier to indicate the data format of the byte array. The JWT recipient can inspect the
cty
value to determine how to convert the byte array to the final content type as desired. This is a
convenience method semantically equivalent to:
content(content)
.header()
.contentType(cty)
.and()
Compact Media Type Identifier
This method will automatically remove any application/
prefix from the
cty
string if possible according to the rules defined in the last paragraph of
RFC 7517, Section 4.1.10:
To keep messages compact in common situations, it is RECOMMENDED that producers omit an "application/" prefix of a media type value in a "cty" Header Parameter when no other '/' appears in the media type value. A recipient using the media type value MUST treat it as if "application/" were prepended to any "cty" value not containing a '/'. For instance, a "cty" value of "example" SHOULD be used to represent the "application/example" media type, whereas the media type "application/example;part="1/2"" cannot be shortened to "example;part="1/2"".
JJWT performs the reverse during JWT parsing: Header.getContentType()
will automatically prepend the
application/
prefix if the parsed cty
value does not contain a '/
' character (as
mandated by the RFC language above). This ensures application developers can use and read standard IANA Media
Type identifiers without needing JWT-specific prefix conditional logic in application code.
Mutually Exclusive Claims and Content
This method is mutually exclusive of the claim(String, Object)
and claims()
methods. Either claims
or content
method variants may be used, but not both. If you want the
JWT payload to be JSON claims, use the claim(String, Object)
or claims()
methods instead.
content
- the content byte array that will be the JWT payload. Cannot be null.cty
- the content type (media type) identifier attributed to the byte array. Cannot be null or empty.IllegalArgumentException
- if either content
or cty
are null or empty.JwtBuilder.BuilderClaims claims()
Claims
payload to modify as desired. When finished, callers may
return to JwtBuilder
configuration via the and()
method.
For example:
String jwt = Jwts.builder() .claims() .issuer("me") .subject("Joe") .audience().add("you").and() .add("customClaim", customValue) .add(myClaimsMap) // ... etc ... .and()
//return back to the JwtBuilder .signWith(key) // resume JwtBuilder calls // ... etc ... .compact();
JwtBuilder.BuilderClaims
to use for Claims construction.@Deprecated JwtBuilder setClaims(Map<String,?> claims)
claims()
builder.claims()
.empty()
.add(claims)
.and()
The content
and claims
properties are mutually exclusive - only one of the two variants
may be used.
claims
- the JWT Claims to be set as the JWT payload.claims()
,
content(String)
,
content(byte[])
,
content(InputStream)
@Deprecated JwtBuilder addClaims(Map<String,?> claims)
claims()
.add(Map)
.and()
.
This method will be removed before the 1.0 release.claims()
.add(claims)
.and()
The content and claims properties are mutually exclusive - only one of the two may be used.
claims
- the JWT Claims to be added to the JWT payload.JwtBuilder claim(String name, Object value)
null
or empty
value will remove the claim entirely. This is a convenience alias for:
claims()
.add(name, value)
.and()
name
- the JWT Claims property namevalue
- the value to set for the specified Claims property nameJwtBuilder claims(Map<String,?> claims)
null
or empty value, that claim will be removed from the
Claims. This is a convenience alias for:
claims()
.add(claims)
.and()
The content and claims properties are mutually exclusive - only one of the two may be used.
claims
- the JWT Claims to be added to the JWT payload.JwtBuilder issuer(String iss)
iss
(issuer) claim. A null
value will remove the property from the Claims.
This is a convenience wrapper for:
claims()
.issuer(iss)
.and()
issuer
in interface ClaimsMutator<JwtBuilder>
iss
- the JWT iss
value or null
to remove the property from the Claims map.JwtBuilder subject(String sub)
sub
(subject) claim. A null
value will remove the property from the Claims.
This is a convenience wrapper for:
claims()
.subject(sub)
.and()
subject
in interface ClaimsMutator<JwtBuilder>
sub
- the JWT sub
value or null
to remove the property from the Claims map.JwtBuilder expiration(Date exp)
exp
(expiration) claim. A null
value will remove the property from the Claims.
A JWT obtained after this timestamp should not be used.
This is a convenience wrapper for:
claims()
.expiration(exp)
.and()
expiration
in interface ClaimsMutator<JwtBuilder>
exp
- the JWT exp
value or null
to remove the property from the Claims map.JwtBuilder notBefore(Date nbf)
nbf
(not before) claim. A null
value will remove the property from the Claims.
A JWT obtained before this timestamp should not be used.
This is a convenience wrapper for:
claims()
.notBefore(nbf)
.and()
notBefore
in interface ClaimsMutator<JwtBuilder>
nbf
- the JWT nbf
value or null
to remove the property from the Claims map.JwtBuilder issuedAt(Date iat)
iat
(issued at) claim. A null
value will remove the property from the Claims.
The value is the timestamp when the JWT was created.
This is a convenience wrapper for:
claims()
.issuedAt(iat)
.and()
issuedAt
in interface ClaimsMutator<JwtBuilder>
iat
- the JWT iat
value or null
to remove the property from the Claims map.JwtBuilder id(String jti)
jti
(JWT ID) claim. A null
value will remove the property from the Claims.
The value is a CaSe-SenSiTiVe unique identifier for the JWT. If specified, this value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object. The ID can be used to prevent the JWT from being replayed.
This is a convenience wrapper for:
claims()
.id(jti)
.and()
id
in interface ClaimsMutator<JwtBuilder>
jti
- the JWT jti
(id) value or null
to remove the property from the Claims map.JwtBuilder signWith(Key key) throws InvalidKeyException
signWith(Key, SecureDigestAlgorithm)
instead.
If you are looking to invoke this method with a byte array that you are confident may be used for HMAC-SHA
algorithms, consider using Keys
.hmacShaKeyFor(bytes)
to
convert the byte array into a valid Key
.
Recommended Signature Algorithm
The recommended signature algorithm used with a given key is chosen based on the following:
If the Key is a: | And: | With a key size of: | The SignatureAlgorithm used will be: |
---|---|---|---|
SecretKey |
1 |
256 <= size <= 383 2 | HS256 |
SecretKey |
1 |
384 <= size <= 511 | HS384 |
SecretKey |
1 |
512 <= size | HS512 |
ECKey |
instanceof |
256 <= size <= 383 3 | ES256 |
ECKey |
instanceof |
384 <= size <= 520 4 | ES384 |
ECKey |
instanceof |
521 <= size 4 | ES512 |
RSAKey |
instanceof |
2048 <= size <= 3071 5,6 | RS256 |
RSAKey |
instanceof |
3072 <= size <= 4095 6 | RS384 |
RSAKey |
instanceof |
4096 <= size 5 | RS512 |
EdECKey7 | instanceof |
256 || 456 | EdDSA |
Notes:
SecretKey
instances must have an algorithm
name equal
to HmacSHA256
, HmacSHA384
or HmacSHA512
. If not, the key bytes might not be
suitable for HMAC signatures will be rejected with a InvalidKeyException
. SecretKey
s with key lengths less than 256 bits will be rejected with an
WeakKeyException
.ECKey
s with key lengths less than 256 bits will be rejected with a
WeakKeyException
.P-521
curve does indeed use keys of 521 bits, not 512 as might be expected. ECDSA
keys of 384 < size <= 520 are suitable for ES384, while ES512 requires keys >= 521 bits. The '512' part of the
ES512 name reflects the usage of the SHA-512 algorithm, not the ECDSA key length. ES512 with ECDSA keys less
than 521 bits will be rejected with a WeakKeyException
.RSAKey
s with key lengths less than 2048 bits will be rejected with a
WeakKeyException
.RS256
, RS384
, and
RS512
algorithms, so we assume an RSA signature algorithm based on the key
length to parallel similar decisions in the JWT specification for HMAC and ECDSA signature algorithms.
This is not required - just a convenience.This implementation does not use the PS256
,
PS384
, or PS512
RSA variants for any
specified RSAKey
because the the RS256
,
RS384
, and RS512
algorithms are
available in the JDK by default while the PS
* variants require either JDK 11 or an additional JCA
Provider (like BouncyCastle). If you wish to use a PS
* variant with your key, use the
signWith(Key, SecureDigestAlgorithm)
method instead.
Finally, this method will throw an InvalidKeyException
for any key that does not match the
heuristics and requirements documented above, since that inevitably means the Key is either insufficient,
unsupported, or explicitly disallowed by the JWT specification.
key
- the key to use for signingInvalidKeyException
- if the Key is insufficient, unsupported, or explicitly disallowed by the JWT
specification as described above in recommended signature algorithms.Jwts.SIG
,
signWith(Key, SecureDigestAlgorithm)
@Deprecated JwtBuilder signWith(SignatureAlgorithm alg, byte[] secretKey) throws InvalidKeyException
Keys
.hmacShaKeyFor(bytes)
to
obtain the Key
and then invoke signWith(Key)
or
signWith(Key, SecureDigestAlgorithm)
.
This method will be removed in the 1.0 release.Deprecation Notice: Deprecated as of 0.10.0
Use Keys
.hmacShaKeyFor(bytes)
to
obtain the Key
and then invoke signWith(Key)
or
signWith(Key, SecureDigestAlgorithm)
.
This method will be removed in the 1.0 release.
alg
- the JWS algorithm to use to digitally sign the JWT, thereby producing a JWS.secretKey
- the algorithm-specific signing key to use to digitally sign the JWT.InvalidKeyException
- if the Key is insufficient for the specified algorithm or explicitly disallowed by
the JWT specification.@Deprecated JwtBuilder signWith(SignatureAlgorithm alg, String base64EncodedSecretKey) throws InvalidKeyException
signWith(Key)
or signWith(Key, SignatureAlgorithm)
instead. This
method will be removed in the 1.0 release.This is a convenience method: the string argument is first BASE64-decoded to a byte array and this resulting
byte array is used to invoke signWith(SignatureAlgorithm, byte[])
.
Deprecation Notice: Deprecated as of 0.10.0, will be removed in the 1.0 release.
This method has been deprecated because the key
argument for this method can be confusing: keys for
cryptographic operations are always binary (byte arrays), and many people were confused as to how bytes were
obtained from the String argument.
This method always expected a String argument that was effectively the same as the result of the following (pseudocode):
String base64EncodedSecretKey = base64Encode(secretKeyBytes);
However, a non-trivial number of JJWT users were confused by the method signature and attempted to
use raw password strings as the key argument - for example with(HS256, myPassword)
- which is
almost always incorrect for cryptographic hashes and can produce erroneous or insecure results.
See this StackOverflow answer explaining why raw (non-base64-encoded) strings are almost always incorrect for signature operations.
To perform the correct logic with base64EncodedSecretKey strings with JJWT >= 0.10.0, you may do this:
byte[] keyBytes = Decoders
.BASE64
.decode(base64EncodedSecretKey)
;
Key key = Keys
.hmacShaKeyFor(keyBytes)
;
jwtBuilder.with(key); //or signWith(Key, SignatureAlgorithm)
This method will be removed in the 1.0 release.
alg
- the JWS algorithm to use to digitally sign the JWT, thereby producing a JWS.base64EncodedSecretKey
- the BASE64-encoded algorithm-specific signing key to use to digitally sign the
JWT.InvalidKeyException
- if the Key is insufficient or explicitly disallowed by the JWT specification as
described by SignatureAlgorithm.forSigningKey(Key)
.@Deprecated JwtBuilder signWith(SignatureAlgorithm alg, Key key) throws InvalidKeyException
signWith(Key, SecureDigestAlgorithm)
instead.
This method will be removed before the 1.0 release.It is typically recommended to call the signWith(Key)
instead for simplicity.
However, this method can be useful if the recommended algorithm heuristics do not meet your needs or if
you want explicit control over the signature algorithm used with the specified key.
alg
- the JWS algorithm to use to digitally sign the JWT, thereby producing a JWS.key
- the algorithm-specific signing key to use to digitally sign the JWT.InvalidKeyException
- if the Key is insufficient or explicitly disallowed by the JWT specification for
the specified algorithm.signWith(Key)
@Deprecated JwtBuilder signWith(Key key, SignatureAlgorithm alg) throws InvalidKeyException
signWith(Key, SecureDigestAlgorithm)
.Deprecation Notice
This has been deprecated since 0.12.0. Use
signWith(Key, SecureDigestAlgorithm)
instead. Standard JWA algorithms
are represented as instances of this new interface in the Jwts.SIG
algorithm registry.
Signs the constructed JWT with the specified key using the specified algorithm, producing a JWS.
It is typically recommended to call the signWith(Key)
instead for simplicity.
However, this method can be useful if the recommended algorithm heuristics do not meet your needs or if
you want explicit control over the signature algorithm used with the specified key.
key
- the signing key to use to digitally sign the JWT.alg
- the JWS algorithm to use with the key to digitally sign the JWT, thereby producing a JWS.InvalidKeyException
- if the Key is insufficient or explicitly disallowed by the JWT specification for
the specified algorithm.signWith(Key)
<K extends Key> JwtBuilder signWith(K key, SecureDigestAlgorithm<? super K,?> alg) throws InvalidKeyException
The Jwts.SIG
registry makes available all standard signature
algorithms defined in the JWA specification.
It is typically recommended to call the signWith(Key)
instead for simplicity.
However, this method can be useful if the recommended algorithm heuristics do not meet your needs or if
you want explicit control over the signature algorithm used with the specified key.
K
- The type of key accepted by the SignatureAlgorithm
.key
- the signing key to use to digitally sign the JWT.alg
- the JWS algorithm to use with the key to digitally sign the JWT, thereby producing a JWS.InvalidKeyException
- if the Key is insufficient or explicitly disallowed by the JWT specification for
the specified algorithm.signWith(Key)
,
Jwts.SIG
JwtBuilder encryptWith(SecretKey key, AeadAlgorithm enc)
key
using the provided enc
ryption
algorithm, producing a JWE. Because it is a symmetric key, the JWE recipient
must also have access to the same key to decrypt.
This method is a convenience method that delegates to
encryptWith(Key, KeyAlgorithm, AeadAlgorithm)
based on the key
argument:
key
is a Password
instance,
the KeyAlgorithm
used will be one of the three JWA-standard password-based key algorithms
(PBES2_HS256_A128KW
,
PBES2_HS384_A192KW
, or
PBES2_HS512_A256KW
) as determined by the enc
algorithm's
key length
requirement.key
is otherwise a standard SecretKey
, the KeyAlgorithm
will be
DIRECT
, indicating that key
should be used directly with the
enc
algorithm. In this case, the key
argument MUST be of sufficient strength to
use with the specified enc
algorithm, otherwise an exception will be thrown during encryption. If
desired, secure-random keys suitable for an AeadAlgorithm
may be generated using the algorithm's
key()
builder.key
- the symmetric encryption key to use with the enc
algorithm.enc
- the AeadAlgorithm
algorithm used to encrypt the JWE, usually one of the JWA-standard
algorithms accessible via Jwts.ENC
.Jwts.ENC
<K extends Key> JwtBuilder encryptWith(K key, KeyAlgorithm<? super K,?> keyAlg, AeadAlgorithm enc)
enc
algorithm with the symmetric key produced by the
keyAlg
when invoked with the given key
, producing a JWE.
This behavior can be illustrated by the following pseudocode, a rough example of what happens during
compact
ion:
SecretKey encryptionKey = keyAlg.getEncryptionKey(key); // (1) byte[] jweCiphertext = enc.encrypt(payloadBytes, encryptionKey); // (2)
keyAlg
argument is first invoked with the provided key
argument, resulting in a
SecretKey
.SecretKey
result is used to call the provided enc
encryption algorithm argument,
resulting in the final JWE ciphertext.Most application developers will reference one of the JWA
standard key algorithms
and standard encryption algorithms
when invoking this method, but custom implementations are also supported.
K
- the type of key that must be used with the specified keyAlg
instance.key
- the key used to invoke the provided keyAlg
instance.keyAlg
- the key management algorithm that will produce the symmetric SecretKey
to use with the
enc
algorithmenc
- the AeadAlgorithm
algorithm used to encrypt the JWEJwts.ENC
,
Jwts.KEY
JwtBuilder compressWith(CompressionAlgorithm alg)
CompressionAlgorithm
.
If your compact JWTs are large, and you want to reduce their total size during network transmission, this can be useful. For example, when embedding JWTs in URLs, some browsers may not support URLs longer than a certain length. Using compression can help ensure the compact JWT fits within that length. However, NOTE:
Compatibility Warning
The JWT family of specifications defines compression only for JWE (JSON Web Encryption) tokens. Even so, JJWT will also support compression for JWS tokens as well if you choose to use it. However, be aware that if you use compression when creating a JWS token, other libraries may not be able to parse that JWS token. When using compression for JWS tokens, be sure that all parties accessing the JWS token support compression for JWS.
Compression when creating JWE tokens however should be universally accepted for any library that supports JWE.
alg
- implementation of the CompressionAlgorithm
to be used.Jwts.ZIP
@Deprecated JwtBuilder base64UrlEncodeWith(Encoder<byte[],String> base64UrlEncoder)
b64Url(Encoder)
.compaction
with the specified Encoder.
JJWT uses a spec-compliant encoder that works on all supported JDK versions, but you may call this method to specify a different encoder if you desire.
base64UrlEncoder
- the encoder to use when Base64Url-encodingb64Url(Encoder)
JwtBuilder b64Url(Encoder<OutputStream,OutputStream> encoder)
compaction
with the specified OutputStream
Encoder.
The Encoder's encode
method will be given a target OutputStream
to
wrap, and the resulting (wrapping) OutputStream
will be used for writing, ensuring automatic
Base64URL-encoding during write operations.
JJWT uses a spec-compliant encoder that works on all supported JDK versions, but you may call this method to specify a different stream encoder if desired.
encoder
- the encoder to use when Base64Url-encodingJwtBuilder encodePayload(boolean b64)
false
, or standard JWT/JWS/JWE payload encoding otherwise. The default
value is true
per standard RFC behavior rules.
This value may only be false
for JWSs (signed JWTs). It may not be used for standard
(unprotected) JWTs or encrypted JWTs (JWEs). The builder will throw an exception during compact()
if
false
and a JWS is not being created.
b64
- whether to Base64URL-encode the JWS payload@Deprecated JwtBuilder serializeToJsonWith(Serializer<Map<String,?>> serializer)
json(Serializer)
If this method is not called, JJWT will use whatever serializer it can find at runtime, checking for the
presence of well-known implementations such Jackson, Gson, and org.json. If one of these is not found
in the runtime classpath, an exception will be thrown when the compact()
method is invoked.
serializer
- the serializer to use when converting Map objects to JSON strings.JwtBuilder json(Serializer<Map<String,?>> serializer)
If this method is not called, JJWT will use whatever Serializer it can find at runtime, checking for the
presence of well-known implementations such Jackson, Gson, and org.json. If one of these is not found
in the runtime classpath, an exception will be thrown when the compact()
method is invoked.
serializer
- the Serializer to use when converting Map objects to JSON strings.String compact()
Copyright © 2014–2025 jsonwebtoken.io. All rights reserved.