Chapter 5: Advanced Security - Modules 11 to 18
Objectives
- Master Spring Security in depth
- Implement robust security step by step
- Understand each component of the security chain
Main Resource
Security Appendices
This chapter is based on the security-appendices-1 from the repository, an excellent step-by-step guide:
** Security Appendices Folder**
Modules 11 to 18: A complete Spring Boot security project.
Security Modules Plan
| Module | Title | Content |
|---|---|---|
| 11 | Introduction to Spring Security | Basic concepts, architecture |
| 12 | Initial Configuration | SecurityFilterChain, HttpSecurity |
| 13 | Authentication | UserDetails, UserDetailsService |
| 14 | Password Encoding | BCryptPasswordEncoder |
| 15 | JWT - Theory | Structure, claims, signature |
| 16 | JWT - Implementation | JwtService, generation, validation |
| 17 | Custom Filters | JwtAuthenticationFilter |
| 18 | Authorization | Roles, @PreAuthorize, method security |
Module 11: Introduction to Spring Security
What is Spring Security?
Spring Security is the standard security framework for Spring applications. It provides:
- Authentication: Verify the user's identity
- Authorization: Control access to resources
- Protection against attacks: CSRF, XSS, etc.
Spring Security Architecture
┌───────────────────────────────────────────────────────────┐
│ SecurityFilterChain │
│ │
│ Request ──► Filter 1 ──► Filter 2 ──► ... ──► Controller
│ │
│ Each filter can: │
│ - Let the request pass │
│ - Block the request (401/403) │
│ - Modify the request │
└───────────────────────────────────────────────────────────┘
Maven Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Module 12: Initial Configuration
Basic SecurityConfig
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable()) // Disable CSRF for REST API
.authorizeHttpRequests(auth -> auth
.anyRequest().permitAll() // Allow everything to start
)
.build();
}
}
Progressive Configuration
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
// Public endpoints
.requestMatchers("/api/contact").permitAll()
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/h2-console/**").permitAll()
// Protected endpoints
.requestMatchers("/api/admin/**").authenticated()
// Everything else
.anyRequest().authenticated()
)
.headers(headers -> headers.frameOptions(f -> f.disable())) // For H2 console
.build();
}
Module 13: Authentication
User Entity
@Entity
@Table(name = "users")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String email;
private String password;
@Enumerated(EnumType.STRING)
private Role role;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of(new SimpleGrantedAuthority("ROLE_" + role.name()));
}
@Override
public String getUsername() {
return email;
}
@Override
public boolean isAccountNonExpired() { return true; }
@Override
public boolean isAccountNonLocked() { return true; }
@Override
public boolean isCredentialsNonExpired() { return true; }
@Override
public boolean isEnabled() { return true; }
}
UserDetailsService
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return userRepository.findByEmail(email)
.orElseThrow(() -> new UsernameNotFoundException("User not found: " + email));
}
}
AuthenticationProvider Configuration
@Configuration
public class SecurityConfig {
@Bean
public AuthenticationProvider authenticationProvider(
UserDetailsService userDetailsService,
PasswordEncoder passwordEncoder) {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
provider.setPasswordEncoder(passwordEncoder);
return provider;
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config)
throws Exception {
return config.getAuthenticationManager();
}
}
Module 14: Password Encoding
BCryptPasswordEncoder
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
Usage during Registration
@Service
@RequiredArgsConstructor
public class AuthService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public User register(RegisterRequest request) {
User user = new User();
user.setEmail(request.getEmail());
user.setPassword(passwordEncoder.encode(request.getPassword())); // Encoding!
user.setRole(Role.USER);
return userRepository.save(user);
}
}
Verification during Login
public String login(LoginRequest request) {
// The AuthenticationManager automatically handles password verification
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
request.getEmail(),
request.getPassword()
)
);
// If we reach here, authentication was successful
User user = (User) authentication.getPrincipal();
return jwtService.generateToken(user);
}
Module 15: JWT - Theory
Structure of a JWT
A JWT (JSON Web Token) is composed of three parts separated by dots:
xxxxx.yyyyy.zzzzz
│ │ │
│ │ └── Signature
│ └── Payload (Claims)
└── Header
Header
{
"alg": "HS256",
"typ": "JWT"
}
Payload (Claims)
{
"sub": "user@example.com", // Subject (identifier)
"iat": 1609459200, // Issued At (creation date)
"exp": 1609545600, // Expiration
"roles": ["USER"] // Custom claims
}
Signature
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret_key
)
Module 16: JWT - Implementation
Dependency
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.12.3</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.12.3</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.12.3</version>
<scope>runtime</scope>
</dependency>
JwtService
@Service
public class JwtService {
@Value("${jwt.secret}")
private String secretKey;
@Value("${jwt.expiration}")
private long expiration; // In milliseconds
// Generate a token
public String generateToken(UserDetails userDetails) {
return Jwts.builder()
.subject(userDetails.getUsername())
.claim("roles", userDetails.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.toList())
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() + expiration))
.signWith(getSigningKey())
.compact();
}
// Extract the username
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}
// Validate the token
public boolean isTokenValid(String token, UserDetails userDetails) {
String username = extractUsername(token);
return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
}
private boolean isTokenExpired(String token) {
return extractClaim(token, Claims::getExpiration).before(new Date());
}
private <T> T extractClaim(String token, Function<Claims, T> resolver) {
Claims claims = Jwts.parser()
.verifyWith(getSigningKey())
.build()
.parseSignedClaims(token)
.getPayload();
return resolver.apply(claims);
}
private SecretKey getSigningKey() {
byte[] keyBytes = Decoders.BASE64.decode(secretKey);
return Keys.hmacShaKeyFor(keyBytes);
}
}
Configuration application.yml
jwt:
secret: "your-very-long-secret-key-at-least-256-bits-base64-encoded"
expiration: 86400000 # 24 hours in milliseconds
Module 17: Custom Filters
JwtAuthenticationFilter
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtService jwtService;
private final UserDetailsService userDetailsService;
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
// 1. Retrieve the Authorization header
String authHeader = request.getHeader("Authorization");
// 2. Check if the header is present and starts with "Bearer "
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
filterChain.doFilter(request, response);
return;
}
// 3. Extract the token
String token = authHeader.substring(7);
String username = jwtService.extractUsername(token);
// 4. If username found and not yet authenticated
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
// 5. Load the user
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
// 6. Validate the token
if (jwtService.isTokenValid(token, userDetails)) {
// 7. Create the authentication
UsernamePasswordAuthenticationToken authToken =
new UsernamePasswordAuthenticationToken(
userDetails,
null,
userDetails.getAuthorities()
);
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// 8. Put in the SecurityContext
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
// 9. Continue the filter chain
filterChain.doFilter(request, response);
}
}
Integration in SecurityConfig
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/contact").permitAll()
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.authenticationProvider(authenticationProvider)
// Add our filter BEFORE UsernamePasswordAuthenticationFilter
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
Module 18: Authorization
Security Annotations
@Configuration
@EnableMethodSecurity // Enable @PreAuthorize, @PostAuthorize, etc.
public class SecurityConfig {
// ...
}
@PreAuthorize
@RestController
@RequestMapping("/api/admin")
public class AdminController {
// Accessible only to ADMIN
@GetMapping("/leads")
@PreAuthorize("hasRole('ADMIN')")
public List<LeadDto> getAllLeads() {
return leadService.getAllLeads();
}
// Accessible to ADMIN and MANAGER
@GetMapping("/leads/stats")
@PreAuthorize("hasAnyRole('ADMIN', 'MANAGER')")
public StatsDto getStats() {
return leadService.getStats();
}
// Dynamic verification
@GetMapping("/users/{id}")
@PreAuthorize("#id == principal.id or hasRole('ADMIN')")
public UserDto getUser(@PathVariable Long id) {
return userService.getUser(id);
}
}
@PostAuthorize
@GetMapping("/{id}")
@PostAuthorize("returnObject.email == principal.username or hasRole('ADMIN')")
public LeadDto getLead(@PathVariable Long id) {
return leadService.getLead(id);
}
Service Level Security
@Service
public class LeadService {
@PreAuthorize("hasRole('ADMIN')")
public void deleteLead(Long id) {
leadRepository.deleteById(id);
}
@PreAuthorize("isAuthenticated()")
public List<LeadDto> getMyLeads() {
// Retrieve the connected user
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String email = auth.getName();
return leadRepository.findByCreatedBy(email);
}
}
Complete Final Architecture
┌─────────────────────────────────────────────────────────────────┐
│ Client Request │
│ Authorization: Bearer <token> │
└───────────────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ SecurityFilterChain │
│ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ 1. CorsFilter │ │
│ │ - Handles cross-origin requests │ │
│ └───────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ 2. JwtAuthenticationFilter │ │
│ │ - Extracts the token from the header │ │
│ │ - Validates the token │ │
│ │ - Loads UserDetails │ │
│ │ - Creates Authentication │ │
│ │ - Puts in SecurityContext │ │
│ └───────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ 3. AuthorizationFilter │ │
│ │ - Checks authorizations │ │
│ │ - hasRole(), hasAuthority() │ │
│ │ - Returns 403 if unauthorized │ │
│ └───────────────────────────────────────────────────────────┘ │
└───────────────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Controller │
│ @PreAuthorize verified │
└─────────────────────────────────────────────────────────────────┘
Mastery Checklist
After studying these modules, you should be able to:
- Configure SecurityFilterChain
- Implement UserDetails and UserDetailsService
- Encode passwords with BCrypt
- Generate and validate JWT tokens
- Create a custom authentication filter
- Use @PreAuthorize for authorization
- Write security tests
Complete Resource
Direct Access
For the complete detail of each module with all code examples:
** Security Appendices - Modules 11 to 18**
It's an excellent security project to study in depth!
Congratulations!
You have completed Module 16 on the e-contact-backend project. You have now:
- Configured an environment with GitHub Codespaces
- Mastered Spring Boot troubleshooting
- Integrated a frontend with the backend
- Deepened security concepts
- Understood Spring Security from A to Z
⏭️ Next Steps
- Practice: Clone the repository and experiment
- Modify: Add new features
- Test: Write your own security tests
- Deploy: Deploy to a cloud provider