Spring Security 自定義身份認證過濾器

概述

我們可以通過集成AbstractAuthenticationProcessingFilter或者現有的過濾器來完成自定義的身份認證過濾器

身份驗證過濾器的主要責任是何時進行身份認證以及如何進行身份認證等

實現案例

以下是實現案例,可根據需求進行拓展和剔除

1. 繼承AbstractAuthenticationProcessingFilter

public class GetRequestAuthenticationFilter extends AbstractAuthenticationProcessingFilter { }

2. 重寫attemptAuthentication()方法

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    if (request.getMethod().toUpperCase().equals("GET")) {
        // 創建身份認證對象
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("test", "test");
        // 設置細節信息
        token.setDetails(new WebAuthenticationDetails(request));
        // 將身份認證對象交給身份認證管理器進行身份認證
        return this.getAuthenticationManager().authenticate(token);
    }
    return null;
}

3. 爲Filter設置AuthenticationManager

可通過自定義AuthenticationManager和默認AuthenticationManager設置

自定義AuthenticationManager

public GetRequestAuthenticationFilter testFilter(){
	GetRequestAuthenticationFilter filter = new GetRequestAuthenticationFilter();
    filter.setAuthenticationManager(new ProviderManager(Arrays.asList(new AuthenticationProvider() {
      @Override
      public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if ("admin".equals(authentication.getPrincipal()) && "123456".equals(authentication.getCredentials())) {
          List<GrantedAuthority> grantedAuthorities = Arrays.asList(new SimpleGrantedAuthority("admin"));
          UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getAuthorities(), grantedAuthorities);
          token.setDetails(authentication.getDetails());
          return token;
        }else{
          throw new BadCredentialsException("賬號密碼錯誤");
        }
      }

      @Override
      public boolean supports(Class<?> aClass) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass);
      }
    })));
    return filter;
}

默認ProviderManager

GetRequestAuthenticationFilter filter = new GetRequestAuthenticationFilter();
filter.setAuthenticationManager(super.authenticationManager());
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章