在Spring Security中的FORM_LOGIN_FILTER之后添加可选的身份验证步骤

时间:2014-10-24 09:37:24

标签: java spring authentication spring-security

我在Web应用程序中使用Spring Security的基本登录工作流程:用户通过表单登录,该表单最终由UserDetailsService中的DaoAuthenticationProvider中的应用程序逻辑处理,并带有令牌由UsernamePasswordAuthenticationFilter创建。

但是,在某些情况下(在运行时通过用户偏好决定),我希望在此之后有一个额外的身份验证步骤(基本上是双因素身份验证)。我尝试添加其他类似的过滤器

<custom-filter ref="twoFactorAuthFilter" after="FORM_LOGIN_FILTER"/>

但是如果表单登录成功,则永远不会调用此过滤器。我的计划是创建一个可由TwoFactorAuthenticationToken接受的特殊TwoFactorAuthenticationProvider,但由于未调用过滤器,我的新身份验证提供程序也不是。如果登录凭据错误,我希望整个安全链中止,但如果它们正确则继续遍历它并继续(可选)下一步。

是否有可能在不重写现有UsernamePasswordAuthenticationFilter的情况下按我的意愿行事?我觉得这一定很容易,因为Spring通常具有相当的可扩展性,但我现在已经和它斗争了很多天而且还没有取得任何成功。

2 个答案:

答案 0 :(得分:1)

您想要的是两个过滤器:一个用于userNamePasswordFilter,另一个用于tokenFilter。如果您的用户启用了双因素身份验证,userDetailsService daoAuthenticationProvider SimpleGrantedAuthority只应授予他一个tokenFilter个实例,其中包含一个角色&#34; ROLE_PRE_AUTH&#34;例如。只应向具有此角色的用户提供对tokenProvider的访问权限 - &#34; ROLE_PRE_AUTH&#34;并且该过滤器应尝试对您的辅助令牌进行身份验证,然后继续从{{1}}向用户授予其实际权限(USER,ADMIN等)。 显示该附加弹出窗体的方式同样是检查用户的角色是否为&#34; ROLE_PRE_AUTH&#34;。

答案 1 :(得分:0)

您只需要使用登录后身份验证逻辑扩展DaoAuthenticationProvider并覆盖additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication)

public CustomDaoAuthenticationProvider extends DaoAuthenticationProvider {

    public additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        super.additionalAuthenticationChecks(userDetails, authentication);

        // Your Logic Here
    }
}

修改

我可能误解了你的问题,因为你提到过&#34; Logic&#34;。无论如何,post显示了您问题的优雅解决方案。