@PreAuthorize
Annotations provide a declarative method in Spring Security that adds method-level security checks in your Spring Boot app. This tutorial will guide you to set up and use it effectively@PreAuthorize
, ensuring that users can only call the REST API with specific roles or permissions.
What is @PreAuthorize?
@PreAuthorize
Is annotation of Spring Security that specifies the expressions that should be evaluated before a method invocation to determine whether the caller has permission to execute the method.
Add Spring Security to your project
Make sure that Spring Security is included in your project. For Maven, add the following dependencies toIn the file:
<dependency> <groupId></groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
For Gradle, add the following toIn the file:
implementation ':spring-boot-starter-security'
Enable method level security
To apply Spring Security to a specific method in the Rest Controller class of a Spring Boot application, method-level security must be enabled. To do this, you need to use@EnableMethodSecurity
annotation.
@Configuration @EnableMethodSecurity public class SpringSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { (csrf -> ()) .authorizeHttpRequests(authorize -> authorize .requestMatchers(, "/api/user").hasRole("USER") .requestMatchers(, "/api/admin").hasRole("ADMIN") .anyRequest().authenticated() ) .httpBasic(()); return (); } @Bean public UserDetailsService userDetailsService() { UserDetails ramesh = () .username("ramesh") .password(passwordEncoder().encode("password")) .roles("USER") .build(); UserDetails admin = () .username("admin") .password(passwordEncoder().encode("admin")) .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(ramesh, admin); } }
@EnableMethodSecurity
is a Spring annotation that enables method-level security in Spring applications. With this annotation, Spring creates a proxy for the class containing secure methods and intercepts when invoking these methods to check if the caller has the permissions needed to execute the method.
This annotation and other annotations (e.g.@PreAuthorize
、@PostAuthorize
、@Secured
and@RolesAllowed
) works together, these annotations are used to specify access control rules for methods. For example, you can use@PreAuthorize
Specifies that only users with a specific role or permission can call a method; or use@PostAuthorize
The specified method returns only data that the caller has permission to view.
Protect REST API with @PreAuthorize annotation
The following code shows how to use Spring Security for role-based RESTful endpoint authorization.
@RestController @RequestMapping("/api/") public class AdminController { @PreAuthorize("hasRole('ADMIN')") @GetMapping("/admin") public ResponseEntity<String> helloAdmin() { return ("Hello Admin"); } @PreAuthorize("hasRole('USER')") @GetMapping("/user") public ResponseEntity<String> helloUser() { return ("Hello User"); } }
-
@PreAuthorize("hasRole('ADMIN')")
: Applied tohelloAdmin()
Method, indicating that only users with the ‘ADMIN’ role can access this endpoint. -
@PreAuthorize("hasRole('USER')")
: Applied tohelloUser()
Method, restrict access to only users with the ‘USER’ role.
Summarize
This tutorial describes how to use Spring method-level security and@PreAuthorize
Annotations to protect the RestController method. With these steps, you can ensure that only users with the appropriate role or permissions can access a specific REST API.
This is the end of this article about Spring Security @PreAuthorize annotation analysis. For more related Spring Security @PreAuthorize content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!