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:

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:

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:

@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):

@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:

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.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


six − = 5



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books