Spring Security Implementation Guide
Prerequisites
Before implementing Spring Security, ensure you have:
- ✅ Complete Spring Boot application (error-free)
- ✅ Controllers
- ✅ Repositories
- ✅ Models
- ✅ Database connection
- ✅ DTOs
- ✅ Services
- ✅ Mappers
- ✅ Required dependencies
1. Custom Security Filter Chain
Default
SecurityFilterChainis auto-enabled with all filters. To customize it:
Steps:
- Create package →
config - Create class →
SecurityConfig.java Add annotations:
@Configuration@EnableWebSecurity– Helps override default chain@EnableMethodSecurity– Enables method-security annotations
Create a
@Beanmethod:- Return type:
SecurityFilterChain - Parameter:
HttpSecurity - Configure your custom filters here
- Return type:
📌 V1: Define username and password in application.properties for Basic Auth and Form Login.
2. User Details Service
Steps:
- Create a
@Beanmethod forUserDetailsService - Create object(s) of type
UserDetails - Return →
new InMemoryUserDetailsManager(userDetails)
📌 V2.1
3. Method-Level Security (RBAC)
Set Role-Based Access Control on specific endpoints using annotations.
Steps:
- Use
@PreAuthorize("hasAuthority('ROLE_ADMIN')")on controller methods - Requires
@EnableMethodSecurityinSecurityConfig.java
📌 V2.2
4. Basic Auth & RBAC via Database
Steps:
Create package →
securityCreate the following classes: | Class | Implements | |-------|------------| |
CustomUserDetails|UserDetails| |CustomUserDetailsService|UserDetailsService|In
SecurityConfig:- Inject
CustomUserDetailsService - Pass it to the filter chain:
.userDetailsService(customUserDetailsService) - Create a
@BeanforPasswordEncoder
- Inject
In
UserServiceImpl:- Apply
PasswordEncoderin create and update user methods
- Apply
5. JWT X DB
Steps:
Create
JwtServiceinutilpackage:- Token creation and generation method
- Data extraction methods (username, expiration)
- Token validation method
Create
JwtAuthFilterinutilpackage:- Extend
OncePerRequestFilter - Implement
doFilterInternalmethod - Extract token from
Authorizationheader - Validate and set authentication in
SecurityContext
- Extend
Update
SecurityConfig:- Inject
JwtAuthFilter - Create a
@BeanofAuthenticationManager - Replace form/Basic Auth with
SessionCreationPolicy.STATELESS - Add filter:
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
- Inject
Create login endpoint in
UserController:- Accept username and password
- Authenticate using
AuthenticationManager - Return JWT token from
JwtService
6. OAuth2 X JWT X DB
Integrate OAuth2 (e.g., GitHub) with JWT for stateless authentication.
Steps:
Add Dependency for OAuth2 client in
pom.xmlConfigure OAuth2 Provider in
application.properties:spring.security.oauth2.client.registration.github.client-id=YOUR_CLIENT_ID spring.security.oauth2.client.registration.github.client-secret=YOUR_CLIENT_SECRETCreate
OAuth2AuthenticationSuccessHandlerinsecuritypackage:- Extend
SimpleUrlAuthenticationSuccessHandler - Override
onAuthenticationSuccessmethod - Extract username from
OAuth2Userprincipal - Generate JWT token using
JwtService - Return token in JSON response
- Extend
Update
SecurityConfig:- Inject
OAuth2AuthenticationSuccessHandler - Configure OAuth2 login with success handler
- Inject
Flow:
- User hits a protected endpoint → Redirected to GitHub login
- User authenticates with GitHub
- Success handler generates JWT token and returns it
- User uses JWT token in
Authorization: Bearer <token>header for subsequent requests
7. Exception Handling & Validation
Implement global exception handling and input validation for consistent API responses.
Steps:
Add Validation Dependency in
pom.xml:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>Create Custom Exceptions in
configpackage: | Class | Purpose | |-------|---------| |ResourceNotFoundException| When entity not found (404) | |BadRequestException| Invalid input data (400) | |DuplicateResourceException| Duplicate entry (409) |Create
ErrorResponseDTO:- Contains: timestamp, status, error, message, path, validationErrors
Create
GlobalExceptionHandler:- Annotate with
@RestControllerAdvice - Handle all custom and common exceptions
- Return consistent
ErrorResponsestructure
- Annotate with
Add Validation Annotations to DTOs:
CreateUserDto:@NotBlank,@Email,@SizeProductDto:@NotBlank,@NotNull,@DecimalMinStoreDto:@NotBlank,@NotNull,@Size
Update Controllers with
@Validannotation on@RequestBodyparameters
Error Response Format:
{
"timestamp": "2024-01-26T12:00:00",
"status": 404,
"error": "Not Found",
"message": "User not found with id: 1",
"path": "/users/1",
"validationErrors": null
}
Validation Error Response:
{
"timestamp": "2024-01-26T12:00:00",
"status": 400,
"error": "Validation Failed",
"message": "Input validation failed",
"path": "/users/register",
"validationErrors": {
"email": "Invalid email format",
"password": "Password must be at least 6 characters"
}
}
Log in or sign up for Devpost to join the conversation.