java 使用 Spring Security 的 @Secured 批注中是否允许多个角色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7918154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:01:06  来源:igfitidea点击:

Are multiple roles allowed in the @Secured annotation with Spring Security

javaspring-security

提问by Paul Gregtheitroade

I would like to allow access to a particular method to more than one group of users. Is it possible in Spring Security 3.x to do such a thing using the @Secured annotation? Consider two groups (roles) OPERATOR and USER, would this code be valid:

我想允许一组以上的用户访问特定方法。在 Spring Security 3.x 中是否可以使用 @Secured 注释来做这样的事情?考虑两组(角色)操作员和用户,此代码是否有效:

    @Secured("ROLE_OPERATOR", "ROLE_USER")
    public void doWork() {
        // do useful processing
    }

回答by Donal Fellows

You're almost there. Syntactically, you need to write it like this:

你快到了。在语法上,你需要这样写:

@Secured({"ROLE_OPERATOR", "ROLE_USER"})
public void doWork() { ... }

This is because you're supplying multiple values to a single array attribute of the annotation. (Java syntactically special-cases handing in a single value, but now you need to do it “properly”.)

这是因为您要为注释的单个数组属性提供多个值。(Java 语法上的特殊情况处理单个值,但现在您需要“正确地”执行此操作。)

回答by 10GritSandpaper

@Donal Fellows answer is correct for Spring apps. However, if you're working in Grails, you need to use the Groovy syntax for lists so the code would look like this

@Donal Fellows 的回答对于 Spring 应用程序是正确的。但是,如果您在 Grails 中工作,则需要对列表使用 Groovy 语法,因此代码如下所示

@Secured(["ROLE_OPERATOR", "ROLE_USER"])
public void doWork() { ... }