Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security, Method Security annotation (@Secured ) is not working (java config)

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?

like image 639
silverhawk Avatar asked Jul 02 '15 14:07

silverhawk


People also ask

How do I enable method level security in Spring?

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.

How does secured annotation work?

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.


1 Answers

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{.. 
like image 74
Mudassar Avatar answered Sep 22 '22 16:09

Mudassar