Capítulo 5: Seguridad Avanzada
Introducción
La autenticación es solo la primera línea de defensa. Este capítulo cubre los mecanismos de protección avanzada contra ataques comunes y la gestión detallada de permisos.
🎯 Objetivos del Capítulo
Al final de este capítulo, usted sabrá:
- ✅ Proteger contra ataques CSRF
- ✅ Configurar CORS para las API
- ✅ Utilizar @PreAuthorize y @Secured
- ✅ Implementar un sistema RBAC
- ✅ Configurar los headers de seguridad
1. Protección CSRF
¿Qué es CSRF?
Cross-Site Request Forgery: Un atacante hace que un usuario autenticado ejecute acciones sin su consentimiento.
Protección por Defecto
Spring Security activa CSRF por defecto para aplicaciones web:
// Por defecto, CSRF está ACTIVADO
// El token CSRF se verifica automáticamente en POST, PUT, DELETE
Token CSRF en Formularios
<!-- Thymeleaf - automático con th:action -->
<form th:action="@{/transfer}" method="post">
<!-- El token CSRF se añade automáticamente -->
<input type="hidden" name="_csrf" th:value="${_csrf.token}"/>
...
</form>
<!-- O explícitamente -->
<form action="/transfer" method="post">
<input type="hidden"
th:name="${_csrf.parameterName}"
th:value="${_csrf.token}"/>
...
</form>
CSRF para API REST
Para API REST stateless con JWT, desactive CSRF:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable()) // ← Desactivar para API REST
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
// ...
.build();
}
Desactive CSRF únicamente si utiliza autenticación stateless (JWT, OAuth2). ¡Para sesiones, manténgalo activado!
CSRF Selectivo
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf
.ignoringRequestMatchers("/api/**") // Desactivado para /api/
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
)
.build();
}
2. Configuración de CORS
¿Qué es CORS?
Cross-Origin Resource Sharing: Controla qué dominios pueden acceder a su API.
Frontend: https://app.example.com
Backend: https://api.example.com ← ¡Dominio diferente!
Sin CORS configurado → Solicitudes bloqueadas por el navegador
Configuración Global
@Configuration
public class CorsConfig {
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
// Orígenes permitidos
configuration.setAllowedOrigins(List.of(
"http://localhost:3000",
"https://app.example.com"
));
// Métodos HTTP permitidos
configuration.setAllowedMethods(List.of(
"GET", "POST", "PUT", "DELETE", "OPTIONS"
));
// Headers permitidos
configuration.setAllowedHeaders(List.of(
"Authorization",
"Content-Type",
"X-Requested-With"
));
// Permitir credenciales (cookies, Authorization header)
configuration.setAllowCredentials(true);
// Duración de caché del preflight
configuration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
Integración con Spring Security
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.cors(Customizer.withDefaults()) // ← Activar CORS
.csrf(csrf -> csrf.disable())
// ...
.build();
}
CORS por Controller
@RestController
@RequestMapping("/api/public")
@CrossOrigin(origins = "http://localhost:3000") // ← Específico
public class PublicController {
// ...
}
// O por método
@GetMapping("/data")
@CrossOrigin(origins = "*", maxAge = 3600)
public Data getData() {
// ...
}
3. Method-Level Security
Activación
@Configuration
@EnableWebSecurity
@EnableMethodSecurity // ← Activa @PreAuthorize, @PostAuthorize, @Secured
public class SecurityConfig {
// ...
}
@PreAuthorize
Verifica ANTES de la ejecución del método:
@RestController
@RequestMapping("/api")
public class UserController {
// Verificar un rol
@GetMapping("/admin/users")
@PreAuthorize("hasRole('ADMIN')")
public List<User> getAllUsers() { ... }
// Verificar varios roles
@DeleteMapping("/users/{id}")
@PreAuthorize("hasAnyRole('ADMIN', 'MANAGER')")
public void deleteUser(@PathVariable Long id) { ... }
// Verificar una authority/permiso
@PostMapping("/users")
@PreAuthorize("hasAuthority('CREATE_USER')")
public User createUser(@RequestBody User user) { ... }
// Expresión compleja
@PutMapping("/users/{id}")
@PreAuthorize("hasRole('ADMIN') or #id == authentication.principal.id")
public User updateUser(@PathVariable Long id, @RequestBody User user) { ... }
// Acceso al objeto de autenticación
@GetMapping("/me")
@PreAuthorize("isAuthenticated()")
public User getCurrentUser(Authentication auth) { ... }
}
@PostAuthorize
Verifica DESPUÉS de la ejecución (útil para verificar el resultado):
@GetMapping("/users/{id}")
@PostAuthorize("returnObject.username == authentication.name or hasRole('ADMIN')")
public User getUser(@PathVariable Long id) {
return userRepository.findById(id).orElseThrow();
}
@Secured (Legacy)
Más simple pero menos flexible:
@Secured("ROLE_ADMIN")
public void adminOnly() { ... }
@Secured({"ROLE_ADMIN", "ROLE_MANAGER"})
public void adminOrManager() { ... }
Expresiones SpEL Disponibles
| Expresión | Descripción |
|---|---|
hasRole('ROLE') | Tiene el rol (agrega ROLE_ automáticamente) |
hasAnyRole('R1', 'R2') | Tiene uno de los roles |
hasAuthority('AUTH') | Tiene la autoridad exacta |
hasAnyAuthority('A1', 'A2') | Tiene una de las autoridades |
isAuthenticated() | Está autenticado |
isAnonymous() | No está autenticado |
isFullyAuthenticated() | No vía remember-me |
permitAll | Siempre permitido |
denyAll | Siempre denegado |
#paramName | Acceso a los parámetros |
returnObject | Resultado (@PostAuthorize) |
authentication | Objeto Authentication |
principal | El usuario (UserDetails) |
4. Sistema RBAC (Role-Based Access Control)
Modelo de Datos
Entidades
@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 con Permisos
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()) {
// Añadir el rol
authorities.add(new SimpleGrantedAuthority(role.getName()));
// Añadir los permisos del rol
for (Permission permission : role.getPermissions()) {
authorities.add(new SimpleGrantedAuthority(permission.getName()));
}
}
return authorities;
}
// ...
}
Uso
// Por rol
@PreAuthorize("hasRole('ADMIN')")
public void adminAction() { }
// Por permiso
@PreAuthorize("hasAuthority('DELETE_USERS')")
public void deleteUser(Long id) { }
// Combinación
@PreAuthorize("hasRole('MANAGER') and hasAuthority('APPROVE_ORDERS')")
public void approveOrder(Long orderId) { }
5. Headers de Seguridad
Configuración
@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 (HTTPS obligatorio)
.httpStrictTransportSecurity(hsts -> hsts
.includeSubDomains(true)
.maxAgeInSeconds(31536000)
)
)
.build();
}
Headers Resultantes
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. Protección Contra Ataques
Brute Force (Límite de Intentos)
@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;
}
}
Integración con la Autenticación
@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. Auditoría de Seguridad
Logging de Eventos
@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. Resumen
Protecciones Esenciales
| Protección | Contra | Configuración |
|---|---|---|
| CSRF | Solicitudes falsificadas | Activado por defecto (desactivar para API REST) |
| CORS | Solicitudes cross-origin | cors(Customizer.withDefaults()) |
| XSS | Scripts maliciosos | Headers + CSP |
| Clickjacking | Frames maliciosos | X-Frame-Options |
| Brute Force | Ataques de fuerza bruta | Límite de intentos |
Method Security
@PreAuthorize("hasRole('ADMIN')") // Por rol
@PreAuthorize("hasAuthority('DELETE_USER')") // Por permiso
@PreAuthorize("#id == authentication.principal.id") // Por expresión
Checklist de Seguridad
✅ CSRF activado para sesiones
✅ CORS configurado para la API
✅ Contraseñas codificadas (BCrypt)
✅ Headers de seguridad configurados
✅ @PreAuthorize en métodos sensibles
✅ Auditoría de eventos de seguridad
✅ Protección contra fuerza bruta
🎯 Próximo Paso
¡Ahora tiene toda la teoría! Es momento de la práctica con los trabajos prácticos.
➡️ TP8.1: Autenticación Form Login