@Secured({ "ROLE_USER", "ROLE_ADMIN" }) 到底是什么意思

What does @Secured({ "ROLE_USER", "ROLE_ADMIN" }) exactly means

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

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

谁能解释一下这是什么意思?

这是一个 Spring 安全框架注释,允许仅当调用者具有 ROLE_USERROLE_ADMIN 安全角色时才执行该方法。

有关 Spring 安全性的详细信息,请参阅 documentation

举个例子:

@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注解是Spring框架中的一个方法安全。它是 在方法级别 应用的授权语义之一。它允许至少具有 @Secured 注释中指定角色之一的用户访问该方法。

在您查看的示例中,即 @Secured({ROLE_USER, ROLE_ADMIN}) 表示此注释后面的方法只能由具有 ROLE_ADMIN 或 ROLE_USER 的人访问。

如需进一步参考,请转到 this 页面。