spring security中使用自定义方法安全注解

Kyl*_*leM 3 java spring annotations spring-security

我想用自定义注释标记类中的方法,该注释将使用 spring 安全性控制授权决策。例如:

@Role("ADMIN")
public void accessControlledMethod(){}
Run Code Online (Sandbox Code Playgroud)

我了解这意味着我需要以某种方式注册我的自定义注释“角色”,以便在ConfigAttributes授权决定做出时它可以出现AccessDecisionManager. 但是,我不明白如何使用 spring security 注册我的自定义注释以便它被识别。

我在框架代码中看到了一种潜在的解决方案。有一个名为 SecuredAnnotationSecurityMetadataSource 的类,其文档说“为自定义注释注入 AnnotationMetadataExtractor”。如果这是首选方法,我不确定如何配置 SecuredAnnotationSecurityMetadataSource 或如何将 AnnotationMetadataExtractor 注入其中。

Jér*_*e B 5

您可以GlobalMethodSecurityConfiguration在配置中扩展:

@EnableGlobalMethodSecurity
@Configuration
public class MyMethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    protected MethodSecurityMetadataSource customMethodSecurityMetadataSource() {
        return SecuredAnnotationSecurityMetadataSource(...);
    }    
}
Run Code Online (Sandbox Code Playgroud)

在 xml 中,您可以执行以下操作:

<global-method-security metadata-source-ref="customMethodSecurityMetadataSource">
...
</global-method-security>
<bean id="customMethodSecurityMetadataSource"  class="org.springframework.security.access.annotation.SecuredAnnotationSecurityMetadataSource">
...
</bean>
Run Code Online (Sandbox Code Playgroud)

customMethodSecurityMetadataSource 可以是 MethodSecurityMetadataSource 的任何实例