【发布时间】:2015-05-22 08:24:19
【问题描述】:
我在示例代码中遇到了以下注释。
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
谁能解释一下是什么意思?
【问题讨论】:
标签: java spring security annotations role
我在示例代码中遇到了以下注释。
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
谁能解释一下是什么意思?
【问题讨论】:
标签: java spring security annotations role
@Secured注解是Spring框架中的一种方法安全。它是在方法级别应用的授权语义之一。它允许至少具有@Secured 注释中指定的角色之一的用户访问该方法。
在您查看的示例中,即@Secured({ROLE_USER, ROLE_ADMIN}) 表示此注释后面的方法只能由具有 ROLE_ADMIN 或 ROLE_USER 的人访问。
如需进一步参考,请转至this 页面。
【讨论】:
这里有一个例子:
@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);
}
}
【讨论】:
这是一个 Spring Security Framework 注解,仅当调用者具有 ROLE_USER 或 ROLE_ADMIN 安全角色时才允许执行该方法。
有关 Spring Security 的更多信息,请参阅documentation。
【讨论】: