feat: added ECDSA-based algorithm support

make the simple-jwt auth0 implementation can use ECDSA-based algorithms

BREAKING CHANGE: the io.jsonwebtoken:jjwt implementation was
discontinued since its design made a big challenge to encapsulation
This commit is contained in:
zihluwang
2024-08-06 22:02:00 +08:00
parent 62b8cb8118
commit fe88788611
21 changed files with 344 additions and 1477 deletions
+3 -3
View File
@@ -15,9 +15,9 @@
# limitations under the License.
#
jacksonVersion=2.17.0
jacksonVersion=2.17.2
javaJwtVersion=4.4.0
jjwtVersion=0.12.5
jjwtVersion=0.12.6
junitVersion=5.10.2
logbackVersion=1.5.4
lombokVersion=1.18.30
@@ -26,7 +26,7 @@ springVersion=6.1.3
springBootVersion=3.2.3
buildGroupId=com.onixbyte
buildVersion=1.5.0
buildVersion=1.6.0
projectUrl=https://onixbyte.com/JDevKit
projectGithubUrl=https://github.com/OnixByte/JDevKit
licenseName=The Apache License, Version 2.0
+2 -4
View File
@@ -20,13 +20,11 @@ rootProject.name = "JDevKit"
include(
"devkit-core",
"devkit-utils",
"map-util-unsafe",
"guid",
"webcal",
"key-pair-loader",
"simple-jwt-facade",
"simple-jwt-authzero",
"simple-jwt-jjwt",
"simple-jwt-spring-boot-starter",
"property-guard-spring-boot-starter"
)
include("map-util-unsafe")
include("key-pair-loader")
@@ -19,13 +19,11 @@ package com.onixbyte.simplejwt.authzero;
import com.onixbyte.devkit.utils.Base64Util;
import com.onixbyte.guid.GuidCreator;
import com.onixbyte.simplejwt.SecretCreator;
import com.onixbyte.security.KeyLoader;
import com.onixbyte.simplejwt.TokenPayload;
import com.onixbyte.simplejwt.TokenResolver;
import com.onixbyte.simplejwt.annotations.ExcludeFromPayload;
import com.onixbyte.simplejwt.annotations.TokenEnum;
import com.onixbyte.simplejwt.authzero.config.AuthzeroTokenResolverConfig;
import com.onixbyte.simplejwt.config.TokenResolverConfig;
import com.onixbyte.simplejwt.constants.PredefinedKeys;
import com.onixbyte.simplejwt.constants.TokenAlgorithm;
import com.auth0.jwt.JWT;
@@ -37,13 +35,20 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.onixbyte.simplejwt.exceptions.IllegalKeyPairException;
import com.onixbyte.simplejwt.exceptions.IllegalSecretException;
import com.onixbyte.simplejwt.exceptions.UnsupportedAlgorithmException;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.InvocationTargetException;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* The {@code AuthzeroTokenResolver} class is an implementation of the {@link TokenResolver}
@@ -97,110 +102,160 @@ import java.util.*;
public class AuthzeroTokenResolver implements TokenResolver<DecodedJWT> {
/**
* Creates a new instance of {@code AuthzeroTokenResolver} with the provided configurations.
* Create a builder of {@link AuthzeroTokenResolver}.
*
* @param jtiCreator the {@link GuidCreator} used for generating unique identifiers for "jti"
* claim in JWT tokens
* @param algorithm the algorithm used for signing and verifying JWT tokens
* @param issuer the issuer claim value to be included in JWT tokens
* @param privateKey the secret used for HMAC-based algorithms (HS256, HS384, HS512) for
* token signing and verification, or the private key for ECDSA-based
* algorithms
* @param publicKey the public key for ECDSA-based algorithms
* @param objectMapper JSON handler
* @return a builder instance
*/
public AuthzeroTokenResolver(GuidCreator<?> jtiCreator,
TokenAlgorithm algorithm,
String issuer,
String privateKey,
String publicKey,
ObjectMapper objectMapper) {
if (TokenResolverConfig.HMAC_ALGORITHMS.contains(algorithm)) {
if (privateKey == null || privateKey.isBlank()) {
throw new IllegalArgumentException("A secret is required to build a JSON Web Token.");
}
public static Builder builder() {
return new Builder();
}
if (privateKey.length() < 32) {
log.warn("The provided secret which owns {} characters is too weak. Please consider" +
" replacing it with a stronger one.", privateKey.length());
}
/**
* Builder for {@link AuthzeroTokenResolver}
*/
public static class Builder {
/**
* GuidCreator used for generating unique identifiers for "jti" claim in JWT tokens.
*/
private GuidCreator<?> jtiCreator;
/**
* The algorithm used for signing and verifying JWT tokens.
*/
private Algorithm algorithm;
/**
* The issuer claim value to be included in JWT tokens.
*/
private String issuer;
/**
* Jackson JSON handler.
*/
private ObjectMapper objectMapper;
/**
* The secret to sign a JWT with HMAC based algorithm.
*/
private String secret;
/**
* The private key to sign a JWT with ECDSA based algorithm.
*/
private ECPrivateKey privateKey;
/**
* The public key to read a JWT with ECDSA based algorithm.
*/
private ECPublicKey publicKey;
/**
* Private constructor prevents this class being initialised at somewhere it should not
* be initialised.
*/
private Builder() {
}
this.jtiCreator = jtiCreator;
this.algorithm = config
.getAlgorithm(algorithm)
.apply(privateKey, publicKey);
this.issuer = issuer;
this.verifier = JWT.require(this.algorithm).build();
this.objectMapper = objectMapper;
}
/**
* Set the secret to sign a JWT.
*
* @param secret the secret
* @return the builder instance
*/
public Builder secret(String secret) {
this.secret = secret;
return this;
}
/**
* Creates a new instance of {@link AuthzeroTokenResolver} with the provided configurations
* and a simple UUID GuidCreator.
*
* @param algorithm the algorithm used for signing and verifying JWT tokens
* @param issuer the issuer claim value to be included in JWT tokens
* @param privateKey the secret used for HMAC-based algorithms (HS256, HS384, HS512) for
* token signing and verification, or the private key for ECDSA-based
* algorithms
* @param publicKey the public key for ECDSA-based algorithms
* @param objectMapper Jackson Databind JSON Handler
*/
public AuthzeroTokenResolver(TokenAlgorithm algorithm,
String issuer,
String privateKey,
String publicKey,
ObjectMapper objectMapper) {
this(UUID::randomUUID, algorithm, issuer, privateKey, publicKey, objectMapper);
}
/**
* Set the key pair to sign a JWT.
*
* @param publicKey the pem formatted public key text
* @param privateKey the pem formatted private key text
* @return the builder instance
*/
public Builder keyPair(String publicKey, String privateKey) {
this.publicKey = KeyLoader.loadEcdsaPublicKey(publicKey);
this.privateKey = KeyLoader.loadEcdsaPrivateKey(privateKey);
return this;
}
/**
* Creates a new instance of {@link AuthzeroTokenResolver} with the provided configurations
* and a simple UUID GuidCreator.
*
* @param algorithm the algorithm used for signing and verifying JWT tokens
* @param issuer the issuer claim value to be included in JWT tokens
* @param privateKey the secret used for HMAC-based algorithms (HS256, HS384, HS512) for
* token signing and verification, or the private key for ECDSA-based
* algorithms
* @param publicKey the public key for ECDSA-based algorithms
*/
public AuthzeroTokenResolver(TokenAlgorithm algorithm, String issuer, String privateKey, String publicKey) {
this(UUID::randomUUID, algorithm, issuer, privateKey, publicKey, new ObjectMapper());
}
/**
* Set the algorithm to sign a JWT.
* <p>
* A secret required by HMAC-based algorithms, or key pair required by ECDSA-based
* algorithms need to be set before initialise an algorithm.
*
* @param algorithm an {@link TokenAlgorithm} value
* @return the builder instance
*/
public Builder algorithm(TokenAlgorithm algorithm) {
// check the secret or key pair before algorithm initialised
if (HMAC_ALGORITHMS.containsKey(algorithm)) {
if (Objects.isNull(secret) || secret.isBlank()) {
throw new IllegalSecretException("""
Please specify a secret before define an algorithm.""");
}
} else if (ECDSA_ALGORITHMS.containsKey(algorithm)) {
if (Objects.isNull(publicKey) || Objects.isNull(privateKey)) {
throw new IllegalKeyPairException("""
Please specify a ECDSA key pair before define an algorithm.""");
}
}
/**
* Creates a new instance of {@link AuthzeroTokenResolver} with the
* provided configurations, HMAC256 algorithm and a simple
* UUID GuidCreator.
*
* @param issuer the issuer claim value to be included in JWT tokens
* @param secret the secret used for HS256 algorithms for token signing and verification
*/
public AuthzeroTokenResolver(String issuer, String secret) {
this(UUID::randomUUID, TokenAlgorithm.HS256, issuer, secret, "", new ObjectMapper());
}
// initialise algorithm
this.algorithm = switch (algorithm) {
case HS256, HS384, HS512 -> HMAC_ALGORITHMS.get(algorithm).apply(secret);
case ES256, ES384, ES512 -> ECDSA_ALGORITHMS.get(algorithm)
.apply(publicKey, privateKey);
default -> throw new UnsupportedAlgorithmException("""
This algorithm is not supported yet.""");
};
return this;
}
/**
* Creates a new instance of {@link AuthzeroTokenResolver} with the
* provided configurations, HMAC256 algorithm and a simple
* UUID GuidCreator.
*
* @param issuer the issuer claim value to be included in JWT tokens
*/
public AuthzeroTokenResolver(String issuer) {
var secret = SecretCreator.createSecret(32, true, true, true);
/**
* Set the object mapper.
*
* @param objectMapper an object mapper
* @return the builder instance
*/
public Builder objectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
return this;
}
this.jtiCreator = UUID::randomUUID;
this.algorithm = config
.getAlgorithm(TokenAlgorithm.HS256)
.apply(secret, "");
this.issuer = issuer;
this.verifier = JWT.require(this.algorithm).build();
this.objectMapper = new ObjectMapper();
/**
* Set the creator of JWT id.
*
* @param jtiCreator a creator to create JWT id
* @return the builder instance
*/
public Builder jtiCreator(GuidCreator<?> jtiCreator) {
this.jtiCreator = jtiCreator;
return this;
}
log.info("The secret has been set to {}.", secret);
/**
* Set the issuer of created JWT.
*
* @param issuer the person or organisation issued this JWT
* @return the builder instance
*/
public Builder issuer(String issuer) {
this.issuer = issuer;
return this;
}
/**
* Create an {@link AuthzeroTokenResolver} instance
*
* @return created instance
*/
public AuthzeroTokenResolver build() {
return new AuthzeroTokenResolver(jtiCreator, algorithm, issuer, objectMapper);
}
}
/**
@@ -251,7 +306,7 @@ public class AuthzeroTokenResolver implements TokenResolver<DecodedJWT> {
*/
@Override
public <T extends TokenPayload> String createToken(Duration expireAfter, String audience, String subject, T payload) {
final JWTCreator.Builder builder = JWT.create();
final var builder = JWT.create();
buildBasicInfo(builder, expireAfter, subject, audience);
var payloadClass = payload.getClass();
@@ -294,7 +349,7 @@ public class AuthzeroTokenResolver implements TokenResolver<DecodedJWT> {
*/
@Override
public DecodedJWT resolve(String token) {
return verifier.verify(token);
return jwtVerifier.verify(token);
}
/**
@@ -450,15 +505,15 @@ public class AuthzeroTokenResolver implements TokenResolver<DecodedJWT> {
// bind issuer (iss)
builder.withIssuer(issuer);
// bind issued at (iat)
builder.withIssuedAt(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()));
builder.withIssuedAt(now.atZone(ZoneId.systemDefault()).toInstant());
// bind not before (nbf)
builder.withNotBefore(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()));
builder.withNotBefore(now.atZone(ZoneId.systemDefault()).toInstant());
// bind audience (aud)
builder.withAudience(audience);
// bind subject (sub)
builder.withSubject(subject);
// bind expire at (exp)
builder.withExpiresAt(Date.from(now.plus(expireAfter).atZone(ZoneId.systemDefault()).toInstant()));
builder.withExpiresAt(now.plus(expireAfter).atZone(ZoneId.systemDefault()).toInstant());
// bind JWT Id (jti)
builder.withJWTId(jtiCreator.nextId().toString());
}
@@ -534,14 +589,13 @@ public class AuthzeroTokenResolver implements TokenResolver<DecodedJWT> {
/**
* Default type reference for Map.
*/
private static class MapTypeReference extends TypeReference<Map<String, Object>> {
public static class MapTypeReference extends TypeReference<Map<String, Object>> {
MapTypeReference() {
}
}
/**
* GuidCreator used for generating unique identifiers for "jti" claim in
* JWT tokens.
* GuidCreator used for generating unique identifiers for "jti" claim in JWT tokens.
*/
private final GuidCreator<?> jtiCreator;
@@ -558,12 +612,45 @@ public class AuthzeroTokenResolver implements TokenResolver<DecodedJWT> {
/**
* The JSON Web Token resolver.
*/
private final JWTVerifier verifier;
private final JWTVerifier jwtVerifier;
/**
* Jackson JSON handler.
*/
private final ObjectMapper objectMapper;
private final AuthzeroTokenResolverConfig config = AuthzeroTokenResolverConfig.getInstance();
/**
* A map contains all HMAC-SHA based algorithms.
*/
public static final Map<TokenAlgorithm, Function<String, Algorithm>> HMAC_ALGORITHMS = Map.of(
TokenAlgorithm.HS256, Algorithm::HMAC256,
TokenAlgorithm.HS384, Algorithm::HMAC384,
TokenAlgorithm.HS512, Algorithm::HMAC512
);
/**
* A map contains all ECDSA based algorithms.
*/
public static final Map<TokenAlgorithm, BiFunction<ECPublicKey, ECPrivateKey, Algorithm>> ECDSA_ALGORITHMS = Map.of(
TokenAlgorithm.ES256, Algorithm::ECDSA256,
TokenAlgorithm.ES384, Algorithm::ECDSA384,
TokenAlgorithm.ES512, Algorithm::ECDSA512
);
/**
* Private constructor prevent this class being initialised mistakenly.
*
* @param jtiCreator a creator that can create JWT id
* @param algorithm an algorithm to sign this JWT
* @param issuer the person or organisation who issued this JWT
* @param objectMapper a mapper for handling JSON serialisation and deserialization
*/
private AuthzeroTokenResolver(GuidCreator<?> jtiCreator, Algorithm algorithm, String issuer, ObjectMapper objectMapper) {
this.jtiCreator = jtiCreator;
this.algorithm = algorithm;
this.issuer = issuer;
this.objectMapper = objectMapper;
this.jwtVerifier = JWT.require(algorithm).build();
}
}
@@ -1,148 +0,0 @@
/*
* Copyright (C) 2024-2024 OnixByte.
*
* 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 com.onixbyte.simplejwt.authzero.config;
import com.onixbyte.security.KeyLoader;
import com.onixbyte.simplejwt.TokenResolver;
import com.onixbyte.simplejwt.authzero.AuthzeroTokenResolver;
import com.onixbyte.simplejwt.config.TokenResolverConfig;
import com.onixbyte.simplejwt.constants.TokenAlgorithm;
import com.onixbyte.simplejwt.exceptions.UnsupportedAlgorithmException;
import com.auth0.jwt.algorithms.Algorithm;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.ECPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* The {@code AuthzeroTokenResolverConfig} class provides the configuration for
* the {@link AuthzeroTokenResolver}.
* <p>
* This configuration is used to establish the mapping between the standard {@link TokenAlgorithm}
* defined in the {@code cn.org.codecrafters:simple-jwt-facade} and the specific algorithms used
* by the {@code com.auth0:java-jwt} library, which is the underlying library used by
* {@link AuthzeroTokenResolver} to handle JSON Web Tokens (JWTs).
* <p>
* <b>Algorithm Mapping:</b>
* The {@code AuthzeroTokenResolverConfig} allows specifying the relationships between the standard
* {@link TokenAlgorithm} instances supported by {@link AuthzeroTokenResolver} and the corresponding
* algorithms used by the {@code com.auth0:java-jwt} library. The mapping is achieved using a Map,
* where the keys are the standard {@link TokenAlgorithm} instances, and the values represent the
* algorithm functions used by {@code com.auth0:java-jwt} library for each corresponding key.
* <p>
* <b>Note:</b>
* The provided algorithm mapping should be consistent with the actual algorithms supported and used
* by the {@code com.auth0:java-jwt} library. It is crucial to ensure that the mapping is accurate
* to enable proper token validation and processing within the {@link AuthzeroTokenResolver}.
*
* @author Zihlu Wang
* @version 1.1.1
* @since 1.0.0
*/
public final class AuthzeroTokenResolverConfig
implements TokenResolverConfig<BiFunction<String, String, Algorithm>> {
/**
* Gets the instance of {@code AuthzeroTokenResolverConfig}.
* <p>
* This method returns the singleton instance of {@code AuthzeroTokenResolverConfig}. If the
* instance is not yet created, it will create a new instance and return it. Otherwise, it
* returns the existing instance.
*
* @return the instance of {@code AuthzeroTokenResolverConfig}
*/
public static AuthzeroTokenResolverConfig getInstance() {
if (Objects.isNull(instance)) {
instance = new AuthzeroTokenResolverConfig();
}
return instance;
}
/**
* Gets the algorithm function corresponding to the specified {@link TokenAlgorithm}.
* <p>
* This method returns the algorithm function associated with the given {@link TokenAlgorithm}.
* The provided {@link TokenAlgorithm} represents the specific algorithm for which the
* corresponding algorithm function is required. The returned Algorithm Function represents the
* function implementation that can be used by the {@link TokenResolver} to handle the
* specific algorithm.
*
* @param algorithm the {@link TokenAlgorithm} for which the algorithm function is required
* @return the algorithm function associated with the given {@link TokenAlgorithm}
* @throws UnsupportedAlgorithmException if the given {@code algorithm} is not supported by
* this implementation
*/
@Override
public BiFunction<String, String, Algorithm> getAlgorithm(TokenAlgorithm algorithm) {
return Optional.of(SUPPORTED_ALGORITHMS).map((entry) -> entry.get(algorithm))
.orElseThrow(() -> new UnsupportedAlgorithmException("The specified algorithm is not supported yet."));
}
/**
* Constructs a new instance of {@code AuthzeroTokenResolverConfig}.
* <p>
* The constructor is set as private to enforce the singleton pattern for
* this configuration class. Instances of
* {@code AuthzeroTokenResolverConfig} should be obtained through the
* {@link #getInstance()} method.
*/
private AuthzeroTokenResolverConfig() {
}
/**
* The singleton instance of {@code AuthzeroTokenResolverConfig}.
* <p>
* This instance is used to ensure that only one instance of
* {@code AuthzeroTokenResolverConfig} is created and shared throughout the
* application. The singleton pattern is implemented to provide centralised
* configuration and avoid redundant object creation.
*/
private static AuthzeroTokenResolverConfig instance;
/**
* The supported algorithms and their corresponding algorithm functions.
* <p>
* This map stores the supported algorithms as keys and their corresponding
* algorithm functions as values. The algorithm functions represent the
* functions used by the {@code com.auth0:java-jwt} library to handle the
* specific algorithms. The mapping is used to provide proper algorithm
* resolution and processing within the {@link AuthzeroTokenResolver}.
*/
private static final
Map<TokenAlgorithm, BiFunction<String, String, Algorithm>> SUPPORTED_ALGORITHMS =
new HashMap<>() {{
put(TokenAlgorithm.HS256, (String secret, String ignoredValue) ->
Algorithm.HMAC256(secret));
put(TokenAlgorithm.HS384, (String secret, String ignoredValue) ->
Algorithm.HMAC384(secret));
put(TokenAlgorithm.HS512, (String secret, String ignoredValue) ->
Algorithm.HMAC512(secret));
put(TokenAlgorithm.ES256, (String privateKey, String publicKey) ->
Algorithm.ECDSA256(KeyLoader.loadEcdsaPrivateKey(privateKey)));
put(TokenAlgorithm.ES384, (String privateKey, String publicKey) ->
Algorithm.ECDSA256(KeyLoader.loadEcdsaPrivateKey(privateKey)));
put(TokenAlgorithm.ES512, (String privateKey, String publicKey) ->
Algorithm.ECDSA256(KeyLoader.loadEcdsaPrivateKey(privateKey)));
}};
}
@@ -1,54 +0,0 @@
/*
* Copyright (C) 2024-2024 OnixByte.
*
* 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.
*/
/**
* The package {@code cn.org.codecrafters.simplejwt.authzero.config} contains
* configuration classes related to the {@link
* com.onixbyte.simplejwt.authzero.AuthzeroTokenResolver}
* implementation.
* <p>
* The classes in this package provide configuration options and settings for
* the {@link com.onixbyte.simplejwt.authzero.AuthzeroTokenResolver},
* which is used for resolving JSON Web Tokens (JWT) using the Auth0 library.
* <p>
* The {@link
* com.onixbyte.simplejwt.authzero.config.AuthzeroTokenResolverConfig}
* class is a configuration class that defines the mapping between standard
* {@link com.onixbyte.simplejwt.constants.TokenAlgorithm} and the
* corresponding function implementation used by {@link
* com.onixbyte.simplejwt.authzero.AuthzeroTokenResolver} for handling
* JWT algorithms. It enables developers to specify and customize the
* algorithm functions according to the chosen JWT algorithm and the library
* being used.
* <p>
* The configuration options in this package help developers integrate and
* configure the {@link
* com.onixbyte.simplejwt.authzero.AuthzeroTokenResolver} seamlessly
* into their Spring Boot applications. Developers can fine-tune the token
* resolution process and customize algorithm handling to align with their
* specific requirements and desired level of security.
* <p>
* It is recommended to explore the classes in this package to understand how
* to configure and use the {@link
* com.onixbyte.simplejwt.authzero.AuthzeroTokenResolver} effectively
* in the Spring Boot environment to handle JWT authentication and
* authorisation securely and efficiently.
*
* @since 1.0.0
*/
package com.onixbyte.simplejwt.authzero.config;
@@ -1,65 +0,0 @@
/*
* Copyright (C) 2024-2024 OnixByte.
*
* 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 com.onixbyte.simplejwt.config;
import com.onixbyte.simplejwt.TokenResolver;
import com.onixbyte.simplejwt.constants.TokenAlgorithm;
import java.util.List;
/**
* The {@code TokenResolverConfig} provides a mechanism to configure an
* implementation of {@link TokenResolver} with algorithm functions.
* <p>
* This generic interface is used to define the configuration details for a
* {@link TokenResolver} that utilizes algorithm functions. The interface
* allows for specifying algorithm functions corresponding to different {@link
* TokenAlgorithm} instances supported by the {@link TokenResolver}
* implementation.
*
* @param <Algo> the type representing algorithm functions used by the
* {@link TokenResolver}
* @author Zihlu Wang
* @version 1.0.0
* @since 1.0.0
*/
public interface TokenResolverConfig<Algo> {
/**
* Gets the algorithm function corresponding to the specified {@link
* TokenAlgorithm}.
* <p>
* This method returns the algorithm function associated with the given
* {@link TokenAlgorithm}. The provided TokenAlgorithm represents the
* specific algorithm for which the corresponding algorithm function is
* required. The returned {@code Algo} represents the function
* implementation that can be used by the {@link TokenResolver} to handle
* the specific algorithm.
*
* @param algorithm the {@link TokenAlgorithm} for which the algorithm function is required
* @return the algorithm function associated with the given {@link TokenAlgorithm}
*/
Algo getAlgorithm(TokenAlgorithm algorithm);
List<TokenAlgorithm> ECDSA_ALGORITHMS =
List.of(TokenAlgorithm.ES256, TokenAlgorithm.ES384, TokenAlgorithm.ES512);
List<TokenAlgorithm> HMAC_ALGORITHMS =
List.of(TokenAlgorithm.HS256, TokenAlgorithm.HS384, TokenAlgorithm.HS512);
}
@@ -1,32 +0,0 @@
/*
* Copyright (C) 2024-2024 OnixByte.
*
* 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.
*/
/**
* The classes in this package provide configuration options and settings for
* the {@code cn.org.codecrafters:simple-jwt-facade} library. They are used
* to customize the behavior of the library and allow developers to fine-tune
* various aspects of JWT generation and validation.
* <p>
* Other configuration classes may be added in the future to support additional
* customisation options and features. Developers using the
* {@code cn.org.codecrafters:simple-jwt-facade} library should be familiar
* with the available configuration options to ensure proper integration and
* usage of the library.
*
* @since 1.0.0
*/
package com.onixbyte.simplejwt.config;
@@ -19,6 +19,8 @@ package com.onixbyte.simplejwt.constants;
import lombok.Getter;
import java.util.List;
/**
* The {@code TokenAlgorithm} enum class defines the algorithms that can be
* used for signing and verifying JSON Web Tokens (JWT). JWT allows various
@@ -92,4 +94,18 @@ public enum TokenAlgorithm {
ES512,
;
/**
* HMAC-based algorithms.
*/
public static final List<TokenAlgorithm> HMAC_ALGORITHMS = List.of(
TokenAlgorithm.HS256, TokenAlgorithm.HS384, TokenAlgorithm.HS512
);
/**
* ECDSA-based algorithms.
*/
public static final List<TokenAlgorithm> ECDSA_ALGORITHMS = List.of(
TokenAlgorithm.ES256, TokenAlgorithm.ES384, TokenAlgorithm.ES512
);
}
@@ -0,0 +1,53 @@
/*
* Copyright (C) 2024-2024 OnixByte.
*
* 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 com.onixbyte.simplejwt.exceptions;
/**
* {@link IllegalKeyPairException} indicates an exception that the key pair is invalid.
*
* @author zihluwang
* @version 1.6.0
*/
public class IllegalKeyPairException extends RuntimeException {
/**
* Create a default exception instance.
*/
public IllegalKeyPairException() {
}
/**
* Create an exception instance with specific message.
*
* @param message the message of the exception
*/
public IllegalKeyPairException(String message) {
super(message);
}
/**
* Create an exception instance with specific message and cause.
*
* @param message the message of the exception
* @param cause the cause of the exception
*/
public IllegalKeyPairException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,54 @@
/*
* Copyright (C) 2024-2024 OnixByte.
*
* 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 com.onixbyte.simplejwt.exceptions;
/**
* {@link IllegalKeyPairException} indicates the secret to sign a JWT is illegal.
*
* @author zihluwang
* @version 1.6.0
* @since 1.6.0
*/
public class IllegalSecretException extends RuntimeException {
/**
* Create a default exception instance.
*/
public IllegalSecretException() {
}
/**
* Create an exception instance with specific message.
*
* @param message the message of the exception
*/
public IllegalSecretException(String message) {
super(message);
}
/**
* Create an exception instance with specific message and the cause of this exception.
*
* @param message the message of the exception
* @param cause the cause of the exception
*/
public IllegalSecretException(String message, Throwable cause) {
super(message, cause);
}
}
-54
View File
@@ -1,54 +0,0 @@
# Module `simple-jwt-jjwt`
## Introduction
The `simple-jwt-jjwt` module is an implementation of module `simple-jwt-facade` which uses the third-party library [`io.jsonwebtoken:jjwt-api`](https://github.com/jwtk/jjwt). By using this module can help you use JWT to help you in your application.
## Prerequisites
This whole `JDevKit` is developed by **JDK 17**, which means you have to use JDK 17 for better experience.
## Installation
> This module has already imported `simple-jwt-facade`, there is no need to import it again.
### If you are using `Maven`
It is quite simple to install this module by `Maven`. The only thing you need to do is find your `pom.xml` file in the project, then find the `<dependencies>` node in the `<project>` node, and add the following codes to `<dependencies>` node:
```xml
<dependency>
<groupId>cn.org.codecrafters</groupId>
<artifactId>simple-jwt-jjwt</artifactId>
<version>${simple-jwt-jjwt.version}</version>
</dependency>
```
And run `mvn dependency:get` in your project root folder(i.e., if your `pom.xml` is located at `/path/to/your/project/pom.xml`, then your current work folder should be `/path/to/your/project`), then `Maven` will automatically download the `jar` archive from `Maven Central Repository`. This could be **MUCH EASIER** if you are using IDE(i.e., IntelliJ IDEA), the only thing you need to do is click the refresh button of `Maven`.
### If you are using `Gradle`
Add this module to your project with `Gradle` is much easier than doing so with `Maven`.
Find `build.gradle` in the needed project, and add the following code to the `dependencies` closure in the build script:
```groovy
implementation 'cn.org.codecrafters:simple-jwt-authzero:${simple-jwt-authzero.version}'
```
### If you are not using `Maven` or `Gradle`
1. Download the `jar` file from the Internet.
2. Create a folder in your project and name it as a name you like(i.e., for me, I prefer `vendor`).
3. Put the `jar` file to the folder you just created in Step 2.
4. Add this folder to your project `classpath`.
## Use the `JjwtTokenResolver`
We have implemented `TokenResolver` to make sure you can add JWT to your Java application as soon as possible. All you need to do is to create an instance of `jjwt.com.onixbyte.simplejwt.JjwtTokenResolver` and other operations to JWT could follow our instruction in [`simple-jwt-facade`](../simple-jwt-facade/README.md).
## Contact
If you have any suggestions, ideas, don't hesitate contacting us via [GitHub Issues](https://github.com/CodeCraftersCN/jdevkit/issues/new) or [Discord Community](https://discord.gg/NQK9tjcBB8).
If you face any bugs while using our library and you are able to fix any bugs in our library, we would be happy to accept pull requests from you on [GitHub](https://github.com/CodeCraftersCN/jdevkit/compare).
-107
View File
@@ -1,107 +0,0 @@
/*
* Copyright (C) 2024-2024 OnixByte.
*
* 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.
*/
import java.net.URI
val buildGroupId: String by project
val buildVersion: String by project
val projectUrl: String by project
val projectGithubUrl: String by project
val licenseName: String by project
val licenseUrl: String by project
val jacksonVersion: String by project
val jjwtVersion: String by project
group = buildGroupId
version = buildVersion
dependencies {
implementation(project(":devkit-utils"))
implementation(project(":guid"))
implementation("com.fasterxml.jackson.core:jackson-databind:$jacksonVersion")
implementation("io.jsonwebtoken:jjwt-api:$jjwtVersion")
implementation("io.jsonwebtoken:jjwt-impl:$jjwtVersion")
implementation("io.jsonwebtoken:jjwt-jackson:$jjwtVersion")
implementation(project(":simple-jwt-facade"))
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
withSourcesJar()
withJavadocJar()
}
tasks.test {
useJUnitPlatform()
}
publishing {
publications {
create<MavenPublication>("simpleJwtJjwt") {
groupId = buildGroupId
artifactId = "simple-jwt-jjwt"
version = buildVersion
pom {
name = "Simple JWT :: JJWT"
description = "SSimple JWT implemented with io.jsonwebtoken:jjwt."
url = projectUrl
licenses {
license {
name = licenseName
url = licenseUrl
}
}
scm {
connection = "scm:git:git://github.com:OnixByte/JDevKit.git"
developerConnection = "scm:git:git://github.com:OnixByte/JDevKit.git"
url = projectGithubUrl
}
developers {
developer {
id = "zihluwang"
name = "Zihlu Wang"
email = "really@zihlu.wang"
timezone = "Asia/Hong_Kong"
}
}
}
from(components["java"])
signing {
sign(publishing.publications["simpleJwtJjwt"])
}
}
repositories {
maven {
name = "sonatypeNexus"
url = URI(providers.gradleProperty("repo.maven-central.host").get())
credentials {
username = providers.gradleProperty("repo.maven-central.username").get()
password = providers.gradleProperty("repo.maven-central.password").get()
}
}
}
}
}
@@ -1,474 +0,0 @@
/*
* Copyright (C) 2024-2024 OnixByte.
*
* 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 com.onixbyte.simplejwt.jjwt;
import com.onixbyte.devkit.utils.MapUtil;
import com.onixbyte.guid.GuidCreator;
import com.onixbyte.simplejwt.SecretCreator;
import com.onixbyte.simplejwt.TokenPayload;
import com.onixbyte.simplejwt.TokenResolver;
import com.onixbyte.simplejwt.annotations.ExcludeFromPayload;
import com.onixbyte.simplejwt.annotations.TokenEnum;
import com.onixbyte.simplejwt.constants.PredefinedKeys;
import com.onixbyte.simplejwt.constants.TokenAlgorithm;
import com.onixbyte.simplejwt.exceptions.WeakSecretException;
import com.onixbyte.simplejwt.jjwt.config.JjwtTokenResolverConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SecureDigestAlgorithm;
import lombok.extern.slf4j.Slf4j;
import javax.crypto.SecretKey;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
/**
* The {@link JjwtTokenResolver} class is an implementation of the {@link
* TokenResolver} interface. It uses the {@code
* io.jsonwebtoken:jjwt} library to handle JSON Web Token (JWT) resolution.
* This resolver provides functionality to create, extract, verify, and renew
* JWT tokens using various algorithms and custom payload data.
* <p>
* <b>Usage:</b>
* To use the {@code JjwtTokenResolver}, first, create an instance of this
* class:
* <pre>{@code
* TokenResolver<Jws<Claims>> tokenResolver =
* new JjwtTokenResolver(TokenAlgorithm.HS256,
* "Token Subject",
* "Token Issuer",
* "Token Secret");
* }</pre>
* <p>
* Then, you can utilize the various methods provided by this resolver to
* handle JWT tokens:
* <pre>{@code
* // Creating a new JWT token
* String token =
* tokenResolver.createToken(Duration.ofHours(1),
* "your_subject",
* "your_audience",
* customPayloads);
*
* // Extracting payload data from a JWT token
* DecodedJWT decodedJWT = tokenResolver.resolve(token);
* T payloadData = decodedJWT.extract(token, T.class);
*
* // Renewing an existing JWT token
* String renewedToken =
* tokenResolver.renew(token, Duration.ofMinutes(30), customPayloads);
* }</pre>
* <p>
* <b>Note:</b>
* It is essential to configure the appropriate algorithms, secret, and issuer
* according to your specific use case when using this resolver.
* Additionally, ensure that the {@code io.jsonwebtoken:jjwt} library is
* correctly configured in your project's dependencies.
*
* @author Zihlu Wang
* @version 1.1.0
* @see Claims
* @see Jws
* @see Jwts
* @see SecureDigestAlgorithm
* @see Keys
* @since 1.0.0
*/
@Slf4j
public class JjwtTokenResolver implements TokenResolver<Jws<Claims>> {
/**
* Create a resolver with specified algorithm, issuer, secret and guid strategy.
*
* @param jtiCreator jwt id creator
* @param algorithm specified algorithm
* @param issuer specified issuer
* @param secret specified secret
*/
public JjwtTokenResolver(GuidCreator<?> jtiCreator, TokenAlgorithm algorithm, String issuer, String secret) {
if (Objects.isNull(secret) || secret.isBlank()) {
throw new IllegalArgumentException("A secret is required to build a JSON Web Token.");
}
if (secret.length() < 32) {
throw new WeakSecretException("""
The provided secret which owns %s characters is too weak. Please replace it with a stronger one."""
.formatted(secret.length()));
}
this.jtiCreator = jtiCreator;
this.algorithm = config.getAlgorithm(algorithm);
this.issuer = issuer;
this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
}
/**
* Create a resolver with specified algorithm, issuer, secret and default guid strategy.
*
* @param algorithm specified algorithm
* @param issuer specified issuer
* @param secret specified secret
*/
public JjwtTokenResolver(TokenAlgorithm algorithm, String issuer, String secret) {
if (secret == null || secret.isBlank()) {
throw new IllegalArgumentException("A secret is required to build a JSON Web Token.");
}
if (secret.length() < 32) {
log.error(
"The provided secret which owns {} characters is too weak. Please replace it with a stronger one.",
secret.length());
throw new WeakSecretException(
"The provided secret which owns %s characters is too weak. Please replace it with a stronger one."
.formatted(secret.length()));
}
this.jtiCreator = UUID::randomUUID;
this.algorithm = config.getAlgorithm(algorithm);
this.issuer = issuer;
this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
}
/**
* Create a resolver with specified issuer, secret, default algorithm and guid strategy.
*
* @param issuer specified issuer
* @param secret specified secret
* @see #JjwtTokenResolver(TokenAlgorithm, String, String)
*/
public JjwtTokenResolver(String issuer, String secret) {
if (secret == null || secret.isBlank()) {
throw new IllegalArgumentException("A secret is required to build a JSON Web Token.");
}
if (secret.length() < 32) {
throw new WeakSecretException(
"The provided secret which owns %s characters is too weak. Please replace it with a stronger one."
.formatted(secret.length()));
}
this.jtiCreator = UUID::randomUUID;
this.algorithm = config.getAlgorithm(TokenAlgorithm.HS256);
this.issuer = issuer;
this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
}
/**
* Create a resolver with specified issuer, random secret string, default algorithm and guid strategy.
*
* @param issuer specified issuer
* @see #JjwtTokenResolver(String, String)
*/
public JjwtTokenResolver(String issuer) {
this.jtiCreator = UUID::randomUUID;
this.algorithm = config.getAlgorithm(TokenAlgorithm.HS256);
this.issuer = issuer;
this.key = Keys.hmacShaKeyFor(SecretCreator.createSecret(32, true, true, true).getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a new token with the specified expiration time, subject, and
* audience.
*
* @param expireAfter the duration after which the token will expire
* @param audience the audience for which the token is intended
* @param subject the subject of the token
* @return the generated token as a {@code String}
*/
@Override
public String createToken(Duration expireAfter, String audience, String subject) {
return buildToken(expireAfter, audience, subject, null);
}
/**
* Creates a new token with the specified expiration time, subject,
* audience, and custom payload data.
*
* @param expireAfter the duration after which the token will expire
* @param audience the audience for which the token is intended
* @param subject the subject of the token
* @param payload the custom payload data to be included in the token
* @return the generated token as a {@code String}
*/
@Override
public String createToken(Duration expireAfter, String audience, String subject, Map<String, Object> payload) {
return buildToken(expireAfter, audience, subject, payload);
}
/**
* Creates a new token with the specified expiration time, subject,
* audience, and strongly-typed payload data.
*
* @param expireAfter the duration after which the token will expire
* @param audience the audience for which the token is intended
* @param subject the subject of the token
* @param payload the strongly-typed payload data to be included in the
* token
* @return the generated token as a {@code String} or {@code null} if
* creation fails
* @see MapUtil#objectToMap(Object, Map)
*/
@Override
public <T extends TokenPayload> String createToken(Duration expireAfter, String audience, String subject, T payload) {
var fields = payload.getClass().getDeclaredFields();
var payloadMap = new HashMap<String, Object>();
for (var field : fields) {
if (field.isAnnotationPresent(ExcludeFromPayload.class))
continue;
try {
var getter = payload.getClass().getDeclaredMethod("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1));
// Build Claims
/*
* Note (17 Oct, 2023): The jjwt can only add a map to be added.
*/
var fieldValue = getter.invoke(payload);
// Handle enum fields.
if (field.isAnnotationPresent(TokenEnum.class)) {
var annotation = field.getAnnotation(TokenEnum.class);
var enumGetter = field.getType().getDeclaredMethod("get" + annotation.propertyName().substring(0, 1).toUpperCase() + annotation.propertyName().substring(1));
fieldValue = enumGetter.invoke(fieldValue);
}
payloadMap.put(field.getName(), fieldValue);
} catch (IllegalAccessException | NoSuchMethodException e) {
log.error("Cannot access field {}!", field.getName());
} catch (InvocationTargetException e) {
log.error("Cannot invoke getter.", e);
}
}
return buildToken(expireAfter, audience, subject, payloadMap);
}
/**
* Resolves the given token into a {@link Jws<Claims>} object.
*
* @param token the token to be resolved
* @return a ResolvedTokenType object
*/
@Override
public Jws<Claims> resolve(String token) {
return Jwts.parser()
.verifyWith(key)
.build()
.parseSignedClaims(token);
}
/**
* Extracts the payload information from the given token and maps it to the
* specified target type.
*
* @param token the token from which to extract the payload
* @param targetType the target class representing the payload data type
* @return an instance of the specified target type with the extracted
* payload data, or {@code null} if extraction fails.
* @see MapUtil#mapToObject(Map, Object, Map)
*/
@Override
public <T extends TokenPayload> T extract(String token, Class<T> targetType) {
var resolvedToken = resolve(token);
var claims = resolvedToken.getPayload();
try {
var bean = targetType.getConstructor().newInstance();
for (var entry : claims.entrySet()) {
// Jump all JWT pre-defined properties and the fields that are annotated to be excluded.
if (PredefinedKeys.KEYS.contains(entry.getKey()) || targetType.getDeclaredField(entry.getKey()).isAnnotationPresent(ExcludeFromPayload.class))
continue;
var field = targetType.getDeclaredField(entry.getKey());
var fieldValue = entry.getValue();
if (field.isAnnotationPresent(TokenEnum.class)) {
var annotation = field.getAnnotation(TokenEnum.class);
var enumStaticLoader = field.getType().getDeclaredMethod("loadBy" + annotation.propertyName().substring(0, 1).toUpperCase() + annotation.propertyName().substring(1), annotation.dataType().getMappedClass());
fieldValue = enumStaticLoader.invoke(null, entry.getValue());
}
var setter = targetType.getDeclaredMethod("set" + entry.getKey().substring(0, 1).toUpperCase() + entry.getKey().substring(1), fieldValue.getClass());
if (setter.canAccess(bean)) {
setter.invoke(bean, fieldValue);
} else {
log.error("Setter for field {} can't be accessed.", entry.getKey());
}
}
return bean;
} catch (InvocationTargetException e) {
log.error("Target is not invokable.", e);
} catch (NoSuchMethodException e) {
log.error("Cannot find method according to given data.", e);
} catch (InstantiationException e) {
log.error("The required type {} is abstract or an interface.", targetType.getCanonicalName());
} catch (IllegalAccessException e) {
log.error("An error occurs while accessing the fields of the object.", e);
} catch (NoSuchFieldException e) {
log.error("Cannot load field according to given field name.", e);
}
return null;
}
/**
* Re-generate a new token with the payload in the old one.
*
* @param oldToken the old token
* @param expireAfter how long the new token can be valid for
* @return re-generated token with the payload in the old one
*/
@Override
public String renew(String oldToken, Duration expireAfter) {
var resolvedToken = resolve(oldToken);
var tokenPayloads = resolvedToken.getPayload();
var audience = tokenPayloads.getAudience().toArray(new String[]{})[0];
var subject = tokenPayloads.getSubject();
PredefinedKeys.KEYS.forEach(tokenPayloads::remove);
return createToken(expireAfter, audience, subject, tokenPayloads);
}
/**
* Renews the given expired token with the specified custom payload data.
*
* @param oldToken the expired token to be renewed
* @param expireAfter specify when does the new token invalid
* @param payload the custom payload data to be included in the renewed
* token
* @return the renewed token as a {@code String}
*/
@Override
public String renew(String oldToken, Duration expireAfter, Map<String, Object> payload) {
var resolvedTokenClaims = resolve(oldToken).getPayload();
var audience = resolvedTokenClaims.getAudience().toArray(new String[]{})[0];
var subject = resolvedTokenClaims.getSubject();
return createToken(expireAfter, audience, subject, payload);
}
/**
* Renews the given expired token with the specified custom payload data.
*
* @param oldToken the expired token to be renewed
* @param payload the custom payload data to be included in the renewed
* token
* @return the renewed token as a {@code String}
*/
@Override
public String renew(String oldToken, Map<String, Object> payload) {
return renew(oldToken, Duration.ofMinutes(30), payload);
}
/**
* Renews the given expired token with the specified strongly-typed
* payload data.
*
* @param oldToken the expired token to be renewed
* @param expireAfter specify when does the new token invalid
* @param payload the strongly-typed payload data to be included in the
* renewed token
* @return the renewed token as a {@code String}
*/
@Override
public <T extends TokenPayload> String renew(String oldToken, Duration expireAfter, T payload) {
var resolvedTokenClaims = resolve(oldToken).getPayload();
var audience = resolvedTokenClaims.getAudience().toArray(new String[]{})[0];
var subject = resolvedTokenClaims.getSubject();
return createToken(expireAfter, audience, subject, payload);
}
/**
* Renews the given expired token with the specified strongly-typed
* payload data.
*
* @param oldToken the expired token to be renewed
* @param payload the strongly-typed payload data to be included in the
* renewed token
* @return the renewed token as a {@code String}
*/
@Override
public <T extends TokenPayload> String renew(String oldToken, T payload) {
return renew(oldToken, Duration.ofMinutes(30), payload);
}
/**
* Build a new token with specified data.
*
* @param expireAfter the validity time of the token
* @param audience the audience of the token
* @param subject the subject of the token
* @param claims the data to be included in the token
* @return the built token
*/
private String buildToken(Duration expireAfter, String audience, String subject, Map<String, Object> claims) {
var now = LocalDateTime.now();
var builder = Jwts.builder()
.header().add("typ", "JWT")
.and()
.issuedAt(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()))
.notBefore(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()))
.expiration(Date.from(now.plus(expireAfter).atZone(ZoneId.systemDefault()).toInstant()))
.subject(subject)
.issuer(this.issuer)
.audience().add(audience)
.and()
.id(jtiCreator.nextId().toString());
if (claims != null && !claims.isEmpty()) {
builder.claims(claims);
}
return builder.signWith(key, algorithm)
.compact();
}
/**
* The ID creator for creating unique JWT IDs.
*/
private final GuidCreator<?> jtiCreator;
/**
* The algorithm to sign this token.
*/
private final SecureDigestAlgorithm<SecretKey, SecretKey> algorithm;
/**
* The issuer of this token.
*/
private final String issuer;
/**
* The signature key of this token.
*/
private final SecretKey key;
/**
* The config of this token resolver.
*/
private final JjwtTokenResolverConfig config = JjwtTokenResolverConfig.getInstance();
}
@@ -1,121 +0,0 @@
/*
* Copyright (C) 2024-2024 OnixByte.
*
* 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 com.onixbyte.simplejwt.jjwt.config;
import com.onixbyte.simplejwt.TokenResolver;
import com.onixbyte.simplejwt.config.TokenResolverConfig;
import com.onixbyte.simplejwt.constants.TokenAlgorithm;
import com.onixbyte.simplejwt.exceptions.UnsupportedAlgorithmException;
import com.onixbyte.simplejwt.jjwt.JjwtTokenResolver;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.SecureDigestAlgorithm;
import javax.crypto.SecretKey;
import java.util.HashMap;
import java.util.Map;
/**
* The {@code JjwtTokenResolverConfig} class provides the configuration for
* the {@link JjwtTokenResolver}.
* <p>
* This configuration is used to establish the mapping between the standard
* {@link TokenAlgorithm} defined in the
* {@code cn.org.codecrafters:simple-jwt-facade} and the specific algorithms
* used by the {@code io.jsonwebtoken:jjwt} library, which is the underlying
* library used by {@link JjwtTokenResolver} to handle JSON Web Tokens
* (JWTs).
* <p>
* <b>Algorithm Mapping:</b>
* The {@code JjwtTokenResolverConfig} allows specifying the relationships
* between the standard {@link TokenAlgorithm} instances supported by
* {@link JjwtTokenResolver} and the corresponding algorithms used by the
* {@code io.jsonwebtoken:jjwt} library. The mapping is achieved using a Map,
* where the keys are the standard {@link TokenAlgorithm} instances, and the
* values represent the algorithm functions used by
* {@code io.jsonwebtoken:jjwt} library for each corresponding key.
* <p>
* <b>Note:</b>
* The provided algorithm mapping should be consistent with the actual
* algorithms supported and used by the {@code io.jsonwebtoken:jjwt} library.
* It is crucial to ensure that the mapping is accurate to enable proper token
* validation and processing within the {@link JjwtTokenResolver}.
*
* @author Zihlu Wang
* @version 1.1.1
* @since 1.0.0
*/
public final class JjwtTokenResolverConfig implements TokenResolverConfig<SecureDigestAlgorithm<SecretKey, SecretKey>> {
/**
* Get the instance for io.jsonwebtoken:jjwt config.
* @return the instance for io.jsonwebtoken:jjwt config
*/
public static JjwtTokenResolverConfig getInstance() {
if (instance == null) {
instance = new JjwtTokenResolverConfig();
}
return instance;
}
/**
* Gets the algorithm function corresponding to the specified
* {@link TokenAlgorithm}.
* <p>
* This method returns the algorithm function associated with the given
* {@link TokenAlgorithm}. The provided {@link TokenAlgorithm} represents
* the specific algorithm for which the corresponding algorithm function is
* required. The returned algorithm function represents the function
* implementation that can be used by the {@link TokenResolver} to handle
* the specific algorithm.
*
* @param algorithm the {@link TokenAlgorithm} for which the algorithm
* function is required
* @return the algorithm function associated with the given {@link
* TokenAlgorithm}
*/
@Override
public SecureDigestAlgorithm<SecretKey, SecretKey> getAlgorithm(TokenAlgorithm algorithm) {
if (!SUPPORTED_ALGORITHMS.containsKey(algorithm)) {
throw new UnsupportedAlgorithmException("""
The request algorithm is not supported by our system yet. Please change to supported ones.""");
}
return SUPPORTED_ALGORITHMS.get(algorithm);
}
/**
* Private constructor will protect this class from being instantiated.
*/
private JjwtTokenResolverConfig() {
}
/**
* A {@code Map} to map a {@link TokenAlgorithm} to {@link SecureDigestAlgorithm}.
*/
private static final Map<TokenAlgorithm, SecureDigestAlgorithm<SecretKey, SecretKey>> SUPPORTED_ALGORITHMS = new HashMap<>() {{
put(TokenAlgorithm.HS256, Jwts.SIG.HS256);
put(TokenAlgorithm.HS384, Jwts.SIG.HS384);
put(TokenAlgorithm.HS512, Jwts.SIG.HS512);
}};
/**
* The instance of this config class.
*/
private static JjwtTokenResolverConfig instance;
}
@@ -1,53 +0,0 @@
/*
* Copyright (C) 2024-2024 OnixByte.
*
* 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.
*/
/**
* The package {@code cn.org.codecrafters.simplejwt.jjwt.config} contains
* configuration classes related to the {@link
* com.onixbyte.simplejwt.jjwt.JjwtTokenResolver}
* implementation.
* <p>
* The classes in this package provide configuration options and settings for
* the {@link com.onixbyte.simplejwt.jjwt.JjwtTokenResolver},
* which is used for resolving JSON Web Tokens (JWT) using the Auth0 library.
* <p>
* The {@link
* com.onixbyte.simplejwt.jjwt.config.JjwtTokenResolverConfig}
* class is a configuration class that defines the mapping between standard
* {@link com.onixbyte.simplejwt.constants.TokenAlgorithm} and the
* corresponding function implementation used by {@link
* com.onixbyte.simplejwt.jjwt.JjwtTokenResolver} for handling
* JWT algorithms. It enables developers to specify and customize the
* algorithm functions according to the chosen JWT algorithm and the library
* being used.
* <p>
* The configuration options in this package help developers integrate and
* configure the {@link
* com.onixbyte.simplejwt.jjwt.JjwtTokenResolver} seamlessly
* into their Spring Boot applications. Developers can fine-tune the token
* resolution process and customize algorithm handling to align with their
* specific requirements and desired level of security.
* <p>
* It is recommended to explore the classes in this package to understand how
* to configure and use the {@link
* com.onixbyte.simplejwt.jjwt.JjwtTokenResolver} effectively
* in the Spring Boot environment to handle JWT authentication and
* authorisation securely and efficiently.
*
* @since 1.0.0
*/
package com.onixbyte.simplejwt.jjwt.config;
@@ -1,58 +0,0 @@
/*
* Copyright (C) 2024-2024 OnixByte.
*
* 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.
*/
/**
* This package contains classes related to the integration of the {@code
* io.jsonwebtoken:jjwt-api} library in the Simple JWT project. {@code
* io.jsonwebtoken:jjwt-api} is a powerful and widely-used Identity as a Service
* (IDaaS) platform that provides secure authentication and authorisation
* solutions for web and mobile applications. The classes in this package
* provide the necessary functionality to handle JSON Web Tokens (JWTs) using
* the {@code io.jsonwebtoken:jjwt-api} library.
* <p>
* The main class in this package is the {@link
* com.onixbyte.simplejwt.jjwt.JjwtTokenResolver}, which
* implements the {@link com.onixbyte.simplejwt.TokenResolver} interface
* and uses the {@code io.jsonwebtoken:jjwt-api} library to handle JWT
* operations. It provides the functionality to create, validate, and extract
* JWTs using the {@code io.jsonwebtoken:jjwt-api} library. Developers can use
* this class as the main token resolver in the Simple JWT project when
* integrating {@code io.jsonwebtoken:jjwt-api} as the JWT management library.
* <p>
* The {@link com.onixbyte.simplejwt.jjwt.JjwtTokenResolver} relies on
* the {@code io.jsonwebtoken:jjwt-api}
* library to handle the underlying JWT operations, including token creation,
* validation, and extraction. It utilizes the {@code io.jsonwebtoken:jjwt-api}
* {@link io.jsonwebtoken.SignatureAlgorithm} class to define and use different
* algorithms for JWT signing and verification.
* <p>
* To use the {@link com.onixbyte.simplejwt.jjwt.JjwtTokenResolver},
* developers must provide the necessary configurations and dependencies, such
* as the {@link com.onixbyte.guid.GuidCreator} for generating unique
* JWT IDs (JTI), the supported algorithm function, the issuer name, and the
* secret key used for token signing and validation. The
* {@link com.onixbyte.simplejwt.jjwt.config.JjwtTokenResolverConfig}
* class provides a convenient way to configure these dependencies.
* <p>
* Developers using the {@code io.jsonwebtoken:jjwt-api} integration should be
* familiar with the concepts and usage of the {@code io.jsonwebtoken:jjwt-api}
* library and follow the official {@code io.jsonwebtoken:jjwt-api}
* documentation for best practices and security considerations.
*
* @since 1.0.0
*/
package com.onixbyte.simplejwt.jjwt;
@@ -1,32 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (C) 2023 CodeCraftersCN.
~
~ 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.
-->
<configuration>
<property name="COLOURFUL_OUTPUT" value="%black(%date{'dd MMM, yyyy HH:mm:ss', Asia/Hong_Kong, en-UK}) %highlight(%-5level) %black(---) %black([%10.10t]) %cyan(%-20.20logger{20}) %black(:) %msg%n"/>
<property name="STANDARD_OUTPUT" value="%date{'dd MMM, yyyy HH:mm:ss', Asia/Hong_Kong, en-UK} %-5level %black(---) [%10.10t] %-20.20logger{20} : %msg%n"/>
<statusListener class="ch.qos.logback.core.status.NopStatusListener" />
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${COLOURFUL_OUTPUT}</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
@@ -25,7 +25,7 @@ val licenseName: String by project
val licenseUrl: String by project
val javaJwtVersion: String by project
val jjwtVersion: String by project
val jacksonVersion: String by project
val springBootVersion: String by project
group = buildGroupId
@@ -36,10 +36,7 @@ dependencies {
implementation(project(":simple-jwt-facade"))
compileOnly("com.auth0:java-jwt:$javaJwtVersion")
compileOnly(project(":simple-jwt-authzero"))
compileOnly("io.jsonwebtoken:jjwt-api:$jjwtVersion")
compileOnly("io.jsonwebtoken:jjwt-impl:$jjwtVersion")
compileOnly("io.jsonwebtoken:jjwt-jackson:$jjwtVersion")
compileOnly(project(":simple-jwt-jjwt"))
implementation("com.fasterxml.jackson.core:jackson-databind:$jacksonVersion")
implementation("org.springframework.boot:spring-boot-autoconfigure:$springBootVersion")
implementation("org.springframework.boot:spring-boot-starter-logging:$springBootVersion")
implementation("org.springframework.boot:spring-boot-configuration-processor:$springBootVersion")
@@ -23,7 +23,7 @@ import com.onixbyte.simplejwt.authzero.AuthzeroTokenResolver;
import com.onixbyte.simplejwt.autoconfiguration.properties.SimpleJwtProperties;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.onixbyte.simplejwt.config.TokenResolverConfig;
import com.onixbyte.simplejwt.constants.TokenAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
@@ -91,25 +91,21 @@ public class AuthzeroTokenResolverAutoConfiguration {
*/
@Bean
public TokenResolver<DecodedJWT> tokenResolver() {
if (TokenResolverConfig.HMAC_ALGORITHMS.contains(simpleJwtProperties.algorithm())) {
return new AuthzeroTokenResolver(
jtiCreator,
simpleJwtProperties.algorithm(),
simpleJwtProperties.issuer(),
simpleJwtProperties.secret(),
"",
objectMapper
);
} else {
return new AuthzeroTokenResolver(
jtiCreator,
simpleJwtProperties.algorithm(),
simpleJwtProperties.issuer(),
simpleJwtProperties.getPrivateKey(),
simpleJwtProperties.getPublicKey(),
objectMapper
);
var builder = AuthzeroTokenResolver.builder();
if (TokenAlgorithm.HMAC_ALGORITHMS.contains(simpleJwtProperties.getAlgorithm())) {
builder.keyPair(simpleJwtProperties.getPublicKey(), simpleJwtProperties.getPrivateKey())
.algorithm(simpleJwtProperties.getAlgorithm());
} else if (TokenAlgorithm.ECDSA_ALGORITHMS.contains(simpleJwtProperties.getAlgorithm())) {
builder.secret(simpleJwtProperties.getSecret())
.algorithm(simpleJwtProperties.getAlgorithm());
}
builder.issuer(simpleJwtProperties.getIssuer());
builder.jtiCreator(jtiCreator);
builder.objectMapper(objectMapper);
return builder.build();
}
private final GuidCreator<?> jtiCreator;
@@ -1,110 +0,0 @@
/*
* Copyright (C) 2024-2024 OnixByte.
*
* 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 com.onixbyte.simplejwt.autoconfiguration;
import com.onixbyte.guid.GuidCreator;
import com.onixbyte.simplejwt.TokenResolver;
import com.onixbyte.simplejwt.autoconfiguration.properties.SimpleJwtProperties;
import com.onixbyte.simplejwt.jjwt.JjwtTokenResolver;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
/**
* {@code JjwtTokenResolverAutoConfiguration} is responsible for automatically
* configuring the Simple JWT library with {@code io.jsonwebtoken:jjwt-api}
* when used in a Spring Boot application. It provides default settings and
* configurations to ensure that the library works smoothly without requiring
* manual configuration.
* <p>
* This autoconfiguration class sets up the necessary beans and components
* required for JWT generation and validation. It automatically creates and
* configures the {@link JjwtTokenResolver} bean based on the available options
* and properties.
* <p>
* Developers using the Simple JWT library with Spring Boot do not need to
* explicitly configure the library, as the autoconfiguration takes care of
* setting up the necessary components and configurations automatically.
* However, developers still have the flexibility to customize the behavior of
* the library by providing their own configurations and properties.
*
* @author Zihlu Wang
* @version 1.1.0
* @since 1.0.0
*/
@Slf4j
@AutoConfiguration
@EnableConfigurationProperties(value = {SimpleJwtProperties.class})
@ConditionalOnClass({Jws.class, Claims.class, JjwtTokenResolver.class})
@ConditionalOnMissingBean({TokenResolver.class})
@ConditionalOnBean(value = {GuidCreator.class}, name = "jtiCreator")
@AutoConfigureAfter(value = GuidAutoConfiguration.class)
public class JjwtTokenResolverAutoConfiguration {
/**
* Constructs a new {@code SimpleJwtAutoConfiguration} instance with the provided
* {@link SimpleJwtProperties}.
*
* @param jtiCreator a creator to create JSON Web Token ids
* @param simpleJwtProperties the SimpleJwtProperties instance
*/
@Autowired
public JjwtTokenResolverAutoConfiguration(SimpleJwtProperties simpleJwtProperties, @Qualifier("jtiCreator") GuidCreator<?> jtiCreator) {
this.jtiCreator = jtiCreator;
this.simpleJwtProperties = simpleJwtProperties;
}
/**
* Creates a new {@link TokenResolver} bean using {@link JjwtTokenResolver} if no existing
* {@link TokenResolver} bean is found. The {@link JjwtTokenResolver} is configured with the
* provided {@link GuidCreator}, {@code algorithm}, {@code issuer}, and {@code secret}
* properties from {@link SimpleJwtProperties}.
*
* @return the {@link TokenResolver} instance
*/
@Bean
public TokenResolver<Jws<Claims>> tokenResolver() {
return new JjwtTokenResolver(
jtiCreator,
simpleJwtProperties.algorithm(),
simpleJwtProperties.issuer(),
simpleJwtProperties.secret()
);
}
/**
* The GuidCreator instance to be used for generating JWT IDs (JTI).
*/
private final GuidCreator<?> jtiCreator;
/**
* The {@code SimpleJwtProperties} instance containing the configuration properties
* for Simple JWT.
*/
private final SimpleJwtProperties simpleJwtProperties;
}
@@ -20,7 +20,6 @@ package com.onixbyte.simplejwt.autoconfiguration.properties;
import com.onixbyte.simplejwt.SecretCreator;
import com.onixbyte.simplejwt.autoconfiguration.AuthzeroTokenResolverAutoConfiguration;
import com.onixbyte.simplejwt.constants.TokenAlgorithm;
import com.onixbyte.simplejwt.jjwt.JjwtTokenResolver;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@@ -31,9 +30,8 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
* "onixbyte.simple-jwt".
* <p>
* {@code SimpleJwtProperties} provides configuration options for the JWT algorithm, issuer,
* and secret. The properties are used by the {@link AuthzeroTokenResolverAutoConfiguration} and
* {@link JjwtTokenResolver} to set up the necessary configurations for JWT generation
* and validation.
* and secret. The properties are used by the {@link AuthzeroTokenResolverAutoConfiguration} to
* set up the necessary configurations for JWT generation and validation.
* <p>
* Developers can customise the JWT algorithm, issuer, and secret by setting the corresponding
* properties in the application's properties file. The {@code SimpleJwtAutoConfiguration} class
@@ -72,38 +70,14 @@ public class SimpleJwtProperties {
private String secret = SecretCreator.createSecret(32, true, true, true);
/**
* The private key of
* The private key, PEM formatted.
*/
private String privateKey;
/**
* The public key, PEM formatted
*/
private String publicKey;
/**
* Returns the JWT algorithm configured in the properties.
*
* @return the JWT algorithm
*/
public final TokenAlgorithm algorithm() {
return algorithm;
}
/**
* Returns the issuer value configured in the properties.
*
* @return the issuer value
*/
public final String issuer() {
return issuer;
}
/**
* Returns the secret key configured in the properties.
*
* @return the secret key
*/
public final String secret() {
return secret;
}
}