Chapter 5: Advanced Security
Introduction
Authentication is only the first line of defense. This chapter covers advanced protection mechanisms against common attacks and fine-grained authorization management.
🎯 Chapter Objectives
By the end of this chapter, you will know how to:
- ✅ Protect against CSRF attacks
- ✅ Configure CORS for APIs
- ✅ Use @PreAuthorize and @Secured
- ✅ Implement an RBAC system
- ✅ Configure security headers
1. CSRF Protection
What is CSRF?
Cross-Site Request Forgery: An attacker makes a connected user execute actions without their consent.
Default Protection
Spring Security enables CSRF by default for web applications:
// By default, CSRF is ENABLED
// The CSRF token is automatically verified on POST, PUT, DELETE
CSRF Token in Forms
<!-- Thymeleaf - automatic with th:action -->
<form th:action="@{/transfer}" method="post">
<!-- The CSRF token is added automatically -->
<input type="hidden" name="_csrf" th:value="${_csrf.token}"/>
...
</form>
<!-- Or explicitly -->
<form action="/transfer" method="post">
<input type="hidden"
th:name="${_csrf.parameterName}"
th:value="${_csrf.token}"/>
...
</form>
CSRF for REST API
For stateless REST APIs with JWT, disable CSRF:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable()) // ← Disable for REST API
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
// ...
.build();
}
Disable CSRF only if you use stateless authentication (JWT, OAuth2). For sessions, keep it enabled!
Selective CSRF
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf
.ignoringRequestMatchers("/api/**") // Disabled for /api/
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
)
.build();
}
2. CORS Configuration
What is CORS?
Cross-Origin Resource Sharing: Controls which domains can access your API.
Frontend: https://app.example.com
Backend: https://api.example.com ← Different domain!
Without configured CORS → Requests blocked by the browser
Global Configuration
@Configuration
public class CorsConfig {
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
// Allowed origins
configuration.setAllowedOrigins(List.of(
"http://localhost:3000",
"https://app.example.com"
));
// Allowed HTTP methods
configuration.setAllowedMethods(List.of(
"GET", "POST", "PUT", "DELETE", "OPTIONS"
));
// Allowed headers
configuration.setAllowedHeaders(List.of(
"Authorization",
"Content-Type",
"X-Requested-With"
));
// Allow credentials (cookies, Authorization header)
configuration.setAllowCredentials(true);
// Preflight cache duration
configuration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
Integration with Spring Security
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.cors(Customizer.withDefaults()) // ← Enable CORS
.csrf(csrf -> csrf.disable())
// ...
.build();
}
CORS per Controller
@RestController
@RequestMapping("/api/public")
@CrossOrigin(origins = "http://localhost:3000") // ← Specific
public class PublicController {
// ...
}
// Or per method
@GetMapping("/data")
@CrossOrigin(origins = "*", maxAge = 3600)
public Data getData() {
// ...
}
3. Method-Level Security
Activation
@Configuration
@EnableWebSecurity
@EnableMethodSecurity // ← Enables @PreAuthorize, @PostAuthorize, @Secured
public class SecurityConfig {
// ...
}
@PreAuthorize
Checks BEFORE method execution:
@RestController
@RequestMapping("/api")
public class UserController {
// Check a role
@GetMapping("/admin/users")
@PreAuthorize("hasRole('ADMIN')")
public List<User> getAllUsers() { ... }
// Check multiple roles
@DeleteMapping("/users/{id}")
@PreAuthorize("hasAnyRole('ADMIN', 'MANAGER')")
public void deleteUser(@PathVariable Long id) { ... }
// Check an authority/permission
@PostMapping("/users")
@PreAuthorize("hasAuthority('CREATE_USER')")
public User createUser(@RequestBody User user) { ... }
// Complex expression
@PutMapping("/users/{id}")
@PreAuthorize("hasRole('ADMIN') or #id == authentication.principal.id")
public User updateUser(@PathVariable Long id, @RequestBody User user) { ... }
// Access to the authentication object
@GetMapping("/me")
@PreAuthorize("isAuthenticated()")
public User getCurrentUser(Authentication auth) { ... }
}
@PostAuthorize
Checks AFTER execution (useful for checking the result):
@GetMapping("/users/{id}")
@PostAuthorize("returnObject.username == authentication.name or hasRole('ADMIN')")
public User getUser(@PathVariable Long id) {
return userRepository.findById(id).orElseThrow();
}
@Secured (Legacy)
Simpler but less flexible:
@Secured("ROLE_ADMIN")
public void adminOnly() { ... }
@Secured({"ROLE_ADMIN", "ROLE_MANAGER"})
public void adminOrManager() { ... }
Available SpEL Expressions
| Expression | Description |
|---|---|
hasRole('ROLE') | Has the role (adds ROLE_ automatically) |
hasAnyRole('R1', 'R2') | Has one of the roles |
hasAuthority('AUTH') | Has the exact authority |
hasAnyAuthority('A1', 'A2') | Has one of the authorities |
isAuthenticated() | Is logged in |
isAnonymous() | Is not logged in |
isFullyAuthenticated() | Not via remember-me |
permitAll | Always allowed |
denyAll | Always denied |
#paramName | Access to parameters |
returnObject | Result (@PostAuthorize) |
authentication | Authentication object |
principal | The user (UserDetails) |
4. RBAC System (Role-Based Access Control)
Data Model
Entities
@Entity
@Table(name = "permissions")
@Data
public class Permission {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String name; // READ_USERS, WRITE_USERS, DELETE_USERS
}
@Entity
@Table(name = "roles")
@Data
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String name; // ROLE_ADMIN, ROLE_USER, ROLE_MANAGER
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "role_permissions",
joinColumns = @JoinColumn(name = "role_id"),
inverseJoinColumns = @JoinColumn(name = "permission_id")
)
private Set<Permission> permissions = new HashSet<>();
}
UserDetails with Permissions
public class CustomUserDetails implements UserDetails {
private final User user;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> authorities = new HashSet<>();
for (Role role : user.getRoles()) {
// Add the role
authorities.add(new SimpleGrantedAuthority(role.getName()));
// Add the role's permissions
for (Permission permission : role.getPermissions()) {
authorities.add(new SimpleGrantedAuthority(permission.getName()));
}
}
return authorities;
}
// ...
}
Usage
// By role
@PreAuthorize("hasRole('ADMIN')")
public void adminAction() { }
// By permission
@PreAuthorize("hasAuthority('DELETE_USERS')")
public void deleteUser(Long id) { }
// Combination
@PreAuthorize("hasRole('MANAGER') and hasAuthority('APPROVE_ORDERS')")
public void approveOrder(Long orderId) { }
5. Security Headers
Configuration
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.headers(headers -> headers
// Content Security Policy
.contentSecurityPolicy(csp -> csp
.policyDirectives("default-src 'self'; script-src 'self'")
)
// X-Frame-Options (clickjacking)
.frameOptions(frame -> frame.sameOrigin())
// X-Content-Type-Options
.contentTypeOptions(Customizer.withDefaults())
// X-XSS-Protection
.xssProtection(xss -> xss.headerValue(XXssProtectionHeaderWriter.HeaderValue.ENABLED_MODE_BLOCK))
// HSTS (mandatory HTTPS)
.httpStrictTransportSecurity(hsts -> hsts
.includeSubDomains(true)
.maxAgeInSeconds(31536000)
)
)
.build();
}
Resulting Headers
Content-Security-Policy: default-src 'self'; script-src 'self'
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Strict-Transport-Security: max-age=31536000; includeSubDomains
6. Protection Against Attacks
Brute Force (Attempt Limit)
@Service
public class LoginAttemptService {
private final Cache<String, Integer> attemptsCache = CacheBuilder.newBuilder()
.expireAfterWrite(1, TimeUnit.HOURS)
.build();
public void loginSucceeded(String key) {
attemptsCache.invalidate(key);
}
public void loginFailed(String key) {
int attempts = attemptsCache.get(key, () -> 0);
attemptsCache.put(key, attempts + 1);
}
public boolean isBlocked(String key) {
return attemptsCache.get(key, () -> 0) >= 5;
}
}
Integration with Authentication
@Component
@RequiredArgsConstructor
public class AuthenticationFailureListener
implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
private final LoginAttemptService loginAttemptService;
@Override
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
String username = (String) event.getAuthentication().getPrincipal();
loginAttemptService.loginFailed(username);
}
}
@Component
@RequiredArgsConstructor
public class AuthenticationSuccessListener
implements ApplicationListener<AuthenticationSuccessEvent> {
private final LoginAttemptService loginAttemptService;
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
String username = event.getAuthentication().getName();
loginAttemptService.loginSucceeded(username);
}
}
7. Security Audit
Event Logging
@Component
@Slf4j
public class SecurityAuditListener {
@EventListener
public void onSuccess(AuthenticationSuccessEvent event) {
log.info("LOGIN SUCCESS: {} at {}",
event.getAuthentication().getName(),
LocalDateTime.now());
}
@EventListener
public void onFailure(AuthenticationFailureBadCredentialsEvent event) {
log.warn("LOGIN FAILED: {} at {}",
event.getAuthentication().getPrincipal(),
LocalDateTime.now());
}
@EventListener
public void onAccessDenied(AuthorizationDeniedEvent event) {
log.warn("ACCESS DENIED: {} tried to access {}",
event.getAuthentication().get().getName(),
event.getSource());
}
}
8. Summary
Essential Protections
| Protection | Against | Configuration |
|---|---|---|
| CSRF | Forged requests | Enabled by default (disable for REST API) |
| CORS | Cross-origin requests | cors(Customizer.withDefaults()) |
| XSS | Malicious scripts | Headers + CSP |
| Clickjacking | Malicious frames | X-Frame-Options |
| Brute Force | Brute force attacks | Attempt limitation |
Method Security
@PreAuthorize("hasRole('ADMIN')") // By role
@PreAuthorize("hasAuthority('DELETE_USER')") // By permission
@PreAuthorize("#id == authentication.principal.id") // By expression
Security Checklist
✅ CSRF enabled for sessions
✅ CORS configured for API
✅ Passwords encoded (BCrypt)
✅ Security headers configured
✅ @PreAuthorize on sensitive methods
✅ Security event audit
✅ Protection against brute force
🎯 Next Step
You now have all the theory! Time for practice with the practical exercises.
➡️ TP8.1: Form Login Authentication