概述
我們可以通過集成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());