Reputation: 4298
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.
Upvotes: 5
Views: 5769
Reputation: 7553
In Spring Boot you can add custom MethodSecurityMetadataSource
s and AccessDecisionVoter
s by overriding the corresponding methods in GlobalMethodSecurityConfiguration
and adding/modifying the values form the superclass.
@Configuration
@AutoConfigureAfter(SecurityConfiguration.class)
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class MethodSecurityConfiguration extends GlobalMethodSecurityConfiguration {
@Override
public MethodSecurityMetadataSource methodSecurityMetadataSource() {
var source = (DelegatingMethodSecurityMetadataSource) super.methodSecurityMetadataSource();
source.getMethodSecurityMetadataSources().add(new FooSecurityMetadataSource());
return source;
}
@Override
protected AccessDecisionManager accessDecisionManager() {
var manager = (AffirmativeBased) super.accessDecisionManager();
manager.getDecisionVoters().add(new FooVoter());
return manager;
}
}
Upvotes: -1
Reputation: 41
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
Upvotes: 3
Reputation: 11022
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
Upvotes: 9