1. Dependencies
- Spring Security Web — core security features: user management, authentication filters, authorization checks.
- Spring Security JWT (optional) — needed if using JWT-based authentication, for token processing.
2. User entity and UserDetails implementation
- Create a
Userentity (id, username, password, email, etc.). - Implement
UserDetails— a custom class (e.g.UserDetailsImpl) overriding its methods to supply username, password, and authorities/roles for authentication.
3. User data service
- Implement
UserDetailsService(e.g.UserDetailsServiceImpl), withloadUserByUsernameretrieving user details (including roles) from your database via a JPA repository.
4. Security configuration
- Define request authorization rules (e.g. permit
/api/auth/signup, require auth for everything else). - Register your custom authentication provider, if using custom authentication logic.
- Configure a
PasswordEncoder(e.g.BCryptPasswordEncoder) to hash passwords before storage. - For JWT: configure secret key and expiration via properties or annotations.
5. Authentication mechanism (optional)
- Username/password typically relies on the default
UsernamePasswordAuthenticationFilter. - JWT-based auth typically needs a custom filter to extract and validate tokens from request headers.
6. Authorization
- Define rules using request matchers and
permitAll(),hasAnyRole(),hasAuthority(), etc., specifying which roles/authorities can access which URLs.
Reference material: