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 Details

    • AuthService

      public AuthService()
  • Method Details

    • login

      public String 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