Class JwtUtils
This component provides functionality for JWT token generation, validation, and parsing. It uses the JJWT library to create and verify JSON Web Tokens used for authentication and authorization throughout the application. The tokens are signed with HMAC-SHA512 for security.
Key capabilities include:
- Token generation for authenticated users
- Token validation to verify integrity and expiration
- Extraction of username from tokens for authentication
- Configurable secret key and token expiration time
This class is configured via properties that can be set in application.properties:
- jobportal.app.jwtSecret - The secret key used for signing tokens
- jobportal.app.jwtExpirationMs - The token validity period in milliseconds
- Since:
- 2025-05-15
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptiongenerateJwtToken(String username) Generates a JWT token for a user.getUserNameFromJwtToken(String token) Extracts the username from a JWT token.booleanvalidateJwtToken(String authToken) Validates a JWT token.
-
Constructor Details
-
JwtUtils
public JwtUtils()Constructs a new JwtUtils instance.Default constructor that allows Spring to initialize this component and inject the necessary property values from the application configuration.
-
-
Method Details
-
generateJwtToken
Generates a JWT token for a user.Creates a new signed token containing the username as subject, issue time, and expiration time. The token is signed with HMAC-SHA512 using the configured secret key.
- Parameters:
username- the username to include in the token- Returns:
- the JWT token string
-
getUserNameFromJwtToken
Extracts the username from a JWT token.Parses the token, verifies its signature using the signing key, and extracts the subject claim which contains the username.
- Parameters:
token- the JWT token string- Returns:
- the username from the token
- Throws:
io.jsonwebtoken.JwtException- if the token is invalid or cannot be parsed
-
validateJwtToken
Validates a JWT token.Checks if the token is well-formed, has a valid signature, and has not expired. Logs specific errors to help with debugging.
- Parameters:
authToken- the JWT token string to validate- Returns:
- true if the token is valid, false otherwise
-