在Spring Security中实现自定义身份验证

Edd*_*son 2 java spring spring-security

我想就Spring Security中的问题向您寻求帮助.我有一个要求,我必须根据用户选择的选项验证登录凭证.选项1将通过第三方服务验证登录用户.选项2是使用数据库身份验证级别的正常验证.我该如何实现呢?

man*_*ish 10

一般战略

  1. 提供org.springframework.security.authentication.AuthenticationProvider将代理身份验证委派给适当后端(第三方服务,另一个AuthenticationProvider等)的自定义实现.
  2. 将用户选择的选项传递给自定义AuthenticationProvider,使其能够选择正确的身份验证后端.
  3. 将自定义配置AuthenticationProvider为默认身份验证提供程序.

第1步:实施 AuthenticationProvider

AuthenticationProvider是一个单一方法的接口.因此,自定义实现可能如下所示:

class DelegatingAuthenticationProvider implements AuthenticationProvider {
  @Autowired
  private ThirdPartyAuthenticationService service;

  @Autowired
  @Qualifier("anotherAuthenticationProvider")
  private AuthenticationProvider provider;

  @Override
  public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    // Get the user selection.
    String selection = (String) authentication.getDetails();

    // Take action depending on the selection.
    Authentication result;
    if("ThirdParty".equals(selection)) {
      // Authenticate using "service" and generate a new
      // Authentication "result" appropriately.
    }
    else {
      // Authenticate using "provider" and generate a new
      // Authentication "result" appropriately.
    }

    return result;
  }
}
Run Code Online (Sandbox Code Playgroud)

第2步:将用户选择传递给 AuthenticationProvider

AuthenticationProvider上面的实现从对象的details属性中选择用户选择Authentication.据推测,在调用之前,必须从用户中选择HttpServletRequest并添加到Authentication对象中AuthenticationProvider.这意味着,在调用之前需要调用另一个可以访问AuthenticationHttpServletRequest对象的组件AuthenticationProvider.

Authentication对象由实现创建AbstractAuthenticationProcessingFilter.该类有一个名为的方法attemptAuthentication,它接受一个HttpServletRequest对象并返回一个Authentication对象.因此,这似乎是实施所需内容的良好候选者.对于基于用户名密码的身份验证,实现类是UsernamePasswordAuthenticationFilter.该类返回一个新实例UsernamePasswordAuthenticationToken,它是一个实现Authentication.因此,扩展课程UsernamePasswordAuthenticationFilter应该足够了.

class ExtendedUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
  @Override
  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    ...
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, password);
    authentication.setDetails(obtainUserSelection(request));

    ...

    return authentication;
  }
}
Run Code Online (Sandbox Code Playgroud)

obtainUserSelection 是一种私有方法,可以从请求中选择用户.

第3步:配置

配置AuthenticationProvider和过滤器实现在春季安全配置.具体步骤将根据是使用XML还是Java配置而有所不同.