Package vaultWeb.security
Class JwtUtil
java.lang.Object
vaultWeb.security.JwtUtil
Utility class for creating and parsing JSON Web Tokens (JWT). A JWT is a compact, URL-safe token
format consisting of three parts: header, payload, and signature.
- Header: contains metadata about the token, such as the signing algorithm (e.g., HS256) and token type.
- Payload: contains claims — pieces of information about the user or the token itself.
- Signature: cryptographic signature to ensure token integrity and authenticity.
- Registered claims like
sub(subject, often the username),iat(issued at), andexp(expiration time). - Public claims which can be custom, e.g. user roles, email, etc.
- Private claims defined by your application for specific needs.
In this class, the "role" claim is a custom public claim used to store the user's role for authorization purposes.
The token is cryptographically signed using the secret key to ensure its integrity and authenticity.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionextractUsername(String token) Extracts the username (subject) from the provided JWT token.generateToken(User user) Generates a signed JWT token for the given user.org.springframework.security.core.AuthenticationgetAuthentication(String token) booleanvalidateToken(String token)
-
Constructor Details
-
JwtUtil
-
-
Method Details
-
generateToken
Generates a signed JWT token for the given user. The token is signed with theSECRET_KEYusing HS256.- Parameters:
user- the user entity containing username and role- Returns:
- a signed JWT token string
-
extractUsername
Extracts the username (subject) from the provided JWT token.This method also validates the token's signature using the
SECRET_KEY. If the token is invalid or expired, parsing will throw an exception.- Parameters:
token- the JWT token string- Returns:
- the username (subject) embedded in the token
- Throws:
io.jsonwebtoken.JwtException- if token parsing or validation fails
-
validateToken
-
getAuthentication
-