io.jsonwebtoken.JwtBuilder Maven / Gradle / Ivy
/*
* Copyright (C) 2014 jsonwebtoken.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jsonwebtoken;
import io.jsonwebtoken.io.CompressionAlgorithm;
import io.jsonwebtoken.io.Decoder;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoder;
import io.jsonwebtoken.io.Serializer;
import io.jsonwebtoken.lang.Conjunctor;
import io.jsonwebtoken.lang.MapMutator;
import io.jsonwebtoken.security.AeadAlgorithm;
import io.jsonwebtoken.security.InvalidKeyException;
import io.jsonwebtoken.security.KeyAlgorithm;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.Password;
import io.jsonwebtoken.security.SecureDigestAlgorithm;
import io.jsonwebtoken.security.WeakKeyException;
import io.jsonwebtoken.security.X509Builder;
import javax.crypto.SecretKey;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.interfaces.ECKey;
import java.security.interfaces.RSAKey;
import java.util.Date;
import java.util.Map;
/**
* A builder for constructing Unprotected JWTs, Signed JWTs (aka 'JWS's) and Encrypted JWTs (aka 'JWE's).
*
* @since 0.1
*/
public interface JwtBuilder extends ClaimsMutator {
/**
* Sets the JCA Provider to use during cryptographic signing or encryption operations, or {@code null} if the
* JCA subsystem preferred provider should be used.
*
* @param provider the JCA Provider to use during cryptographic signing or encryption operations, or {@code null} if the
* JCA subsystem preferred provider should be used.
* @return the builder for method chaining.
* @since 0.12.0
*/
JwtBuilder provider(Provider provider);
/**
* Sets the {@link SecureRandom} to use during cryptographic signing or encryption operations, or {@code null} if
* a default {@link SecureRandom} should be used.
*
* @param secureRandom the {@link SecureRandom} to use during cryptographic signing or encryption operations, or
* {@code null} if a default {@link SecureRandom} should be used.
* @return the builder for method chaining.
* @since 0.12.0
*/
JwtBuilder random(SecureRandom secureRandom);
/**
* Returns the {@code 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 {@link BuilderHeader#and() and()} method.
* For example:
*
*
* String jwt = Jwts.builder()
*
* .header()
* .keyId("keyId")
* .add("aName", aValue)
* .add(myHeaderMap)
* // ... etc ...
* .{@link BuilderHeader#and() and()} //return back to the JwtBuilder
*
* .subject("Joe") // resume JwtBuilder calls
* // ... etc ...
* .compact();
*
* @return the {@link BuilderHeader} to use for header construction.
* @since 0.12.0
*/
BuilderHeader header();
/**
* Per standard Java idiom 'setter' conventions, this method sets (and fully replaces) any existing header with the
* specified name/value pairs. This is a wrapper method for:
*
*
* {@link #header()}.{@link MapMutator#empty() empty()}.{@link MapMutator#add(Map) add(map)}.{@link BuilderHeader#and() and()}
*
* If you do not want to replace the existing header and only want to append to it,
* call {@link #header()}.{@link io.jsonwebtoken.lang.MapMutator#add(Map) add(map)}.{@link BuilderHeader#and() and()}
instead.
*
* @param map the name/value pairs to set as (and potentially replace) the constructed JWT header.
* @return the builder for method chaining.
* @deprecated since 0.12.0 in favor of
* {@link #header()}.{@link MapMutator#empty() empty()}.{@link MapMutator#add(Map) add(map)}.{@link BuilderHeader#and() and()}
* (to replace all header parameters) or
* {@link #header()}.{@link MapMutator#add(Map) add(map)}.{@link BuilderHeader#and() and()}
* to only append the {@code map} entries. This method will be removed before the 1.0 release.
*/
@SuppressWarnings("DeprecatedIsStillUsed")
@Deprecated
JwtBuilder setHeader(Map map);
/**
* Adds the specified name/value pairs to the header. Any parameter with an empty or null value will remove the
* entry from the header. This is a wrapper method for:
*
* {@link #header()}.{@link MapMutator#add(Map) add(map)}.{@link BuilderHeader#and() and()}
*
* @param params the header name/value pairs to append to the header.
* @return the builder for method chaining.
* @deprecated since 0.12.0 in favor of
* {@link #header()}.{@link MapMutator#add(Map) add(map)}.{@link BuilderHeader#and() and()}
.
* This method will be removed before the 1.0 release.
*/
@SuppressWarnings("DeprecatedIsStillUsed")
@Deprecated
JwtBuilder setHeaderParams(Map params);
/**
* Adds the specified name/value pair to the header. If the value is {@code null} or empty, the parameter will
* be removed from the header entirely. This is a wrapper method for:
*
* {@link #header()}.{@link MapMutator#add(Object, Object) add(name, value)}.{@link BuilderHeader#and() and()}
*
* @param name the header parameter name
* @param value the header parameter value
* @return the builder for method chaining.
* @deprecated since 0.12.0 in favor of
* {@link #header()}.{@link MapMutator#add(Object, Object) add(name, value)}.{@link BuilderHeader#and() and()}
.
* This method will be removed before the 1.0 release.
*/
@SuppressWarnings("DeprecatedIsStillUsed")
@Deprecated
JwtBuilder setHeaderParam(String name, Object value);
/**
* Since JJWT 0.12.0, this is an alias for {@link #content(String)}. This method will be removed
* before the 1.0 release.
*
* @param payload the string used to set UTF-8-encoded bytes as the JWT payload.
* @return the builder for method chaining.
* @see #content(String)
* @deprecated since JJWT_RELEASE VERSION in favor of {@link #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.
*/
@SuppressWarnings("DeprecatedIsStillUsed")
@Deprecated
JwtBuilder setPayload(String payload);
/**
* Sets the JWT payload to be the specified string's UTF-8 bytes. This is a convenience method semantically
* equivalent to calling:
*
*
* {@link #content(byte[]) 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
* {@link #content(String, String)} method instead of this one. That method ensures that a JWT recipient can
* inspect the {@code cty} header to know how to handle the payload bytes without ambiguity.
*
* Mutually Exclusive Claims and Content
*
* This method is mutually exclusive of the {@link #claim(String, Object)} and {@link #claims()}
* methods. Either {@code claims} or {@code content} method variants may be used, but not both. If you want the
* JWT payload to be JSON claims, use the {@link #claim(String, Object)} or {@link #claims()} methods instead.
*
* @param content the content string to use for the JWT payload
* @return the builder for method chaining.
* @see #content(String, String)
* @see #content(byte[], String)
* @see #content(InputStream, String)
* @since 0.12.0
*/
JwtBuilder content(String content);
/**
* Sets the JWT payload to be the specified content byte array. This is a convenience method semantically
* equivalent to calling:
*
* {@link #content(InputStream) 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
* {@link Header#getContentType() contentType} header. For example:
*
*
* content(bytes).{@link #header() header()}.{@link HeaderMutator#contentType(String) contentType(cty)}.{@link BuilderHeader#and() and()}
*
* This ensures a JWT recipient can inspect the {@code cty} header to know how to handle the payload bytes
* without ambiguity.
*
* Mutually Exclusive Claims and Content
*
* This method is mutually exclusive of the {@link #claim(String, Object)} and {@link #claims()}
* methods. Either {@code claims} or {@code content} method variants may be used, but not both. If you want the
* JWT payload to be JSON claims, use the {@link #claim(String, Object)} or {@link #claims()} methods instead.
*
* @param content the content byte array to use as the JWT payload
* @return the builder for method chaining.
* @see #content(byte[], String)
* @since 0.12.0
*/
JwtBuilder content(byte[] content);
/**
* Sets the JWT payload to be the bytes in the specified content stream.
*
* 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
* {@link HeaderMutator#contentType(String) contentType} header. For example:
*
*
* content(in).{@link #header() header()}.{@link HeaderMutator#contentType(String) contentType(cty)}.{@link BuilderHeader#and() and()}
*
* This ensures a JWT recipient can inspect the {@code cty} header to know how to handle the payload bytes
* without ambiguity.
*
* Mutually Exclusive Claims and Content
*
* This method is mutually exclusive of the {@link #claim(String, Object)} and {@link #claims()}
* methods. Either {@code claims} or {@code content} method variants may be used, but not both. If you want the
* JWT payload to be JSON claims, use the {@link #claim(String, Object)} or {@link #claims()} methods instead.
*
* @param in the input stream containing the bytes to use as the JWT payload
* @return the builder for method chaining.
* @see #content(byte[], String)
* @since 0.12.0
*/
JwtBuilder content(InputStream in);
/**
* Sets the JWT payload to be the specified String's UTF-8 bytes, and also sets the
* {@link HeaderMutator#contentType(String) contentType} header value to a compact {@code cty} IANA Media Type
* identifier to indicate the data format of the resulting byte array. The JWT recipient can inspect the
* {@code 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:
*
*
* {@link #content(String) content(content)}.{@link #header()}.{@link HeaderMutator#contentType(String) contentType(cty)}.{@link BuilderHeader#and() and()}
*
* Compact Media Type Identifier
*
* This method will automatically remove any application/
prefix from the
* {@code 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: {@link Header#getContentType()} will automatically prepend the
* {@code application/} prefix if the parsed {@code 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 {@link #claim(String, Object)} and {@link #claims()}
* methods. Either {@code claims} or {@code content} method variants may be used, but not both. If you want the
* JWT payload to be JSON claims, use the {@link #claim(String, Object)} or {@link #claims()} methods instead.
*
* @param content the content byte array that will be the JWT payload. Cannot be null or empty.
* @param cty the content type (media type) identifier attributed to the byte array. Cannot be null or empty.
* @return the builder for method chaining.
* @throws IllegalArgumentException if either {@code content} or {@code cty} are null or empty.
* @since 0.12.0
*/
JwtBuilder content(String content, String cty) throws IllegalArgumentException;
/**
* Sets the JWT payload to be the specified byte array, and also sets the
* {@link HeaderMutator#contentType(String) contentType} header value to a compact {@code cty} IANA Media Type
* identifier to indicate the data format of the byte array. The JWT recipient can inspect the
* {@code 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:
*
*
* {@link #content(byte[]) content(content)}.{@link #header()}.{@link HeaderMutator#contentType(String) contentType(cty)}.{@link BuilderHeader#and() and()}
*
* Compact Media Type Identifier
*
* This method will automatically remove any application/
prefix from the
* {@code 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: {@link Header#getContentType()} will automatically prepend the
* {@code application/} prefix if the parsed {@code 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 {@link #claim(String, Object)} and {@link #claims()}
* methods. Either {@code claims} or {@code content} method variants may be used, but not both. If you want the
* JWT payload to be JSON claims, use the {@link #claim(String, Object)} or {@link #claims()} methods instead.
*
* @param content the content byte array that will be the JWT payload. Cannot be null or empty.
* @param cty the content type (media type) identifier attributed to the byte array. Cannot be null or empty.
* @return the builder for method chaining.
* @throws IllegalArgumentException if either {@code content} or {@code cty} are null or empty.
* @since 0.12.0
*/
JwtBuilder content(byte[] content, String cty) throws IllegalArgumentException;
/**
* Sets the JWT payload to be the specified content byte stream and also sets the
* {@link BuilderHeader#contentType(String) contentType} header value to a compact {@code cty} IANA Media Type
* identifier to indicate the data format of the byte array. The JWT recipient can inspect the
* {@code 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:
*
*
* {@link #content(InputStream) content(content)}.{@link #header()}.{@link HeaderMutator#contentType(String) contentType(cty)}.{@link BuilderHeader#and() and()}
*
* Compact Media Type Identifier
*
* This method will automatically remove any application/
prefix from the
* {@code 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: {@link Header#getContentType()} will automatically prepend the
* {@code application/} prefix if the parsed {@code 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 {@link #claim(String, Object)} and {@link #claims()}
* methods. Either {@code claims} or {@code content} method variants may be used, but not both. If you want the
* JWT payload to be JSON claims, use the {@link #claim(String, Object)} or {@link #claims()} methods instead.
*
* @param content the content byte array that will be the JWT payload. Cannot be null.
* @param cty the content type (media type) identifier attributed to the byte array. Cannot be null or empty.
* @return the builder for method chaining.
* @throws IllegalArgumentException if either {@code content} or {@code cty} are null or empty.
* @since 0.12.0
*/
JwtBuilder content(InputStream content, String cty) throws IllegalArgumentException;
/**
* Returns the JWT {@code Claims} payload to modify as desired. When finished, callers may
* return to {@code JwtBuilder} configuration via the {@link BuilderClaims#and() and()} method.
* For example:
*
*
* String jwt = Jwts.builder()
*
* .claims()
* .issuer("me")
* .subject("Joe")
* .audience().add("you").and()
* .add("customClaim", customValue)
* .add(myClaimsMap)
* // ... etc ...
* .{@link BuilderClaims#and() and()} //return back to the JwtBuilder
*
* .signWith(key) // resume JwtBuilder calls
* // ... etc ...
* .compact();
*
* @return the {@link BuilderClaims} to use for Claims construction.
* @since 0.12.0
*/
BuilderClaims claims();
/**
* Replaces the JWT Claims payload with the specified name/value pairs. This is an alias for:
*
* {@link #claims()}.{@link MapMutator#empty() empty()}.{@link MapMutator#add(Map) add(claims)}.{@link BuilderClaims#and() and()}
*
* The {@code content} and {@code claims} properties are mutually exclusive - only one of the two variants
* may be used.
*
* @param claims the JWT Claims to be set as the JWT payload.
* @return the builder for method chaining.
* @see #claims()
* @see #content(String)
* @see #content(byte[])
* @see #content(InputStream)
* @deprecated since 0.12.0 in favor of using the {@link #claims()} builder.
*/
@SuppressWarnings("DeprecatedIsStillUsed")
@Deprecated
JwtBuilder setClaims(Map claims);
/**
* Adds/appends all given name/value pairs to the JSON Claims in the payload. This is an alias for:
*
*
* {@link #claims()}.{@link MapMutator#add(Map) add(claims)}.{@link BuilderClaims#and() and()}
*
* The content and claims properties are mutually exclusive - only one of the two may be used.
*
* @param claims the JWT Claims to be added to the JWT payload.
* @return the builder for method chaining.
* @since 0.8
* @deprecated since 0.12.0 in favor of
* {@link #claims()}.{@link BuilderClaims#add(Map) add(Map)}.{@link BuilderClaims#and() and()}
.
* This method will be removed before the 1.0 release.
*/
@SuppressWarnings("DeprecatedIsStillUsed")
@Deprecated
JwtBuilder addClaims(Map claims);
/**
* Sets a JWT claim, overwriting any existing claim with the same name. A {@code null} or empty
* value will remove the claim entirely. This is a convenience alias for:
*
* {@link #claims()}.{@link MapMutator#add(Object, Object) add(name, value)}.{@link BuilderClaims#and() and()}
*
* @param name the JWT Claims property name
* @param value the value to set for the specified Claims property name
* @return the builder instance for method chaining.
* @since 0.2
*/
JwtBuilder claim(String name, Object value);
/**
* Adds all given name/value pairs to the JSON Claims in the payload, overwriting any existing claims
* with the same names. If any name has a {@code null} or empty value, that claim will be removed from the
* Claims. This is a convenience alias for:
*
* {@link #claims()}.{@link MapMutator#add(Map) add(claims)}.{@link BuilderClaims#and() and()}
*
* The content and claims properties are mutually exclusive - only one of the two may be used.
*
* @param claims the JWT Claims to be added to the JWT payload.
* @return the builder instance for method chaining
* @since 0.12.0
*/
JwtBuilder claims(Map claims);
/**
* Sets the JWT Claims
* iss
(issuer) claim. A {@code null} value will remove the property from the Claims.
* This is a convenience wrapper for:
*
* {@link #claims()}.{@link ClaimsMutator#issuer(String) issuer(iss)}.{@link BuilderClaims#and() and()}
*
* @param iss the JWT {@code iss} value or {@code null} to remove the property from the Claims map.
* @return the builder instance for method chaining.
*/
@Override
// for better/targeted JavaDoc
JwtBuilder issuer(String iss);
/**
* Sets the JWT Claims
* sub
(subject) claim. A {@code null} value will remove the property from the Claims.
* This is a convenience wrapper for:
*
* {@link #claims()}.{@link ClaimsMutator#subject(String) subject(sub)}.{@link BuilderClaims#and() and()}
*
* @param sub the JWT {@code sub} value or {@code null} to remove the property from the Claims map.
* @return the builder instance for method chaining.
*/
@Override
// for better/targeted JavaDoc
JwtBuilder subject(String sub);
/**
* Sets the JWT Claims
* exp
(expiration) claim. A {@code 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:
*
* {@link #claims()}.{@link ClaimsMutator#expiration(Date) expiration(exp)}.{@link BuilderClaims#and() and()}
*
* @param exp the JWT {@code exp} value or {@code null} to remove the property from the Claims map.
* @return the builder instance for method chaining.
*/
@Override
// for better/targeted JavaDoc
JwtBuilder expiration(Date exp);
/**
* Sets the JWT Claims
* nbf
(not before) claim. A {@code 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:
*
* {@link #claims()}.{@link ClaimsMutator#notBefore(Date) notBefore(nbf)}.{@link BuilderClaims#and() and()}
*
* @param nbf the JWT {@code nbf} value or {@code null} to remove the property from the Claims map.
* @return the builder instance for method chaining.
*/
@Override
// for better/targeted JavaDoc
JwtBuilder notBefore(Date nbf);
/**
* Sets the JWT Claims
* iat
(issued at) claim. A {@code 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:
*
* {@link #claims()}.{@link ClaimsMutator#issuedAt(Date) issuedAt(iat)}.{@link BuilderClaims#and() and()}
*
* @param iat the JWT {@code iat} value or {@code null} to remove the property from the Claims map.
* @return the builder instance for method chaining.
*/
@Override
// for better/targeted JavaDoc
JwtBuilder issuedAt(Date iat);
/**
* Sets the JWT Claims
* jti
(JWT ID) claim. A {@code 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:
*
* {@link #claims()}.{@link ClaimsMutator#id(String) id(jti)}.{@link BuilderClaims#and() and()}
*
* @param jti the JWT {@code jti} (id) value or {@code null} to remove the property from the Claims map.
* @return the builder instance for method chaining.
*/
@Override
// for better/targeted JavaDoc
JwtBuilder id(String jti);
/**
* Signs the constructed JWT with the specified key using the key's recommended signature algorithm
* as defined below, producing a JWS. If the recommended signature algorithm isn't sufficient for your needs,
* consider using {@link #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 {@link Keys Keys}.{@link Keys#hmacShaKeyFor(byte[]) hmacShaKeyFor(bytes)} to
* convert the byte array into a valid {@code Key}.
*
* Recommended Signature Algorithm
*
* The recommended signature algorithm used with a given key is chosen based on the following:
*
* Key Recommended Signature Algorithm
*
*
* If the Key is a:
* And:
* With a key size of:
* The SignatureAlgorithm used will be:
*
*
*
*
* {@link SecretKey}
* {@link Key#getAlgorithm() getAlgorithm()}.equals("HmacSHA256")
1
* 256 <= size <= 383 2
* {@link Jwts.SIG#HS256 HS256}
*
*
* {@link SecretKey}
* {@link Key#getAlgorithm() getAlgorithm()}.equals("HmacSHA384")
1
* 384 <= size <= 511
* {@link Jwts.SIG#HS384 HS384}
*
*
* {@link SecretKey}
* {@link Key#getAlgorithm() getAlgorithm()}.equals("HmacSHA512")
1
* 512 <= size
* {@link Jwts.SIG#HS512 HS512}
*
*
* {@link ECKey}
* instanceof {@link PrivateKey}
* 256 <= size <= 383 3
* {@link Jwts.SIG#ES256 ES256}
*
*
* {@link ECKey}
* instanceof {@link PrivateKey}
* 384 <= size <= 520 4
* {@link Jwts.SIG#ES384 ES384}
*
*
* {@link ECKey}
* instanceof {@link PrivateKey}
* 521 <= size 4
* {@link Jwts.SIG#ES512 ES512}
*
*
* {@link RSAKey}
* instanceof {@link PrivateKey}
* 2048 <= size <= 3071 5,6
* {@link Jwts.SIG#RS256 RS256}
*
*
* {@link RSAKey}
* instanceof {@link PrivateKey}
* 3072 <= size <= 4095 6
* {@link Jwts.SIG#RS384 RS384}
*
*
* {@link RSAKey}
* instanceof {@link PrivateKey}
* 4096 <= size 5
* {@link Jwts.SIG#RS512 RS512}
*
*
* EdECKey7
* instanceof {@link PrivateKey}
* 256 || 456
* {@link Jwts.SIG#EdDSA EdDSA}
*
*
*
* Notes:
*
* - {@code SecretKey} instances must have an {@link Key#getAlgorithm() algorithm} name equal
* to {@code HmacSHA256}, {@code HmacSHA384} or {@code HmacSHA512}. If not, the key bytes might not be
* suitable for HMAC signatures will be rejected with a {@link InvalidKeyException}.
* - The JWT JWA Specification (RFC 7518,
* Section 3.2) mandates that HMAC-SHA-* signing keys MUST be 256 bits or greater.
* {@code SecretKey}s with key lengths less than 256 bits will be rejected with an
* {@link WeakKeyException}.
* - The JWT JWA Specification (RFC 7518,
* Section 3.4) mandates that ECDSA signing key lengths MUST be 256 bits or greater.
* {@code ECKey}s with key lengths less than 256 bits will be rejected with a
* {@link WeakKeyException}.
* - The ECDSA {@code 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 {@link WeakKeyException}.
* - The JWT JWA Specification (RFC 7518,
* Section 3.3) mandates that RSA signing key lengths MUST be 2048 bits or greater.
* {@code RSAKey}s with key lengths less than 2048 bits will be rejected with a
* {@link WeakKeyException}.
* - Technically any RSA key of length >= 2048 bits may be used with the
* {@link Jwts.SIG#RS256 RS256}, {@link Jwts.SIG#RS384 RS384}, and
* {@link Jwts.SIG#RS512 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.
* - EdECKeys
* require JDK >= 15 or BouncyCastle in the runtime classpath.
*
*
* This implementation does not use the {@link Jwts.SIG#PS256 PS256},
* {@link Jwts.SIG#PS384 PS384}, or {@link Jwts.SIG#PS512 PS512} RSA variants for any
* specified {@link RSAKey} because the the {@link Jwts.SIG#RS256 RS256},
* {@link Jwts.SIG#RS384 RS384}, and {@link Jwts.SIG#RS512 RS512} algorithms are
* available in the JDK by default while the {@code PS}* variants require either JDK 11 or an additional JCA
* Provider (like BouncyCastle). If you wish to use a {@code PS}* variant with your key, use the
* {@link #signWith(Key, SecureDigestAlgorithm)} method instead.
*
* Finally, this method will throw an {@link 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.
*
* @param key the key to use for signing
* @return the builder instance for method chaining.
* @throws InvalidKeyException if the Key is insufficient, unsupported, or explicitly disallowed by the JWT
* specification as described above in recommended signature algorithms.
* @see Jwts.SIG
* @see #signWith(Key, SecureDigestAlgorithm)
* @since 0.10.0
*/
JwtBuilder signWith(Key key) throws InvalidKeyException;
/**
* Signs the constructed JWT using the specified algorithm with the specified key, producing a JWS.
*
* Deprecation Notice: Deprecated as of 0.10.0
*
* Use {@link Keys Keys}.{@link Keys#hmacShaKeyFor(byte[]) hmacShaKeyFor(bytes)} to
* obtain the {@code Key} and then invoke {@link #signWith(Key)} or
* {@link #signWith(Key, SecureDigestAlgorithm)}.
*
* This method will be removed in the 1.0 release.
*
* @param alg the JWS algorithm to use to digitally sign the JWT, thereby producing a JWS.
* @param secretKey the algorithm-specific signing key to use to digitally sign the JWT.
* @return the builder for method chaining.
* @throws InvalidKeyException if the Key is insufficient for the specified algorithm or explicitly disallowed by
* the JWT specification.
* @deprecated as of 0.10.0: use {@link Keys Keys}.{@link Keys#hmacShaKeyFor(byte[]) hmacShaKeyFor(bytes)} to
* obtain the {@code Key} and then invoke {@link #signWith(Key)} or
* {@link #signWith(Key, SecureDigestAlgorithm)}.
* This method will be removed in the 1.0 release.
*/
@Deprecated
JwtBuilder signWith(SignatureAlgorithm alg, byte[] secretKey) throws InvalidKeyException;
/**
* Signs the constructed JWT using the specified algorithm with the specified key, producing a JWS.
*
* 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 {@link #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 {@code 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):
*
* {@code 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 {@code 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 = {@link Decoders Decoders}.{@link Decoders#BASE64 BASE64}.{@link Decoder#decode(Object) decode(base64EncodedSecretKey)};
* Key key = {@link Keys Keys}.{@link Keys#hmacShaKeyFor(byte[]) hmacShaKeyFor(keyBytes)};
* jwtBuilder.with(key); //or {@link #signWith(Key, SignatureAlgorithm)}
*
*
* This method will be removed in the 1.0 release.
*
* @param alg the JWS algorithm to use to digitally sign the JWT, thereby producing a JWS.
* @param base64EncodedSecretKey the BASE64-encoded algorithm-specific signing key to use to digitally sign the
* JWT.
* @return the builder for method chaining.
* @throws InvalidKeyException if the Key is insufficient or explicitly disallowed by the JWT specification as
* described by {@link SignatureAlgorithm#forSigningKey(Key)}.
* @deprecated as of 0.10.0: use {@link #signWith(Key)} or {@link #signWith(Key, SignatureAlgorithm)} instead. This
* method will be removed in the 1.0 release.
*/
@Deprecated
JwtBuilder signWith(SignatureAlgorithm alg, String base64EncodedSecretKey) throws InvalidKeyException;
/**
* Signs the constructed JWT using the specified algorithm with the specified key, producing a JWS.
*
* It is typically recommended to call the {@link #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.
*
* @param alg the JWS algorithm to use to digitally sign the JWT, thereby producing a JWS.
* @param key the algorithm-specific signing key to use to digitally sign the JWT.
* @return the builder for method chaining.
* @throws InvalidKeyException if the Key is insufficient or explicitly disallowed by the JWT specification for
* the specified algorithm.
* @see #signWith(Key)
* @deprecated since 0.10.0. Use {@link #signWith(Key, SecureDigestAlgorithm)} instead.
* This method will be removed before the 1.0 release.
*/
@Deprecated
JwtBuilder signWith(SignatureAlgorithm alg, Key key) throws InvalidKeyException;
/**
* Deprecation Notice
*
* This has been deprecated since 0.12.0. Use
* {@link #signWith(Key, SecureDigestAlgorithm)} instead. Standard JWA algorithms
* are represented as instances of this new interface in the {@link 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 {@link #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.
*
* @param key the signing key to use to digitally sign the JWT.
* @param alg the JWS algorithm to use with the key to digitally sign the JWT, thereby producing a JWS.
* @return the builder for method chaining.
* @throws InvalidKeyException if the Key is insufficient or explicitly disallowed by the JWT specification for
* the specified algorithm.
* @see #signWith(Key)
* @since 0.10.0
* @deprecated since 0.12.0 to use the more flexible {@link #signWith(Key, SecureDigestAlgorithm)}.
*/
@Deprecated
JwtBuilder signWith(Key key, SignatureAlgorithm alg) throws InvalidKeyException;
/**
* Signs the constructed JWT with the specified key using the specified algorithm, producing a JWS.
*
* The {@link Jwts.SIG} registry makes available all standard signature
* algorithms defined in the JWA specification.
*
* It is typically recommended to call the {@link #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.
*
* @param key the signing key to use to digitally sign the JWT.
* @param The type of key accepted by the {@code SignatureAlgorithm}.
* @param alg the JWS algorithm to use with the key to digitally sign the JWT, thereby producing a JWS.
* @return the builder for method chaining.
* @throws InvalidKeyException if the Key is insufficient or explicitly disallowed by the JWT specification for
* the specified algorithm.
* @see #signWith(Key)
* @see Jwts.SIG
* @since 0.12.0
*/
JwtBuilder signWith(K key, SecureDigestAlgorithm super K, ?> alg) throws InvalidKeyException;
/**
* Encrypts the constructed JWT with the specified symmetric {@code key} using the provided {@code 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
* {@link #encryptWith(Key, KeyAlgorithm, AeadAlgorithm) encryptWith(Key, KeyAlgorithm, AeadAlgorithm)}
* based on the {@code key} argument:
*
* - If the provided {@code key} is a {@link Password Password} instance,
* the {@code KeyAlgorithm} used will be one of the three JWA-standard password-based key algorithms
* ({@link Jwts.KEY#PBES2_HS256_A128KW PBES2_HS256_A128KW},
* {@link Jwts.KEY#PBES2_HS384_A192KW PBES2_HS384_A192KW}, or
* {@link Jwts.KEY#PBES2_HS512_A256KW PBES2_HS512_A256KW}) as determined by the {@code enc} algorithm's
* {@link AeadAlgorithm#getKeyBitLength() key length} requirement.
* - If the {@code key} is otherwise a standard {@code SecretKey}, the {@code KeyAlgorithm} will be
* {@link Jwts.KEY#DIRECT DIRECT}, indicating that {@code key} should be used directly with the
* {@code enc} algorithm. In this case, the {@code key} argument MUST be of sufficient strength to
* use with the specified {@code enc} algorithm, otherwise an exception will be thrown during encryption. If
* desired, secure-random keys suitable for an {@link AeadAlgorithm} may be generated using the algorithm's
* {@link AeadAlgorithm#key() key()} builder.
*
*
* @param key the symmetric encryption key to use with the {@code enc} algorithm.
* @param enc the {@link AeadAlgorithm} algorithm used to encrypt the JWE, usually one of the JWA-standard
* algorithms accessible via {@link Jwts.ENC}.
* @return the JWE builder for method chaining.
* @see Jwts.ENC
*/
JwtBuilder encryptWith(SecretKey key, AeadAlgorithm enc);
/**
* Encrypts the constructed JWT using the specified {@code enc} algorithm with the symmetric key produced by the
* {@code keyAlg} when invoked with the given {@code key}, producing a JWE.
*
* This behavior can be illustrated by the following pseudocode, a rough example of what happens during
* {@link #compact() compact}ion:
*
* SecretKey encryptionKey = keyAlg.getEncryptionKey(key); // (1)
* byte[] jweCiphertext = enc.encrypt(payloadBytes, encryptionKey); // (2)
*
* - The {@code keyAlg} argument is first invoked with the provided {@code key} argument, resulting in a
* {@link SecretKey}.
* - This {@code SecretKey} result is used to call the provided {@code enc} encryption algorithm argument,
* resulting in the final JWE ciphertext.
*
*
* Most application developers will reference one of the JWA
* {@link Jwts.KEY standard key algorithms} and {@link Jwts.ENC standard encryption algorithms}
* when invoking this method, but custom implementations are also supported.
*
* @param the type of key that must be used with the specified {@code keyAlg} instance.
* @param key the key used to invoke the provided {@code keyAlg} instance.
* @param keyAlg the key management algorithm that will produce the symmetric {@code SecretKey} to use with the
* {@code enc} algorithm
* @param enc the {@link AeadAlgorithm} algorithm used to encrypt the JWE
* @return the JWE builder for method chaining.
* @see Jwts.ENC
* @see Jwts.KEY
*/
JwtBuilder encryptWith(K key, KeyAlgorithm super K, ?> keyAlg, AeadAlgorithm enc);
/**
* Compresses the JWT payload using the specified {@link 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.
*
* @param alg implementation of the {@link CompressionAlgorithm} to be used.
* @return the builder for method chaining.
* @see Jwts.ZIP
* @since 0.12.0
*/
JwtBuilder compressWith(CompressionAlgorithm alg);
/**
* Perform Base64Url encoding during {@link #compact() 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.
*
* @param base64UrlEncoder the encoder to use when Base64Url-encoding
* @return the builder for method chaining.
* @see #b64Url(Encoder)
* @since 0.10.0
* @deprecated since 0.12.0 in favor of {@link #b64Url(Encoder)}.
*/
@SuppressWarnings("DeprecatedIsStillUsed")
@Deprecated
JwtBuilder base64UrlEncodeWith(Encoder base64UrlEncoder);
/**
* Perform Base64Url encoding during {@link #compact() compaction} with the specified {@code OutputStream} Encoder.
* The Encoder's {@link Encoder#encode(Object) encode} method will be given a target {@code OutputStream} to
* wrap, and the resulting (wrapping) {@code 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.
*
* @param encoder the encoder to use when Base64Url-encoding
* @return the builder for method chaining.
* @since 0.12.0
*/
JwtBuilder b64Url(Encoder encoder);
/**
* Enables RFC 7797: JSON Web Signature (JWS)
* Unencoded Payload Option if {@code false}, or standard JWT/JWS/JWE payload encoding otherwise. The default
* value is {@code true} per standard RFC behavior rules.
*
* This value may only be {@code 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 {@link #compact()} if
* {@code false} and a JWS is not being created.
*
* @param b64 whether to Base64URL-encode the JWS payload
* @return the builder for method chaining.
*/
JwtBuilder encodePayload(boolean b64);
/**
* Performs Map-to-JSON serialization with the specified Serializer. This is used by the builder to convert
* JWT/JWS/JWE headers and claims Maps to JSON strings as required by the JWT specification.
*
* 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 {@link #compact()} method is invoked.
*
* @param serializer the serializer to use when converting Map objects to JSON strings.
* @return the builder for method chaining.
* @since 0.10.0
* @deprecated since 0.12.0 in favor of {@link #json(Serializer)}
*/
@SuppressWarnings("DeprecatedIsStillUsed")
@Deprecated
JwtBuilder serializeToJsonWith(Serializer