feat: delete jwt toolbox

Due to differing JWT requirements across projects, after careful
consideration, we have decided to remove this secondary encapsulation.
This commit is contained in:
zihluwang
2025-06-18 11:05:01 +08:00
parent fbcd0377ff
commit 7aaea4a306
25 changed files with 0 additions and 1973 deletions
-56
View File
@@ -1,56 +0,0 @@
# JWT Toolbox :: Auth0
## Introduction
**JWT Toolbox :: Auth0** module is an implementation of module JWT Toolbox, which uses third-party
library `com.auth0:java-jwt`. By using this module can help you use JWT to help you in
your application.
### 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>com.onixbyte</groupId>
<artifactId>jwt-toolbox-auth0</artifactId>
<version>${jwt-toolbox-auth0.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 restricted using the Internet, and have to make `Maven` offline, you could follow the
following steps.
1. Download the `jar` file from any place you can get and transfer the `jar` files to your
work computer.
2. Move the `jar` files to your local `Maven` Repository as the path of
`/path/to/maven_local_repo/com/onixbyte/jwt-toolbox-auth0/`.
### 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 'com.onixbyte:jwt-toolbox-auth0:${jwt-toolbox-auth0.version}'
```
## Contact
If you have any suggestions, ideas, don't hesitate contacting us via
[GitHub Issues](https://github.com/onixbyte/onixbyte-toolbox/issues/new).
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/onixbyte/onixbyte-toolbox/compare).
-138
View File
@@ -1,138 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import java.net.URI
plugins {
java
id("java-library")
id("maven-publish")
id("signing")
}
val artefactVersion: String by project
val projectUrl: String by project
val projectGithubUrl: String by project
val licenseName: String by project
val licenseUrl: String by project
group = "com.onixbyte"
version = artefactVersion
repositories {
mavenCentral()
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
withSourcesJar()
withJavadocJar()
}
tasks.withType<JavaCompile> {
options.encoding = "UTF-8"
}
tasks.withType<Jar> {
exclude("logback.xml")
}
dependencies {
compileOnly(libs.slf4j)
implementation(libs.logback)
api(project(":common-toolbox"))
api(project(":identity-generator"))
api(project(":crypto-toolbox"))
api(project(":jwt-toolbox-facade"))
api(libs.jackson.databind)
api(libs.jwt.core)
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
}
tasks.test {
useJUnitPlatform()
}
publishing {
publications {
create<MavenPublication>("jwtToolboxAuth0") {
groupId = group.toString()
artifactId = "jwt-toolbox-auth0"
version = artefactVersion
pom {
name = "OnixByte JWT Toolbox :: Auth0"
description = "Simple JWT implemented with com.auth0:java-jwt."
url = projectUrl
licenses {
license {
name = licenseName
url = licenseUrl
}
}
scm {
connection = "scm:git:git://github.com:onixbyte/onixbyte-toolbox.git"
developerConnection = "scm:git:git://github.com:onixbyte/onixbyte-toolbox.git"
url = projectGithubUrl
}
developers {
developer {
id = "zihluwang"
name = "Zihlu Wang"
email = "really@zihlu.wang"
timezone = "Asia/Hong_Kong"
}
developer {
id = "siujamo"
name = "Siu Jam'o"
email = "jamo.siu@outlook.com"
timezone = "Asia/Shanghai"
}
}
}
from(components["java"])
signing {
sign(publishing.publications["jwtToolboxAuth0"])
}
}
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,28 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.onixbyte.jwt.auth0;
import com.onixbyte.jwt.TokenGenerator;
public class Auth0TokenGenerator implements TokenGenerator {
}
@@ -1,46 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.onixbyte.jwt.auth0;
import com.onixbyte.identitygenerator.IdentityGenerator;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.onixbyte.jwt.TokenParser;
/**
*
*
* @author zihluwang
* @version 3.0.0
* @see IdentityGenerator
* @see Algorithm
* @see JWTVerifier
* @see JWTCreator
* @see JWTCreator.Builder
* @since 1.0.0
*/
public class Auth0TokenParser implements TokenParser {
}
@@ -1,39 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2024-2025 OnixByte
~
~ Permission is hereby granted, free of charge, to any person obtaining a copy
~ of this software and associated documentation files (the "Software"), to deal
~ in the Software without restriction, including without limitation the rights
~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
~ copies of the Software, and to permit persons to whom the Software is
~ furnished to do so, subject to the following conditions:
~
~ The above copyright notice and this permission notice shall be included in all
~ copies or substantial portions of the Software.
~
~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
~ SOFTWARE.
-->
<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>
-135
View File
@@ -1,135 +0,0 @@
# JWT Toolbox :: Facade
## Introduction
The JWT Toolbox Facade module is a lightweight and easy-to-use façade for working with JSON Web
Tokens (JWT) in Java applications. It provides a simplified interface and utilities to handle the
creation, validation, renewal, and processing of JWTs without the need for complex configurations or
third-party dependencies.
## Installation
### 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>com.onixbyte</groupId>
<artifactId>jwt-toolkit-facade</artifactId>
<version>${jwt-toolkit-facade.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 restricted using the Internet, and have to make `Maven` offline, you could follow the
following steps.
1. Download the `jar` file from any place you can get and transfer the `jar` files to your
work computer.
2. Move the `jar` files to your local `Maven` Repository as the path of
`/path/to/maven_local_repo/com/onixbyte/jwt-toolbox-facade/`.
### 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 'com.onixbyte:jwt-toolbox-facade:${jwt-toolbox-facade.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`.
## Implement a `TokenResolver`
If you want to use `TokenResolver` to handle with JWTs, you can choose to use any implementation such as `cn.org.codecrafters:simple-jwt-authzero` or any other `simple-jwt-$implementation_artifact`. But if you do choose to use other implementation, it is not the topic we are going to talk about here. We are here for helping you to implement one by yourself.
First, you are going to choose a third-party library or your own library which is aims to process JWTs(i.e., `com.auth0:java-jwt` and `io.jsonwebtoken:jjwt`). Then, you need to confirm which class they are going to use for a parsed JWT(i.e., `DecodedJWT` is being used in `com.auth0:java-jwt`). And let me use `com.auth0:java-jwt` for example in this tutor.
Then, you can add these following codes in your project:
```java
class Auth0TokenResolver implements TokenResolver<DecodedJWT> {
// Dont forget to implement methods in interface TokenResolver.
}
```
After doing all these, an implemented `TokenResolver` is ready to process JWTs.
**Let's pretend that you already implemented a `TokenResolver` and named as `ImplementedTokenResolver`.**
You will need an instance of the implementation to process JWTs.
```java
var tokenResolver = new ImplementedTokenResolver(/* arguments you declared */);
```
## Create a JSON Web Token with `TokenResolver`
Then, there are 3 method to create a token:
```java
String createToken(java.time.Duration expireAfter, String audience, String subject);
String createToken(java.time.Duration expireAfter, String audience, String subject, Map<String, Object> payloads);
<T extends TokenPayload> String createToken(java.time.Duration expireAfter, String audience, String subject, T payload);
```
## Read or Verify a JSON Web Token
There are many ways to read a JWT.
If you want to read as the data class which is designed by the third-party library, you can just use `resolve(String token)`. If you want know what is contained in this JWT, you can use `extract(String, Class<?>)`.
Meanwhile, the `resolve(token)` method also serves as a token validation mechanism. If any issues arise, such as token expiration, tampering suspicion, or mismatched token signatures, corresponding exceptions will be thrown.
## Renew a Token that is About to Expire
When a token is about to expire, its validity period can be extended using this method, allowing users to obtain a new valid token without the need for re-login.
**Renew a token** means that the content of the pre-defined properties by JWT, such as the audience (aud) representing the recipient of this token, will not be altered, except for the time-related fields.
```java
String renew(String oldToken, Map<String, Object> payload);
```
This method allows you to pass new custom payload into the updated token. The new token will be available for 30 minutes.
```java
String renew(String oldToken, Duration expireAfter, Map<String, Object> payload);
```
This method allows you to pass new custom payload into the updated token. The new token will be available for the specific duration.
```java
<T extends TokenPayload> String renew(String oldToken, Duration expireAfter, T payload);
```
This method allows you to pass new custom payload into the updated token. The new token will be available for 30 minutes.
```java
<T extends TokenPayload> String renew(String oldToken, Duration expireAfter, T payload);
```
This method allows you to pass new custom payload into the updated token. The new token will be available for the specific duration.
## 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).
-135
View File
@@ -1,135 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import java.net.URI
plugins {
java
id("java-library")
id("maven-publish")
id("signing")
}
val artefactVersion: String by project
val projectUrl: String by project
val projectGithubUrl: String by project
val licenseName: String by project
val licenseUrl: String by project
group = "com.onixbyte"
version = artefactVersion
repositories {
mavenCentral()
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
withSourcesJar()
withJavadocJar()
}
tasks.withType<JavaCompile> {
options.encoding = "UTF-8"
}
tasks.withType<Jar> {
exclude("logback.xml")
}
dependencies {
compileOnly(libs.slf4j)
implementation(libs.logback)
api(project(":common-toolbox"))
api(project(":identity-generator"))
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
}
tasks.test {
useJUnitPlatform()
}
publishing {
publications {
create<MavenPublication>("jwtToolboxFacade") {
groupId = group.toString()
artifactId = "jwt-toolbox-facade"
version = artefactVersion
pom {
name = "OnixByte JWT Toolbox :: Facade"
description = "Declaration of simple JWT module."
url = projectUrl
licenses {
license {
name = licenseName
url = licenseUrl
}
}
scm {
connection = "scm:git:git://github.com:onixbyte/onixbyte-toolbox.git"
developerConnection = "scm:git:git://github.com:onixbyte/onixbyte-toolbox.git"
url = projectGithubUrl
}
developers {
developer {
id = "zihluwang"
name = "Zihlu Wang"
email = "really@zihlu.wang"
timezone = "Asia/Hong_Kong"
}
developer {
id = "siujamo"
name = "Siu Jam'o"
email = "jamo.siu@outlook.com"
timezone = "Asia/Shanghai"
}
}
}
from(components["java"])
signing {
sign(publishing.publications["jwtToolboxFacade"])
}
}
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,162 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.onixbyte.jwt;
import com.onixbyte.jwt.exceptions.WeakSecretException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Random;
/**
* {@code SecretCreator} is a utility class that provides methods to generate secure secret strings.
* The generated secrets can be used as cryptographic keys or passwords for various
* security-sensitive purposes.
*
* @author zihluwang
* @version 3.0.0
* @since 1.0.0
*/
public final class SecretCreator {
/**
* Generates a secure secret with the specified length and character sets.
*
* @param length the length of the secret to be generated
* @param isContainCapital flag indicating if the secret should contain
* uppercase letters
* @param isContainDigital flag indicating if the secret should contain
* digits
* @param isContainSpecialSign flag indicating if the secret should contain
* special sign characters
* @return the generated secure secret
* @throws WeakSecretException if the requested secret length is less than
* 32 characters
*/
public static String createSecret(int length,
boolean isContainCapital,
boolean isContainDigital,
boolean isContainSpecialSign) {
if (length < 32) {
throw new WeakSecretException("""
The requested secret, which is only %d characters long, is too weak. \
Please replace it with a stronger secret.""".formatted(length));
}
final var randomiser = new Random();
var charset = new StringBuilder(LOWERCASE_CHARACTERS);
if (isContainCapital) charset.append(UPPERCASE_CHARACTERS);
if (isContainDigital) charset.append(DIGITS);
if (isContainSpecialSign) charset.append(SPECIAL_SIGNS);
var secretBuilder = new StringBuilder();
var charsetSize = charset.length();
for (var i = 0; i < length; ++i) {
secretBuilder.append(charset.charAt(randomiser.nextInt(charsetSize)));
}
return secretBuilder.toString();
}
/**
* Generates a secure secret with the specified length, containing
* uppercase letters and digits.
*
* @param length the length of the secret to be generated
* @param isContainCapital flag indicating if the secret should contain
* uppercase letters
* @param isContainDigital flag indicating if the secret should contain
* digits
* @return the generated secure secret
* @throws WeakSecretException if the requested secret length is less than
* 32 characters
* @see #createSecret(int, boolean, boolean, boolean)
*/
public static String createSecret(int length,
boolean isContainCapital,
boolean isContainDigital) {
return createSecret(length, isContainCapital, isContainDigital, false);
}
/**
* Generates a secure secret with the specified length, containing
* uppercase letters.
*
* @param length the length of the secret to be generated
* @param isContainCapital flag indicating if the secret should contain
* uppercase letters
* @return the generated secure secret
* @throws WeakSecretException if the requested secret length is less than
* 32 characters
* @see #createSecret(int, boolean, boolean, boolean)
*/
public static String createSecret(int length,
boolean isContainCapital) {
return createSecret(length, isContainCapital, false, false);
}
/**
* Generates a secure secret with the specified length, containing
* lowercase letters.
*
* @param length the length of the secret to be generated
* @return the generated secure secret
* @throws WeakSecretException if the requested secret length is less than
* 32 characters
* @see #createSecret(int, boolean, boolean, boolean)
*/
public static String createSecret(int length) {
return createSecret(length, false, false, false);
}
/**
* Private constructor to prevent instantiation of this utility class.
*/
private SecretCreator() {
}
/**
* The string containing all lowercase characters that can be used to
* generate the secret.
*/
private static final String LOWERCASE_CHARACTERS = "abcdefghijklmnopqrstuvwxyz";
/**
* The string containing all uppercase characters that can be used to
* generate the secret.
*/
private static final String UPPERCASE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/**
* The string containing all digit characters that can be used to generate
* the secret.
*/
private static final String DIGITS = "0123456789";
/**
* The string containing all special sign characters that can be used to
* generate the secret.
*/
private static final String SPECIAL_SIGNS = "!@#$%^&,*()_+-=,[]{}|;:,'\",.<>/?";
}
@@ -1,26 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.onixbyte.jwt;
public interface TokenGenerator {
}
@@ -1,26 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.onixbyte.jwt;
public interface TokenParser {
}
@@ -1,110 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.onixbyte.jwt.constants;
import java.util.List;
/**
* The {@code PredefinedKeys} class contains constants for standard JSON Web Token (JWT) claims. These constants
* represent the names of the standard claims that can be included in a JWT payload. Developers can use these constants
* when working with JWTs to ensure consistent naming of the claims.
* <p>
* The class provides the following standard JWT claim constants:
* <ul>
* <li>{@link #ISSUER}: Represents the "iss" (Issuer) claim.</li>
* <li>{@link #SUBJECT}: Represents the "sub" (Subject) claim.</li>
* <li>{@link #AUDIENCE}: Represents the "aud" (Audience) claim.</li>
* <li>{@link #EXPIRATION_TIME}: Represents the "exp" (Expiration Time) claim.</li>
* <li>{@link #NOT_BEFORE}: Represents the "nbf" (Not Before) claim.</li>
* <li>{@link #ISSUED_AT}: Represents the "iat" (Issued At) claim.</li>
* <li>{@link #JWT_ID}: Represents the "jti" (JWT ID) claim.</li>
* </ul>
* <p>
* The class also contains a list of all the standard claim constants, accessible via the {@link
* #KEYS} field. This list can be useful for iterating through all the standard claims or checking
* for the presence of specific claims.
* <p>
* Note: This class is final and cannot be instantiated. It only serves as a utility class to hold
* the standard JWT claim constants.
*
* @author zihluwang
* @version 3.0.0
* @since 1.0.0
*/
public final class PredefinedKeys {
/**
* Constant representing the "iss" (Issuer) claim in a JWT payload.
*/
public static final String ISSUER = "iss";
/**
* Constant representing the "sub" (Subject) claim in a JWT payload.
*/
public static final String SUBJECT = "sub";
/**
* Constant representing the "aud" (Audience) claim in a JWT payload.
*/
public static final String AUDIENCE = "aud";
/**
* Constant representing the "exp" (Expiration Time) claim in a JWT payload.
*/
public static final String EXPIRATION_TIME = "exp";
/**
* Constant representing the "nbf" (Not Before) claim in a JWT payload.
*/
public static final String NOT_BEFORE = "nbf";
/**
* Constant representing the "iat" (Issued At) claim in a JWT payload.
*/
public static final String ISSUED_AT = "iat";
/**
* Constant representing the "jti" (JWT ID) claim in a JWT payload.
*/
public static final String JWT_ID = "jti";
/**
* List containing all the standard JWT claim constants.
*/
public static final List<String> KEYS = List.of(
ISSUER,
SUBJECT,
AUDIENCE,
EXPIRATION_TIME,
NOT_BEFORE,
ISSUED_AT,
JWT_ID
);
/**
* Private constructor to prevent instantiation of this utility class.
*/
private PredefinedKeys() {
}
}
@@ -1,97 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.onixbyte.jwt.constants;
/**
* The {@code TokenAlgorithm} enum class defines the algorithms that can be
* used for signing and verifying JSON Web Tokens (JWT). JWT allows various
* cryptographic algorithms to be used for secure token generation and
* validation. This enum provides a list of supported algorithms to ensure
* consistent usage and avoid potential security issues.
* <p>
* <b>Supported Algorithms:</b>
* <ul>
* <li>{@link TokenAlgorithm#HS256}: HMAC SHA-256</li>
* <li>{@link TokenAlgorithm#HS384}: HMAC SHA-384</li>
* <li>{@link TokenAlgorithm#HS512}: HMAC SHA-512</li>
* <li>{@link TokenAlgorithm#RS256}: RSA PKCS#1 v1.5 with SHA-256</li>
* <li>{@link TokenAlgorithm#RS384}: RSA PKCS#1 v1.5 with SHA-384</li>
* <li>{@link TokenAlgorithm#RS512}: RSA PKCS#1 v1.5 with SHA-512</li>
* <li>{@link TokenAlgorithm#ES256}: ECDSA with SHA-256</li>
* <li>{@link TokenAlgorithm#ES384}: ECDSA with SHA-384</li>
* <li>{@link TokenAlgorithm#ES512}: ECDSA with SHA-512</li>
* </ul>
*
* @author zihluwang
* @version 3.0.0
* @since 1.0.0
*/
public enum TokenAlgorithm {
/**
* HMAC using SHA-256
*/
HS256,
/**
* HMAC using SHA-384
*/
HS384,
/**
* HMAC using SHA-512
*/
HS512,
/**
* RSASSA-PKCS-v1_5 using SHA-256
*/
RS256,
/**
* RSASSA-PKCS-v1_5 using SHA-384
*/
RS384,
/**
* RSASSA-PKCS-v1_5 using SHA-512
*/
RS512,
/**
* ECDSA using P-256 and SHA-256
*/
ES256,
/**
* ECDSA using P-384 and SHA-384
*/
ES384,
/**
* ECDSA using P-521 and SHA-512
*/
ES512,
;
}
@@ -1,58 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.onixbyte.jwt.exceptions;
/**
* {@link IllegalKeyPairException} indicates an exception that the key pair is invalid.
*
* @author zihluwang
* @version 3.0.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);
}
}
@@ -1,59 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.onixbyte.jwt.exceptions;
/**
* {@code 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);
}
}
@@ -1,106 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.onixbyte.jwt.exceptions;
/**
* <p>
* If you want the supports to an unsupported algorithm, you could
* <ul>
* <li>Commit an issue at GitHub Issues or;</li>
* <li>Communicate with us on Discord Community.</li>
* </ul>
*
* @author zihluwang
* @version 3.0.0
*/
public class UnsupportedAlgorithmException extends RuntimeException {
/**
* Constructs a new {@code UnsupportedAlgorithmException} with {@code null} as its
* detail message. The cause is not initialized, and may subsequently be initialized by a call
* to {@link #initCause}.
*/
public UnsupportedAlgorithmException() {
}
/**
* Constructs a new {@code UnsupportedAlgorithmException} with the specified detail message.
* The cause is not initialized, and may subsequently be initialized by a call
* to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
*/
public UnsupportedAlgorithmException(String message) {
super(message);
}
/**
* Constructs a new {@code UnsupportedAlgorithmException} with the specified detail message
* and cause.
*
* @param message the detail message (which is saved for later retrieval by the
* {@link #getMessage()} method)
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is permitted, and
* indicates that the cause is nonexistent or unknown.)
* @since 1.4
*/
public UnsupportedAlgorithmException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new {@code UnsupportedAlgorithmException} with the specified cause and a detail
* message of {@code (cause==null ? null : cause.toString())} (which typically contains the
* class and detail message of {@code cause}). This constructor is useful for runtime
* exceptions that are little more than wrappers for other throwable.
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is permitted, and indicates
* that the cause is nonexistent or unknown.)
* @since 1.4
*/
public UnsupportedAlgorithmException(Throwable cause) {
super(cause);
}
/**
* Constructs a new {@code UnsupportedAlgorithmException} with the specified detail message,
* cause, suppression enabled or disabled, and writable stack trace enabled or disabled.
*
* @param message the detail message.
* @param cause the cause (A {@code null} value is permitted, and indicates that
* the cause is nonexistent or unknown.)
* @param enableSuppression whether suppression is enabled or disabled
* @param writableStackTrace whether the stack trace should be writable
* @since 1.0.0
*/
public UnsupportedAlgorithmException(
String message,
Throwable cause,
boolean enableSuppression,
boolean writableStackTrace
) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
@@ -1,107 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.onixbyte.jwt.exceptions;
/**
* {@code WeakSecretException} represents that your secret is too weak to be used in signing JWTs.
* <p>
* {@code WeakSecretException} will only appears that if you are using the implementation module
* {@code com.onixbyte:jwt-toolbox-auth0} due to it is implemented by {@code com.auth0:java-jwt}.
*
* @author zihluwang
* @version 3.0.0
* @since 1.0.0
*/
public class WeakSecretException extends RuntimeException {
/**
* Constructs a new {@code WeakSecretException} with {@code null} as its detail message.
* The cause is not initialized, and may subsequently be initialized by a call
* to {@link #initCause}.
*/
public WeakSecretException() {
}
/**
* Constructs a new {@code WeakSecretException} with the specified detail message. The cause is
* not initialised, and may subsequently be initialized by a call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for later retrieval by the
* {@link #getMessage()} method.
*/
public WeakSecretException(String message) {
super(message);
}
/**
* Constructs a new {@code WeakSecretException} with the specified detail message and cause.
* <p>
* Note that the detail message associated with {@code cause} is <i>not</i> automatically
* incorporated in this runtime exception's detail message.
*
* @param message the detail message (which is saved for later retrieval by the
* {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is permitted, and
* indicates that the cause is nonexistent or unknown.)
* @since 1.0.0
*/
public WeakSecretException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new {@code WeakSecretException} with the specified cause and a detail message
* of {@code (cause==null ? null : cause.toString())} (which typically contains the class and
* detail message of {@code cause}). This constructor is useful for runtime exceptions that are
* little more than wrappers for other throwable.
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is permitted, and indicates
* that the cause is nonexistent or unknown.)
* @since 1.0.0
*/
public WeakSecretException(Throwable cause) {
super(cause);
}
/**
* Constructs a new {@code WeakSecretException} with the specified detail message, cause,
* suppression enabled or disabled, and writable stack trace enabled or disabled.
*
* @param message the detail message.
* @param cause the cause. (A {@code null} value is permitted, and indicates that
* the cause is nonexistent or unknown.)
* @param enableSuppression whether suppression is enabled or disabled
* @param writableStackTrace whether the stack trace should be writable
* @since 1.0.0
*/
public WeakSecretException(
String message,
Throwable cause,
boolean enableSuppression,
boolean writableStackTrace
) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
@@ -1,39 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2024-2025 OnixByte
~
~ Permission is hereby granted, free of charge, to any person obtaining a copy
~ of this software and associated documentation files (the "Software"), to deal
~ in the Software without restriction, including without limitation the rights
~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
~ copies of the Software, and to permit persons to whom the Software is
~ furnished to do so, subject to the following conditions:
~
~ The above copyright notice and this permission notice shall be included in all
~ copies or substantial portions of the Software.
~
~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
~ SOFTWARE.
-->
<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>
-108
View File
@@ -1,108 +0,0 @@
# JWT Toolbox :: Spring Boot Starter
## Introduction
Module **JWT Toolbox :: Spring Boot Starter** is a lightweight and easy-to-use Spring Boot starter
module that provides seamless integration with JSON Web Token (JWT) authentication in Spring Boot
applications. With this starter, developers can easily configure and enable JWT-based authentication
for their APIs and web applications without the need for complex manual setup. It simplifies the
process of generating and validating JWTs, making it effortless to secure endpoints and implement
token-based authentication in Spring Boot projects. The module is designed to be flexible, allowing
developers to customize various aspects of JWT authentication to suit their specific requirements.
Overall, `jwt-toolbox-spring-boot-starter` is a convenient solution for adding secure and efficient JWT authentication to Spring Boot applications.
## Prerequisites
- This whole `JDevKit` is developed by **JDK 17**, which means you have to use JDK 17 for better experience.
- You also need an implementation of any `simple-jwt-$implementation` module to make sure you can create an instance of `TokenResolver`.
### Known Implementation
> If you implemented one on your own, please contact us to add your artifact to this list.
- [`cn.org.codecrafters:simple-jwt-authzero`](../simple-jwt-authzero/README.md)
- [`cn.org.codecrafters:simple-jwt-jjwt`](../simple-jwt-jjwt/README.md)
## Installation
### 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>${implementation-builder-group-id}</groupId>
<artifactId>simple-jwt-${any-implementation}</artifactId>
<version>${simple-jwt-${any-implementation}.version}</version>
</dependency>
<dependency>
<groupId>com.onixbyte</groupId>
<artifactId>simple-jwt-spring-boot-starter</artifactId>
<version>${simple-jwt-spring-boot-starter.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 restricted using the Internet, and have to make `Maven` offline, you could follow the following steps.
1. Download the `jar` file from any place you can get and transfer the `jar` files to your work computer.
2. Move the `jar` files to your local `Maven` Repository as the path of `/path/to/maven_local_repo/cn/org/codecrafters/simple-jwt-spring-boot-starter/` and `/path/to/maven_local_repo/${implementation-builder-group-seperated-by-system-seperator}/${implementation_artifact_id}`.
### 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 '${implementation-builder-group-id}:simple-jwt-${any-implementation}:${simple-jwt-${any-implementation}.version}'
implementation 'com.onixbyte:simple-jwt-spring-boot-starter:${simple-jwt-spring-boot-starter.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`.
## Configuration
### Configuration for a customized JWT ID Creator
We need a `GuidCreator` instance to create JWT ID, though we did implemented a simple `GuidCreator`, but you can still customize it.
First, please implement the `com.onixbyte.identitygenerator.IdentityGenerator` interface based on your own rules for generating JWT IDs.
Then, add the instance of your own guid creator to spring container, whose name is `jtiCreator`.
Here is a simple example which uses class `Random` to create guid.
```java
@Bean
public GuidCreator<?> jtiCreator() {
return new GuidCreator<Long>() {
private final Random random = new Random();
@Override
public Long nextId() {
return random.nextLong();
}
};
}
```
### `TokenResolver` Configuration
| Property Name | Type | Description |
| ------------------------------------ | ---------------- | ------------------------------------------------------ |
| `code-crafters.simple-jwt.algorithm` | `TokenAlgorithm` | The algorithm used for JWT generation and validation. |
| `code-crafters.simple-jwt.issuer` | `String` | The issuer value to be included in the generated JWT. |
| `code-crafters.simple-jwt.secret` | `String` | The secret key used for JWT generation and validation. |
## 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).
@@ -1,148 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import java.net.URI
plugins {
java
id("java-library")
id("maven-publish")
id("signing")
}
val artefactVersion: String by project
val projectUrl: String by project
val projectGithubUrl: String by project
val licenseName: String by project
val licenseUrl: String by project
group = "com.onixbyte"
version = artefactVersion
repositories {
mavenCentral()
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
withSourcesJar()
withJavadocJar()
}
tasks.withType<JavaCompile> {
options.encoding = "UTF-8"
}
tasks.withType<Jar> {
exclude("logback.xml")
}
dependencies {
compileOnly(libs.slf4j)
implementation(libs.logback)
api(project(":identity-generator"))
api(project(":jwt-toolbox-facade"))
api(project(":jwt-toolbox-auth0"))
implementation(libs.springBoot.autoconfigure)
implementation(libs.springBoot.starter.logging)
implementation(libs.springBoot.configurationProcessor)
annotationProcessor(libs.springBoot.configurationProcessor)
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testImplementation(libs.springBoot.starter.test)
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
withSourcesJar()
withJavadocJar()
}
tasks.test {
useJUnitPlatform()
}
publishing {
publications {
create<MavenPublication>("jwtSpringBootStarter") {
groupId = group.toString()
artifactId = "jwt-spring-boot-starter"
version = artefactVersion
pom {
name = "OnixByte JWT Toolbox :: Spring Boot Starter"
description = "Simple JWT all-in-one package for Spring Boot."
url = projectUrl
licenses {
license {
name = licenseName
url = licenseUrl
}
}
scm {
connection = "scm:git:git://github.com:onixbyte/onixbyte-toolbox.git"
developerConnection = "scm:git:git://github.com:onixbyte/onixbyte-toolbox.git"
url = projectGithubUrl
}
developers {
developer {
id = "zihluwang"
name = "Zihlu Wang"
email = "really@zihlu.wang"
timezone = "Asia/Hong_Kong"
}
developer {
id = "siujamo"
name = "Siu Jam'o"
email = "jamo.siu@outlook.com"
timezone = "Asia/Shanghai"
}
}
}
from(components["java"])
signing {
sign(publishing.publications["jwtSpringBootStarter"])
}
}
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,64 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.onixbyte.jwt.autoconfiguration;
import com.onixbyte.identitygenerator.IdentityGenerator;
import com.onixbyte.jwt.autoconfiguration.conditions.GuidCreatorCondition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import java.util.UUID;
/**
* Autoconfiguration for injecting a {@link IdentityGenerator} for generating jwt id.
*
* @author Zihlu Wang
* @version 1.1.0
* @since 1.0.0
*/
@AutoConfiguration
public class GuidAutoConfiguration {
private final static Logger log = LoggerFactory.getLogger(GuidAutoConfiguration.class);
/**
* Default constructor.
*/
public GuidAutoConfiguration() {
}
/**
* Create a default {@code jtiCreator} with UUID.
*
* @return UUID creator
*/
@Bean(name = "jtiCreator")
@Conditional(GuidCreatorCondition.class)
public IdentityGenerator<?> jtiCreator() {
return UUID::randomUUID;
}
}
@@ -1,69 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.onixbyte.jwt.autoconfiguration.conditions;
import com.onixbyte.identitygenerator.IdentityGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import java.util.Objects;
/**
* The conditions to create bean {@code jtiCreator}.
*
* @author zihluwang
* @version 3.0.0
* @since 1.0.0
*/
public class GuidCreatorCondition implements Condition {
/**
* Default constructor.
*/
public GuidCreatorCondition() {
}
/**
* The condition to create bean {@code jtiCreator}.
* <p>
* If Spring does not have a bean of type {@link IdentityGenerator} named {@code jtiCreator} in the
* application context, then create {@code jtiCreator}.
*
* @param context the spring application context
* @param metadata the metadata of the {@link org.springframework.core.type.AnnotationMetadata
* class} or {@link org.springframework.core.type.MethodMetadata method}
* being checked
*/
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
final var beanFactory = Objects.requireNonNull(context.getBeanFactory());
var isContainJtiCreator = beanFactory.containsBean("jtiCreator");
if (isContainJtiCreator) {
return !(beanFactory.getBean("jtiCreator") instanceof IdentityGenerator<?>);
}
return true;
}
}
@@ -1,174 +0,0 @@
/*
* Copyright (c) 2024-2025 OnixByte
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.onixbyte.jwt.autoconfiguration.properties;
import com.onixbyte.jwt.SecretCreator;
import com.onixbyte.jwt.constants.TokenAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* {@code JwtProperties} is a configuration properties class used to store the properties
* related to Simple JWT library configurations. These properties can be configured in the
* application's properties file (e.g., application.properties) with the prefix
* "onixbyte.simple-jwt".
* <p>
* {@code JwtProperties} provides configuration options for the JWT algorithm, issuer,
* and secret. The properties are used by the {@code Auth0AutoConfiguration} 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 Auth0AutoConfiguration} class
* reads these properties and uses them to create the TokenResolver bean with the
* desired configuration.
*
* @author Zihlu Wang
* @version 1.1.0
* @since 1.0.0
*/
// @ConfigurationProperties(prefix = "onixbyte.jwt")
public class JwtProperties {
/**
* Default constructor.
*/
public JwtProperties() {
}
/**
* The algorithm used for JWT generation and validation. Default value is
* {@link TokenAlgorithm#HS256}
*/
private TokenAlgorithm algorithm = TokenAlgorithm.HS256;
/**
* The issuer value to be included in the generated JWT. Default value is an empty String.
*/
private String issuer = "";
/**
* The secret key used for JWT generation and validation. Default value is the result of call to
* {@link SecretCreator#createSecret(int, boolean, boolean, boolean)}.
*/
private String secret = SecretCreator.createSecret(32, true, true, true);
/**
* The private key, PEM formatted.
*/
private String privateKey;
/**
* The public key, PEM formatted
*/
private String publicKey;
/**
* Algorithm getter.
*
* @return algorithm
*/
public TokenAlgorithm getAlgorithm() {
return algorithm;
}
/**
* Algorithm setter.
*
* @param algorithm the algorithm
*/
public void setAlgorithm(TokenAlgorithm algorithm) {
this.algorithm = algorithm;
}
/**
* Issuer getter.
*
* @return issuer
*/
public String getIssuer() {
return issuer;
}
/**
* Issuer setter.
*
* @param issuer the issuer
*/
public void setIssuer(String issuer) {
this.issuer = issuer;
}
/**
* Secret setter.
*
* @return secret
*/
public String getSecret() {
return secret;
}
/**
* Secret setter.
*
* @param secret the secret
*/
public void setSecret(String secret) {
this.secret = secret;
}
/**
* Private key getter.
*
* @return private key
*/
public String getPrivateKey() {
return privateKey;
}
/**
* Private key setter.
*
* @param privateKey private key
*/
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
/**
* Public key getter.
*
* @return public key
*/
public String getPublicKey() {
return publicKey;
}
/**
* Public key setter.
*
* @param publicKey public key
*/
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
}
@@ -1 +0,0 @@
com.onixbyte.jwt.autoconfiguration.GuidAutoConfiguration
@@ -1,39 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2024-2025 OnixByte
~
~ Permission is hereby granted, free of charge, to any person obtaining a copy
~ of this software and associated documentation files (the "Software"), to deal
~ in the Software without restriction, including without limitation the rights
~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
~ copies of the Software, and to permit persons to whom the Software is
~ furnished to do so, subject to the following conditions:
~
~ The above copyright notice and this permission notice shall be included in all
~ copies or substantial portions of the Software.
~
~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
~ SOFTWARE.
-->
<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>
-3
View File
@@ -23,7 +23,4 @@ include(
"identity-generator", "identity-generator",
"crypto-toolbox", "crypto-toolbox",
"math-toolbox", "math-toolbox",
"jwt-toolbox-facade",
"jwt-toolbox-auth0",
"jwt-toolbox-spring-boot-starter",
) )