java / beginner
Snippet
Restricting Method Access with PreAuthorize Roles
Spring Security's @PreAuthorize annotation uses Spring Expression Language (SpEL) to evaluate authorization rules before executing a method. In this example, only authenticated users assigned the 'ADMIN' role can invoke the generateFinancialSummary method; unauthorized users trigger an AccessDeniedException.
snippet.java
java
1
2
3
4
5
6
7
8
@Servicepublic class AdminReportService {@PreAuthorize("hasRole('ADMIN')")public Report generateFinancialSummary() {return new Report("Q1 Summary", "Confidential financial data");}}
spring
Breakdown
1
@Service
Marks the class as a Spring service component to be managed by the Spring container.
2
@PreAuthorize("hasRole('ADMIN')")
Enforces that the current security principal must possess the ADMIN authority before method execution.
3
public Report generateFinancialSummary() {
Declares the sensitive business operation protected by method-level security.
4
return new Report("Q1 Summary", "Confidential financial data");
Instantiates and returns the protected report data when access is granted.