Question
How can Spring Security use @PreAuthorize on controller methods?
@RestController
public class MyController {
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin")
public ResponseEntity<String> getAdminData() {
return ResponseEntity.ok("Admin data");
}
}
Answer
In Spring Security, the @PreAuthorize annotation allows you to specify authorization constraints on your controller methods. By applying this annotation, you can ensure that only users with the designated roles or permissions can access specific endpoints in your application.
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated();
}
}
Causes
- User does not have the required role or permission.
- Security configuration is not properly set up to recognize @PreAuthorize.
- Missing dependency for Aspect-Oriented Programming (AOP) support.
Solutions
- Ensure the correct role or permission is granted to the user trying to access the resource.
- Verify that your Spring Security configuration includes method security enabled with @EnableGlobalMethodSecurity(prePostEnabled = true).
- Add 'spring-boot-starter-aop' dependency if not already included in your project.
Common Mistakes
Mistake: Not enabling method security in the configuration.
Solution: Make sure to add @EnableGlobalMethodSecurity(prePostEnabled = true) in your configuration.
Mistake: Incorrect SpEL expressions in @PreAuthorize annotations.
Solution: Double-check your SpEL expressions and user roles.
Helpers
- Spring Security
- @PreAuthorize
- Spring controllers
- method security
- authorization in Spring