0

Assuming a grails (v2.3.x) custom class created and setup in a way that mimics the java way outlined by @JamesWatkins in this post, it is simple to annotate a method with a static string:

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

But in an attempt to prevent hard-coding values, is it possible to replace 'special' by embedding a custom Enum (or similar) in the SpEL expression?

I have tried this:

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

but I keep getting an exception about the string not being a constant:

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

1 Answers1

2

First of all, the SpEL syntax is wrong. Remove the ' and move the .SPECIAL outside the T(...).

Further, @Secured doesn't support SpEL - as seen in the other post, you have to use @PreAuthorize.

I just wrote a quick test case, and this works fine...

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

}
Gary Russell
  • 166,535
  • 14
  • 146
  • 179
  • Unfortunately this throws the same error: ` Expected '@mySecurityService.hasPermission({ T(com.example.MyConfig$MyEnum).SPECIAL })' to be an inline constant of type java.lang.String in @org.springframework.security.access.annotation.Secured @ line 26, column 15.` – mdlandon Nov 13 '13 at 19:04
  • Sorry, I wasn't looking at the bigger picture, just correcting your SpEL syntax error. Updated my answer with a solution. – Gary Russell Nov 13 '13 at 20:10
  • Thanks @gary-russell, but I should've used more than tags to indicate that I'm trying to do this in grails (v2.3.x) which does support SpEL with the `@Secured` tag (I'll edit my question). Regardless, I tried using `@PreAuthorize` and got the same error message. Looking at the [response from Burt Beckwith to this post](http://stackoverflow.com/questions/3508184/using-pre-post-spring-security-annotations-with-grails), it sounds like the grails spring-security plugin (v2.0-RC2) might not mimic the SpEL support avail via straight java. – mdlandon Nov 14 '13 at 16:46
  • OK; sorry - I am a java guy :-) – Gary Russell Nov 14 '13 at 17:26