Recently a user on the Grails User mailing list wanted to know how to reduce repetition when defining @Secured annotations. The rules for specifying attributes in Java annotations are pretty restrictive, so I couldn’t see a direct way to do what he was asking.
Using Groovy doesn’t really help here since for the most part annotations in a Groovy class are pretty much the same as in Java (except for the syntax for array values). Of course Groovy now supports closures in annotations, but this would require a code change in the plugin. But then I thought about some work Jeff Brown did recently in the cache plugin.
Spring’s cache abstraction API includes three annotations; @Cacheable,@CacheEvict, and @CachePut. We were thinking ahead about supporting more configuration options than these annotations allow, but since you can’t subclass annotations we decided to use an AST transformation to find our versions of these annotations (currently with the same attributes as the Spring annotations) and convert them to valid Spring annotations. So I looked at Jeff’s code and it ended up being the basis for a fix for this problem.
It’s not possible to use code to externalize the authority lists because you can’t control the compilation order. So I ended up with a solution that isn’t perfect but works – I look for a properties file in the project root (roles.properties). The format is simple – the keys are names for each authority list and the values are the lists of authority names, comma-delimited. Here’s an example:
1
admins=ROLE_ADMIN, ROLE_SUPERADMIN
2
switchUser=ROLE_SWITCH_USER
3
editors=ROLE_EDITOR, ROLE_ADMIN
These keys are the values you use for the new @Authorities annotation:
* The property file key; the property value will be a
24
* comma-delimited list of role names.
25
* @return the key
26
*/
27
String value();
28
}
For example here’s a controller using the new annotation:
1
@Authorities('admins')
2
classSecureController {
3
4
@Authorities('editors')
5
def someAction() {
6
...
7
}
8
}
This is the equivalent of this controller (and if you decompile the one with @Authorities you’ll see both annotations):
1
@Secured(['ROLE_ADMIN', 'ROLE_SUPERADMIN'])
2
classSecureController {
3
4
@Secured(['ROLE_EDITOR', 'ROLE_ADMIN'])
5
def someAction() {
6
...
7
}
8
}
The AST transformation class looks for @Authorities annotations, loads the properties file, and adds a new @Securedannotation (the @Authorities annotation isn’t removed) using the role names specified in the properties file:
I’ll probably include this in the plugin at some point – I created a JIRA issue as a reminder – but for now you can just copy these two classes into your application’s src/java folder and create a roles.properties file in the project root. Any time you want to add or remove an entry or add or remove a role name from an entry, update the properties file, rungrails clean and grails compile to be sure that the latest values are used.