spring-security 提供了一些默认的过滤器用于实现基本的认证和授权策略。其中,UsernamePasswordAuthenticationFilter 主要用于处理登录认证的逻辑。
然而,它并不适用于所有情况,有时需要实现自定义的认证方式以及让其在Filter Chain 中使用。这时,强行使用UsernamePasswordAuthenticationFilter 会导致许多问题,例如:
因此,建议使用基于AbstractAuthenticationProcessingFilter自定义认证过滤器。
以下是一个自定义的TokenAuthenticationFilter示例:
public class TokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private final String HEADER_AUTHORIZATION = "Authorization";
public TokenAuthenticationFilter() {
super("/api/**");
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
String token = request.getHeader(HEADER_AUTHORIZATION);
if (token == null || token.isBlank()) {
throw new AuthenticationServiceException("No token provided");
}
return getAuthenticationManager().authenticate(new TokenAuthentication(token));
}
}
其中,TokenAuthentication 继承自 AbstractAuthenticationToken,并且实现了getCredentials() 和 getPrincipal() 等方法。
在配置中,只需要将该filter添加到现有的过滤器链中即可。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService userDetailsService;
@Autowired
private TokenAuthenticationFilter tokenAuthenticationFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
// ...
http.addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.