通过注释的Spring授权不使用自定义身份验证

时间:2011-11-22 11:16:54

标签: spring spring-security jsr250

我已经覆盖了BasicAuthenticationFilter并将其替换为我们的过滤器以从db获取自定义Authentication对象并通过

设置它
SecurityContextHolder.getContext().setAuthentication(auth);

以下是安全配置的重要部分:

<http use-expressions="true" entry-point-ref="authEntryPoint">
    <custom-filter position="BASIC_AUTH_FILTER" ref="basicProcessingFilter" />
    <intercept-url pattern="/**" access="hasRole('user')"/>
</http>
<beans:bean id="authEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
    <beans:property name="loginFormUrl" value="/login"/>
</beans:bean>
<global-method-security jsr250-annotations="enabled"/>

我还提供自己的AuthenticationProvider,它只是一个无操作,因为身份验证过程已在自定义过滤器中完成:

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    logger.info("user:" + authentication.getPrincipal() + " pw:" + authentication.getCredentials());
    authentication.setAuthenticated(false);        
    return authentication;
}

@Override
public boolean supports(Class<? extends Object> authentication) {
    return MyAuthentication.class.isAssignableFrom(authentication);
}

现在,Spring正确地为每个启动方法打印了所需的角色,因此它可以正确检测注释。例如。删除方法的'admin'角色:

2011-11-22 11:47:09,474 [main] DEBUG org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource - 添加安全方法[CacheKey [com.somecompany.SomeClass; public com.somecompany.ReturnType com.somecompany.SomeClass.delete()]],带有属性[admin]

但是Spring不会以某种方式检查用户是否具有此角色。而是回退到安全上下文xml文件的http标记中定义的全局模式。所以,例如如果我使用角色用户访问此删除方法:[“user”]它将接受它,因为http标记中有hasRole('user')。

初始化DefaultFilterInvocationSecurityMetadataSource对象时可能会出错,因为它不会被删除方法的特定规则填充!?仅通过addSecureUrl方法添加了http标签定义的规则。

可能出现什么问题?

1 个答案:

答案 0 :(得分:2)

移动

<global-method-security jsr250-annotations="enabled"/>

从Spring安全上下文到我'扫描'类的上下文(即我的应用程序上下文)帮助。感谢this answer

的评论