Make your Spring Security @Secured annotations more DRY
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 2 3 | admins=ROLE_ADMIN, ROLE_SUPERADMIN switchUser=ROLE_SWITCH_USER editors=ROLE_EDITOR, ROLE_ADMIN |
These keys are the values you use for the new @Authorities
annotation:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | package grails.plugins.springsecurity.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.codehaus.groovy.transform.GroovyASTTransformationClass; /** * @author Burt Beckwith */ @Target ({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) @Retention (RetentionPolicy.RUNTIME) @Inherited @Documented @GroovyASTTransformationClass ( "grails.plugins.springsecurity.annotation.AuthoritiesTransformation" ) public @interface Authorities { /** * The property file key; the property value will be a * comma-delimited list of role names. * @return the key */ String value(); } |
For example here’s a controller using the new annotation:
1 2 3 4 5 6 7 8 | @Authorities ( 'admins' ) class SecureController { @Authorities ( 'editors' ) def someAction() { ... } } |
This is the equivalent of this controller (and if you decompile the one with @Authorities
you’ll see both annotations):
1 2 3 4 5 6 7 8 | @Secured ([ 'ROLE_ADMIN' , 'ROLE_SUPERADMIN' ]) class SecureController { @Secured ([ 'ROLE_EDITOR' , 'ROLE_ADMIN' ]) def someAction() { ... } } |
The AST transformation class looks for @Authorities
annotations, loads the properties file, and adds a new @Secured
annotation (the @Authorities
annotation isn’t removed) using the role names specified in the properties file:
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095 096 097 098 099 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | package grails.plugins.springsecurity.annotation; import grails.plugins.springsecurity.Secured; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.ListExpression; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.transform.ASTTransformation; import org.codehaus.groovy.transform.GroovyASTTransformation; import org.springframework.util.StringUtils; /** * @author Burt Beckwith */ @GroovyASTTransformation (phase=CompilePhase.CANONICALIZATION) public class AuthoritiesTransformation implements ASTTransformation { protected static final ClassNode SECURED = new ClassNode(Secured. class ); public void visit(ASTNode[] astNodes, SourceUnit sourceUnit) { try { ASTNode firstNode = astNodes[ 0 ]; ASTNode secondNode = astNodes[ 1 ]; if (!(firstNode instanceof AnnotationNode) || !(secondNode instanceof AnnotatedNode)) { throw new RuntimeException( "Internal error: wrong types: " + firstNode.getClass().getName() + " / " + secondNode.getClass().getName()); } AnnotationNode rolesAnnotationNode = (AnnotationNode) firstNode; AnnotatedNode annotatedNode = (AnnotatedNode) secondNode; AnnotationNode secured = createAnnotation(rolesAnnotationNode); if (secured != null ) { annotatedNode.addAnnotation(secured); } } catch (Exception e) { // TODO e.printStackTrace(); } } protected AnnotationNode createAnnotation(AnnotationNode rolesNode) throws IOException { Expression value = rolesNode.getMembers().get( "value" ); if (!(value instanceof ConstantExpression)) { // TODO System.out.println( "annotation @Authorities value isn't a ConstantExpression: " + value); return null ; } String fieldName = value.getText(); String[] authorityNames = getAuthorityNames(fieldName); if (authorityNames == null ) { return null ; } return buildAnnotationNode(authorityNames); } protected AnnotationNode buildAnnotationNode(String[] names) { AnnotationNode securedAnnotationNode = new AnnotationNode(SECURED); List<Expression> nameExpressions = new ArrayList<Expression>(); for (String authorityName : names) { nameExpressions.add( new ConstantExpression(authorityName)); } securedAnnotationNode.addMember( "value" , new ListExpression(nameExpressions)); return securedAnnotationNode; } protected String[] getAuthorityNames(String fieldName) throws IOException { Properties properties = new Properties(); File propertyFile = new File( "roles.properties" ); if (!propertyFile.exists()) { // TODO System.out.println( "Property file roles.properties not found" ); return null ; } properties.load( new FileReader(propertyFile)); Object value = properties.getProperty(fieldName); if (value == null ) { // TODO System.out.println( "No value for property '" + fieldName + "'" ); return null ; } List<String> names = new ArrayList<String>(); String[] nameArray = StringUtils.commaDelimitedListToStringArray( value.toString()) for (String auth : nameArray) { auth = auth.trim(); if (auth.length() > 0 ) { names.add(auth); } } return names.toArray( new String[names.size()]); } } |
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, run grails clean
and grails compile
to be sure that the latest values are used.
Reference: Make your Spring Security @Secured annotations more DRY from our JCG partner Burt Beckwith at the An Army of Solipsists blog.