silverhawk silverhawk - 1 month ago 32
Java Question

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?

Answer

This issue was solved.

I add @EnableGlobalMethodSecurity(prePostEnabled = true)

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AppSecurityConfiguration extends WebSecurityConfigurerAdapter{
}

And in controller i changed @Secured("ADMIN") to @PreAuthorize("hasRole('ADMIN')")