You can use the annotation @Secured
or @RolesAllowed
or @PreAuthorise
/ @PostAuthorise
in Spring Security.
Remember: You need to add this code
@Configuration
@EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true
)
public class MyConfig extends WebSecurityConfigurerAdapter{
}
in front of your configure class. You do not need use all of the 3 parameters securedEnabled
, jsr250Enabled
, prePostEnabled
. You only need one depending on which annotation you want to use.
Then put the role check annotation in your controller class.
@Secured("ROLE_admin")
@GetMapping("/hello")
public String hello(){
return "hello";
}
or
@RolesAllowed("ROLE_admin")
@GetMapping("/hello")
public String hello(){
return "hello";
}
or
@PreAuthorize("hasRole('ROLE_user')")
@GetMapping("/hello")
public String hello(){
return "hello";
}
Here is a tutorial https://www.baeldung.com/spring-security-method-security