Package vaultWeb.services.auth
Class AuthService
java.lang.Object
vaultWeb.services.auth.AuthService
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 -
Method Summary
-
Constructor Details
-
AuthService
public AuthService()
-
-
Method Details
-
login
Authenticates a user using their username and password and returns a JWT token upon successful authentication.Workflow:
- The AuthenticationManager validates the username and password against the stored hash.
- If authentication succeeds, the Authentication object is stored in the SecurityContext.
- UserDetails are retrieved from the Authentication object, containing basic security info (username, roles).
- The full User entity is then loaded from the database for additional details.
- 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 clientpassword- 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
Retrieves the currently authenticated user from the SecurityContext.If no user is authenticated, this method returns
null. Otherwise, it fetches the fullUserentity from the database based on the username.- Returns:
- the currently authenticated
User, ornullif no user is authenticated
-