RBAC and CSRF
Role-Based Access Control (RBAC)
RBAC restricts system access to authorized users based on their assigned roles. In Spring Security, a role is essentially a granted authority string prefixed with ROLE_.
You implement this using intercept URLs inside the SecurityFilterChain or by enabling Method Security annotations globally.
Method Security
Add @EnableMethodSecurity to your configuration class. You can then use the @PreAuthorize annotation directly above Controller or Service methods.
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin/dashboard")
public String viewAdminDashboard() {
return "admin-only-view";
}
Cross-Site Request Forgery (CSRF)
CSRF is an attack that forces an end user to execute unwanted actions on a web application where they are currently authenticated.
For example, if you are logged into your bank, a malicious website in another tab could submit a hidden POST request to bank.com/transfer using your active session cookies.
CSRF Protection in Spring
Spring Security inherently enables robust CSRF protection by default for all data-modifying HTTP methods (POST, PUT, DELETE).
It mitigates the attack by generating a unique Synchronizer Token. When a user loads a Thymeleaf form, Spring transparently injects a hidden <input> field containing this token. When the form is submitted back, Spring expects to see that exact token or it throws a 403 Forbidden error.
(Note: If you are building a completely stateless REST API using JWTs instead of session cookies, you must explicitly disable CSRF protection, as the vulnerability relies on browser cookie mechanics).