JwtTokenService
Name | JwtTokenService |
Class Path |
|
Versions | 9 10 11 |
Overview
The JwtTokenService
class provides functionality for generating and verifying JSON Web Tokens (JWT) using both symmetric (HMAC) and asymmetric (RSA) cryptographic algorithms.
Available Methods
Extracting Payload from JWT
String extractPayload(String token, String key)
Extracts the payload (claims) from a JWT while verifying its signature.
Parameters:
token
(String
): The JWT string.key
(String
): The secret key for HMAC algorithms or the public key for RSA algorithms.
Returns:
String
: The extracted payload in JSON format.
Throws:
GeneralSecurityException
: If the signature verification fails or an invalid algorithm is provided.
Creating a JWT
String createJwtToken(String algorithm, String key, String claims)
Creates a signed JWT using the specified algorithm and key.
Parameters:
algorithm
(String
): The algorithm to use ("HS256"
,"HS384"
,"HS512"
,"RS256"
,"RS384"
,"RS512"
).key
(String
): The secret key for HMAC algorithms or the private key for RSA algorithms.claims
(String
): The claims (payload) to be included in the JWT in JSON format.
Returns:
String
: The generated JWT.
Throws:
GeneralSecurityException
: If an invalid algorithm is provided or signing fails.
Supported Algorithms
The service supports the following JWT signing algorithms:
Algorithm | Type | Description |
---|---|---|
| HMAC | HMAC with SHA-256 |
| HMAC | HMAC with SHA-384 |
| HMAC | HMAC with SHA-512 |
| RSA | RSA with SHA-256 |
| RSA | RSA with SHA-384 |
| RSA | RSA with SHA-512 |
| No Signature | JWT with no signature |
HMAC-based (
HS256
,HS384
,HS512
)
Uses a shared secret key to sign and verify JWTs.RSA-based (
RS256
,RS384
,RS512
)
Uses a private key for signing and a public key for verification.None (
NONE
)
Allows unsigned JWTs.
Security Considerations
Always use strong keys for HMAC-based JWTs.
For RSA-based JWTs, securely store private keys and distribute public keys appropriately.
Avoid using
"NONE"
as an algorithm in production environments.Always validate JWT expiration (
"exp"
) claims before accepting them.
The JwtTokenService
provides robust JWT handling with both symmetric and asymmetric cryptographic security mechanisms.