I am trying to set up a method security annotation using @Secured("ADMIN") (without any XML, only java config, Spring Boot). But access via roles does not work.
Security Config:
@Configuration @EnableWebSecurity public class AppSecurityConfiguration extends WebSecurityConfigurerAdapter{ ..... @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/api/**").fullyAuthenticated().and() .addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } ..... }
I want restrict access to the method of the controller:
@RestController @RequestMapping("/api/groups") public class GroupController { @Autowired private GroupService groupService; @Secured("ADMIN") @RequestMapping public List<Group> list() { return groupService.findAll(); } }
Restrict access by the url is working, with:
.antMatchers("/api/**").hasAuthority("ADMIN")
Maybe I forgot to specify that I want restrict by roles?
UPD: By the rules, At what layer must be @PreAuthorize("hasRole('ADMIN')")
in Controller layer or in Service layer?
Method-level security is implemented by placing the @PreAuthorize annotation on controller methods (actually one of a set of annotations available, but the most commonly used). This annotation contains a Spring Expression Language (SpEL) snippet that is assessed to determine if the request should be authenticated.
The @Secured annotation is used to specify a list of roles on a method. So, a user only can access that method if she has at least one of the specified roles.
Kindly add this
@EnableGlobalMethodSecurity(securedEnabled = true)
This element is used to enable annotation-based security in your application (by setting the appropriate attributes on the element), and also to group together security pointcut declarations which will be applied across your entire application context specifically for @Secured
. Hence your code should look like this
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) public class AppSecurityConfiguration extends WebSecurityConfigurerAdapter{..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With