dawdler-client-plug-jwt
Module Introduction
JWT authentication module that, based on the web architecture of dawdler-client-plug-web, provides token issuance, parsing, validation, and request authentication. It requires no third-party dependencies and uses JDK-native implementations of HMAC (HS256/384/512) and RSA (RS256/384/512) signatures.
Through the SPI (DawdlerFilterInitializer), DawdlerJwtFilter is registered automatically (URL pattern /*, isMatchAfter=true) and runs after ViewFilter.
1. Add the dependency to pom
<groupId>club.dawdler</groupId>
<artifactId>dawdler-client-plug-jwt</artifactId>
Once added, the filter takes effect automatically. When non-key items are not configured, the default configuration inside the jar is used, but the HS* algorithms must have secret configured in jwt.properties (or the unified configuration center), and the RS* algorithms must have a key pair configured; otherwise startup fails (fail fast, no well-known default keys are provided).
2. jwt.properties file description
Create a jwt.properties under the classpath to override the default configuration; the unified configuration center and multiple environments are supported (refer to dawdler.profiles.active).
# Signature algorithm, supports HS256 HS384 HS512 RS256 RS384 RS512
algorithm=HS256
# HMAC secret (used by HS* algorithms), counted in UTF-8 bytes: HS256>=32 HS384>=48 HS512>=64
# Generation: openssl rand -base64 48 (its output is >=32 in bytes, satisfying all three HS algorithms)
secret=replace with a random key generated by openssl rand -base64 48
# RSA private key (used when signing with RS* algorithms), supports base64 (DER) or PEM format
rsaPrivateKey=
# RSA public key (used when verifying RS* signatures), supports base64 (DER) or PEM format
rsaPublicKey=
# How to obtain the token: header, cookie, or param, optionally combined and separated by commas
tokenFrom=header
headerName=Authorization
headerPrefix=Bearer
cookieName=token
paramName=token
# ---- Security attributes when credentials are carried via cookie (effective when tokenFrom includes cookie) ----
# csrfEnabled is disabled by default; cookies are sent automatically by browsers, so it must be enabled for externally exposed services
csrfEnabled=false
csrfMethods=POST,PUT,DELETE,PATCH
csrfExcludePaths=
csrfHeaderName=X-CSRF-Token
csrfCookieName=dawdler_csrf
# Bind the csrf token to the credential to block cross-site cookie writes (login csrf); true is recommended
csrfBind=true
# Additionally require Origin/Referer to be same-origin with the application
csrfCheckOrigin=true
# List of trusted proxy addresses/CIDRs, comma-separated; X-Forwarded-Host/Proto/Port is trusted only when the request peer matches
csrfTrustedProxies=
csrfRotate=false
cookieHttpOnly=true
cookieSameSite=Lax
cookieSecure=false
cookieDomain=
cookiePath=/
cookieMaxAge=
# Issuer; validation requires the token's iss to match it; if empty, it is not validated
issuer=
# Audience; validation requires the token's aud to contain this value; if empty, it is not validated
audience=
# Token expiration time (seconds), used when exp is not explicitly set at signing time
expireSeconds=7200
# Allowed clock skew (seconds), used for exp/nbf validation
leewaySeconds=0
# Whether to reject requests (return 401) when the token is invalid or missing; if false, only parse and populate the context without rejecting
rejectOnInvalid=true
# Whitelist of URIs that need no validation, comma-separated, antPath supported, e.g. /login,/public/**
excludePaths=/login,/public/**
# HTTP status code returned on rejection
unauthorizedStatus=401
# Response body returned on rejection
unauthorizedBody={"code":401,"msg":"unauthorized"}
3. Signing tokens
On the business side (e.g., after a successful login), obtain a JwtOperator via JwtConfig to sign a token.
import java.time.Instant;
import club.dawdler.clientplug.web.jwt.JwtConfig;
import club.dawdler.clientplug.web.jwt.claim.JwtClaims;
import club.dawdler.clientplug.web.jwt.operator.JwtOperator;
JwtOperator operator = JwtConfig.getInstance().getJwtOperator();
String token = operator.sign(JwtClaims.create()
.setSubject(userId)
.setIssuer("dawdler")
.setAudience("web")
.setExpiration(Instant.now().plusSeconds(7200)));
// Return the token to the front end, which carries it via Authorization: Bearer <token>
Note: during sign, if iat is not set it is automatically filled with the current time, and if exp is not set and expireSeconds>0 the expiration time is automatically filled.
3.1 Cross-site protection (CSRF) when credentials are carried via cookie
When tokenFrom includes cookie, browsers send the credential automatically, and a cross-site request can impersonate the identity without knowing the token. Therefore the following measures are needed:
- SameSite/Secure/HttpOnly: controlled by
cookieSameSite/cookieSecure/cookieHttpOnly, applied uniformly when the framework issues cookies;SameSite=Noneautomatically addsSecure(only needed for cross-origin front ends, in which case CSRF validation is the only line of defense). - Double-submit validation (
csrfEnabled=true): non-safe methods (csrfMethods) must carry both the cookiecsrfCookieNameand the request headercsrfHeaderName, and the two must match to be allowed through;csrfExcludePathscan allow paths such as login. - Same-origin validation (
csrfCheckOrigin=true): additionally requiresOrigin(orReferer) to be same-origin with the application; if both are absent, they are treated as cross-origin.X-Forwarded-Host/X-Forwarded-Proto/X-Forwarded-Portare trusted only when the request peer matchescsrfTrustedProxies; otherwise the scheme/host/port observed by the container are always used -- these headers can be forged by clients, and trusting them unconditionally would degrade same-origin validation to "attacker-controlled value vs attacker-controlled value" and always allow through. When the application runs behind Nginx/a gateway and the proxy rewrites the Host, the proxy address or internal network segment must be configured incsrfTrustedProxies(e.g.10.0.0.0/8or192.168.1.237). The proxy must overwrite these headers (e.g., Nginxproxy_set_header X-Forwarded-Host $host) rather than pass through client-submitted values as-is. - Credential binding (
csrfBind=true, default): the csrf token is derived from the credential content, used to block "cross-site cookie writes" (an attacker first obtains their own cookie pair and then uses a cross-site request to write it into the victim's browser). Therefore the login endpoint should issue cookies through the framework and not assemble Set-Cookie by itself.
After a successful login, the framework issues the credential cookie and the csrf cookie; the front end reads dawdler_csrf and sends it back in the X-CSRF-Token request header:
// After a successful login
DawdlerJwtFilter.writeAuthCookie(request, token);
// Logout
DawdlerJwtFilter.deleteAuthCookie(request);
Cookies are written to the response when the request finishes, avoiding conflicts with the business code's own addCookie.
4. Getting the current logged-in user
After authentication passes, the filter automatically binds the claims to the current thread and the request attributes; the business side obtains them via JwtContext.
import club.dawdler.clientplug.web.jwt.context.JwtContext;
import club.dawdler.clientplug.web.jwt.claim.JwtClaims;
JwtClaims claims = JwtContext.get(); // thread-level, may be null
String userId = claims.getSubject();
Object role = claims.getClaim("role");
5. Authentication behavior
- Requests matching the
excludePathswhitelist (antPath supported) are allowed through directly without validation. - Other requests extract the token according to the order of
tokenFrom, then validate the signature andexp,nbf,iss,aud. - Validation passes:
JwtContextis bound, and subsequent filters and the Controller continue to execute. - Validation fails or the token is missing: if
rejectOnInvalid=true(default), theunauthorizedStatusandunauthorizedBodyare returned and processing stops; iffalse, the request is allowed through without binding the context, and the business decides whetherJwtContext.get()is null.
6. RSA key notes
rsaPrivateKey is in PKCS#8 format and rsaPublicKey is in X.509 format; both accept a base64 (DER) or PEM string (the -----BEGIN/END----- markers and line breaks are removed automatically). Signing tokens requires the private key, and validating tokens requires the public key. A typical scenario is that the gateway/server configures only the public key for verification, while the authentication center configures the private key for signing.
7. Unified configuration center and multi-environment support
Refer to Unified configuration center and multi-environment support