【问题标题】:Enum in SpEL for grails spring security annotation?SpEL中的枚举用于grails spring安全注释?
【发布时间】:2013-11-25 07:08:24
【问题描述】:

假设一个 grails (v2.3.x) 自定义类以模仿 @JamesWatkins in this post 概述的 java 方式创建和设置,使用静态字符串注释方法很简单:

@Secured(["@mySecurityService.hasPermission('special')"])
public void doSpecialStuff() { ... }

但是为了防止硬编码值,是否可以通过在 SpEL 表达式中嵌入自定义 Enum(或类似的)来替换 'special'

我试过这个:

@Secured(["@mySecurityService.hasPermission('{ T(com.example.MyConfig$MyEnum.SPECIAL) }')"])
public void doSpecialStuff() { ... }

但我不断收到关于字符串不是常量的异常:

Expected '@mySecurityService.hasPermission('{ T(com.example.MyConfig$MyEnum.SPECIAL) }')' to be an inline constant of type java.lang.String

【问题讨论】:

    标签: grails enums spring-security annotations spring-el


    【解决方案1】:

    首先,SpEL 语法是错误的。删除' 并将.SPECIAL 移到T(...) 之外。

    此外,@Secured 不支持 SpEL - 如在另一篇文章中所见,您必须使用 @PreAuthorize

    我刚刚写了一个快速测试用例,效果很好……

    public class TestHandler implements MessageHandler {
    
        public List<Message<?>> sentMessages = new ArrayList<Message<?>>();
    
        @Override
        @PreAuthorize("@myAuth.hasPermission(T(foo.TestHandler$MyEnum).FOO.toString())")
        public void handleMessage(Message<?> message) {
            sentMessages.add(message);
        }
    
        public enum MyEnum {
            FOO("foo");
    
            private final String value;
    
            private MyEnum(String value) {
                this.value = value;
            }
    
            @Override
            public String toString() {
                return value;
            }
        }
    
        public static class MyAuth {
    
            public boolean hasPermission(String foo) {
                return "foo".equals(foo);
            }
        }
    
    }
    

    【讨论】:

    • 不幸的是,这会引发相同的错误:` 预期 '@mySecurityService.hasPermission({ T(com.example.MyConfig$MyEnum).SPECIAL })' 是 java.lang 类型的内联常量。 @org.springframework.security.access.annotation.Secured @ 第 26 行,第 15 列中的字符串。`
    • 对不起,我没有看大局,只是更正了您的 SpEL 语法错误。用解决方案更新了我的答案。
    • 感谢@gary-russell,但我应该使用多个标签来表明我正在尝试在支持SpEL的grails(v2.3.x)中执行此操作@987654328 @标签(我将编辑我的问题)。无论如何,我尝试使用@PreAuthorize 并得到相同的错误消息。查看response from Burt Beckwith to this post,听起来grails spring-security 插件(v2.0-RC2)可能无法通过直接java 模仿SpEL 支持。
    • 好的;抱歉 - 我是一个 java 人 :-)
    猜你喜欢
    • 1970-01-01
    • 2014-03-15
    • 2018-02-22
    • 2013-06-19
    • 2016-11-17
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    相关资源
    最近更新 更多