Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 666
KyleM Avatar asked Feb 07 '23 19:02

KyleM


2 Answers

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

like image 106
Jérémie B Avatar answered Feb 10 '23 08:02

Jérémie B


This is not working in Spring 5 becuase default bean overriding is disabled by default. It works only with spring.main.allow-bean-definition-overriding property set to true.

If anyone have some idea how to add custom MethodSecurityMetadataSource to GlobalMethodSecurityConfiguration without bean override enabling, it will be helpful for newer Spring version

like image 34
Kappa Avatar answered Feb 10 '23 08:02

Kappa