Class AuthService

java.lang.Object
vaultWeb.services.auth.AuthService

@Service public class AuthService extends Object
Service class responsible for handling authentication and user session-related operations.

Provides functionality for:

  • Authenticating users with username and password.
  • Generating JWT tokens for authenticated users.
  • Retrieving the currently authenticated user from the security context.

This service integrates with Spring Security's AuthenticationManager for authentication, UserRepository for fetching user entities, and JwtUtil for generating JWT tokens.

Security considerations:

  • Passwords are never stored or transmitted in plaintext.
  • Authentication uses BCryptPasswordEncoder for secure password hashing.
  • JWT tokens are signed and include necessary claims (e.g., username, role) for stateless authentication.
  • Constructor Summary

    Constructors
    Constructor
    Description
     
  • Method Summary

    Modifier and Type
    Method
    Description
    Retrieves the currently authenticated user from the SecurityContext.
    login(String username, String password)
    Authenticates a user using their username and password and returns a JWT token upon successful authentication.
    void
    logout(String rawRefreshToken, jakarta.servlet.http.HttpServletResponse response)
    Logs out the current session by revoking the active refresh token (identified via its jti) and deleting the refresh token cookie.
    org.springframework.http.ResponseEntity<?>
    refresh(String rawRefreshToken, jakarta.servlet.http.HttpServletResponse response)
    Refreshes the access token using a valid refresh token and performs refresh token rotation.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • AuthService

      public AuthService()
  • Method Details

    • login

      public LoginResult login(String username, String password)
      Authenticates a user using their username and password and returns a JWT token upon successful authentication.

      Workflow:

      1. The AuthenticationManager validates the username and password against the stored hash.
      2. If authentication succeeds, the Authentication object is stored in the SecurityContext.
      3. UserDetails are retrieved from the Authentication object, containing basic security info (username, roles).
      4. The full User entity is then loaded from the database for additional details.
      5. A JWT token is generated for the user, signed and valid for a specific duration.

      Detailed notes on authenticationManager.authenticate(...):

      • Spring Security calls the UserDetailsService to fetch user info by username.
      • The provided password is compared with the stored hashed password using PasswordEncoder.
      • If the password matches, a fully authenticated Authentication object is returned.
      • If the password does not match, a BadCredentialsException is thrown.
      Parameters:
      username - the username provided by the client
      password - the plaintext password provided by the client
      Returns:
      a signed JWT token representing the authenticated user
      Throws:
      UserNotFoundException - if the user does not exist in the database
    • getCurrentUser

      public User getCurrentUser()
      Retrieves the currently authenticated user from the SecurityContext.

      If no user is authenticated, this method returns null. Otherwise, it fetches the full User entity from the database based on the username.

      Returns:
      the currently authenticated User, or null if no user is authenticated
    • refresh

      public org.springframework.http.ResponseEntity<?> refresh(String rawRefreshToken, jakarta.servlet.http.HttpServletResponse response)
      Refreshes the access token using a valid refresh token and performs refresh token rotation.

      Workflow:

      1. Parses and verifies the refresh JWT using the refresh signing key, including signature and expiration validation.
      2. Extracts the token identifier (jti) from the refresh token.
      3. Looks up the corresponding refresh token record in the database using the extracted jti.
      4. Verifies the refresh token by comparing the SHA-256 hash of the provided token with the stored hash.
      5. If valid, revokes the existing refresh token to prevent reuse (refresh token rotation).
      6. Issues a new refresh token, stores its hash in the database, and sends it to the client as a secure, HttpOnly cookie.
      7. Generates and returns a new short-lived access token.

      Security considerations:

      • Refresh tokens are JWTs signed with a dedicated refresh signing key.
      • Only a non-secret identifier (jti) is used for database lookup; the refresh token itself is never stored in plaintext.
      • Refresh tokens are stored using a one-way SHA-256 hash.
      • Rotation ensures stolen refresh tokens cannot be reused.
      • Revoked tokens may be retained temporarily to allow replay-attack detection and auditing.

      Error scenarios:

      • 401 Unauthorized if the refresh token is missing, expired, revoked, invalid, or reused.
      Parameters:
      rawRefreshToken - the refresh JWT provided by the client (via HttpOnly cookie)
      response - HTTP response used to set the rotated refresh token cookie
      Returns:
      a response containing a new access token if the refresh succeeds
    • logout

      public void logout(String rawRefreshToken, jakarta.servlet.http.HttpServletResponse response)
      Logs out the current session by revoking the active refresh token (identified via its jti) and deleting the refresh token cookie.

      This ensures the refresh token cannot be reused even if it was previously leaked or stolen.