I have come accross the following annotation in my example code.
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
Could anyone explain what doest it mean?
It's a Spring Security Framework annotation to allow the method to be executed only when the caller has either ROLE_USER
or ROLE_ADMIN
security roles.
See the documentation for more information on Spring Security.
Here goes a example:
@Controller
public class ProtectedMethodsController {
@Secured({"ROLE_USER","ROLE_ADMIN"})//->for both security roles
@RequestMapping("/protectedMethod")
public @ResponseBody String secretMethod() {
return "You executed the protected method successfully (For USERs)";
}
@Secured("ROLE_ADMIN")
@RequestMapping("/adminProtectedMethod")
public @ResponseBody String adminSecretMethod() {
return "You executed the protected method successfully (For ADMINs)";
}
//->Without @Secured("ROLE_")
@RequestMapping("/notProtectedMethod")
public @ResponseBody String notProtectedMethod() {
return "You executed the not protected method successfully (For ALL USERs)";
}
/** Notes:
* 1 - The first step is to enable method security, you do that annotating
* the main class (class with the @SpringBootApplication annotation)
* with @EnableGlobalMethodSecurity(securedEnabled = true);
* 2 - Then we can decorate the method resources with @Secured("ROLE_USER")
* annotation.**/
}
@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true)
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) throws Throwable {
SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
@Secured
annotation is a method security in Spring framework. It is one of the authorization semantics applied at the method level . It allows the method to be accessed by the user who has atleast one of the roles specified in the @Secured
annotation.
In the example you have looked into, ie @Secured({ROLE_USER, ROLE_ADMIN})
signifies that the method following this annotation can be accessed only by someone who has either ROLE_ADMIN or ROLE_USER.
For further reference, go to this page.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.