Spring Security provides security features for Java applications by handling authentication and authorization. Along with securing URLs and endpoints, Spring Security also supports method-level security to protect specific methods directly.
Provides role-based access control on specific methods.
Protects service-layer business logic from unauthorized access.
Uses annotations for declarative and cleaner security configuration.
Why Method-Level Security
Granular Control: Restrict access to specific methods instead of the entire application or URL.
Business Logic Protection: Even if someone bypasses the web layer, the service methods remain protected.
Role-Based Access: Easily define role-based restrictions at the method level.
Separation of Concerns: Security logic is applied declaratively without polluting business logic.
Enabling Method-Level Security
In Spring Security, method-level security is enabled using the @EnableMethodSecurity annotation instead of the deprecated @EnableGlobalMethodSecurity.
Common Annotations for Method Security
Spring Security provides annotations to restrict access to methods based on roles and conditions:
1. @Secured
The @Secured annotation restricts method access based on user roles.
Allows access only to users having specific roles.
Simpler than SpEL-based authorization expressions.
Only users with the role ROLE_MANAGER can access generateReport().
2. @PreAuthorize
The @PreAuthorize annotation checks authorization before method execution.
Uses Spring Expression Language (SpEL) for flexible conditions.
Security validation happens before method execution.
Only users with the role ROLE_ADMIN can execute the deleteAccount() method.
3. @PostAuthorize
The @PostAuthorize annotation applies authorization after method execution.
Validates returned objects after method execution.
Useful for filtering sensitive returned data.
Only the owner of the account can access the returned Account object.
4. @RolesAllowed
The @RolesAllowed annotation is part of JSR-250 standard security.
Allows multiple roles for accessing methods.
Requires jsr250Enabled = true in @EnableMethodSecurity.
Both ROLE_ADMIN and ROLE_USER can access viewProfile().
Step-by-Step Implementation of Spring Security at Method Level
Step 1: Create a Spring Boot Project
Create a project via Spring Initializr or directly in IntelliJ IDEA / STS.
Project Details:
Project: Maven Project
Spring Boot Version: 3.3.x
Dependencies: Spring Web, Spring Security
pom.xml:
Step 2: Enable Method-Level Security
Create a configuration class that is annoted with @Configuration and @EnableMethodSecurity.
Activates method-level security annotations.
Allows role-based restrictions on methods.
Step 3: Create a Service with Method-Level Security
Use @PreAuthorize to restrict access to methods based on roles.