KyleM February 2016

Using custom method security annotation in spring security

I want to tag methods in a class with a custom annotation that will control authorization decisions using spring security. For example:

@Role("ADMIN")
public void accessControlledMethod(){}

I understand that this means I somehow need to register my custom annotation "Role" so that it can result in ConfigAttributes being present when an authorization decision is made by the AccessDecisionManager. However, I do not understand how to register my custom annotation with spring security so that it will be recognized.

I see one potential solution in the framework code. There is a class called SecuredAnnotationSecurityMetadataSource whose documentation says "inject AnnotationMetadataExtractor for custom annotations". If that is the preferred method, I'm not sure how to configure the SecuredAnnotationSecurityMetadataSource or how to inject the AnnotationMetadataExtractor into it.

Answers


Jérémie B February 2016

You can extend GlobalMethodSecurityConfiguration in your configuration :

@EnableGlobalMethodSecurity
@Configuration
public class MyMethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    protected MethodSecurityMetadataSource customMethodSecurityMetadataSource() {
        return SecuredAnnotationSecurityMetadataSource(...);
    }    
}

In xml, you can do :

<global-method-security metadata-source-ref="customMethodSecurityMetadataSource">
...
</global-method-security>

<bean id="customMethodSecurityMetadataSource"
    class="org.springframework.security.access.annotation.SecuredAnnotationSecurityMetadataSource">
  ...
</bean>

customMethodSecurityMetadataSource can be any instanceof MethodSecurityMetadataSource

Post Status

Asked in February 2016
Viewed 1,945 times
Voted 10
Answered 1 times

Search




Leave an answer