@Secured({" ROLE_USER"," ROLE_ADMIN"})的确切意味着什么

时间:2015-03-19 09:27:29

标签: java spring security annotations role

我在示例代码中遇到了以下注释。

@Secured({ "ROLE_USER", "ROLE_ADMIN" }) 

有人能解释一下这是什么意思吗?

3 个答案:

答案 0 :(得分:3)

这是一个Spring Security Framework注释,只允许在调用者具有ROLE_USERROLE_ADMIN安全角色时执行该方法。

有关Spring Security的更多信息,请参阅documentation

答案 1 :(得分:0)

这是一个例子:

@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);
    }
}

答案 2 :(得分:0)

@Secured注释是Spring框架中的一种方法安全性。它是在方法级别应用的授权语义之一。它允许具有至少@Secured注释中指定角色之一的用户访问该方法。

在您研究的示例中,即@Secured({ROLE_USER, ROLE_ADMIN})表示只有具有ROLE_ADMIN或ROLE_USER的用户才能访问此批注后面的方法。

有关更多参考,请转到this页。