Class JwtUtil

java.lang.Object
vaultWeb.security.JwtUtil

@Component public class JwtUtil extends Object
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.
Claims are key-value pairs embedded inside the JWT payload that provide data such as:
  • Registered claims like sub (subject, often the username), iat (issued at), and exp (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 Details

    • JwtUtil

      public JwtUtil(@Value("${jwt.secret}") String secret)
  • Method Details

    • generateToken

      public String generateToken(User user)
      Generates a signed JWT token for the given user. The token is signed with the SECRET_KEY using HS256.
      Parameters:
      user - the user entity containing username and role
      Returns:
      a signed JWT token string
    • extractUsername

      public String extractUsername(String token)
      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

      public boolean validateToken(String token)
    • getAuthentication

      public org.springframework.security.core.Authentication getAuthentication(String token)