不要在FilterChain中使用UsernamePasswordAuthenticationFilter
创始人
2025-01-11 01:30:33
0

spring-security 提供了一些默认的过滤器用于实现基本的认证和授权策略。其中,UsernamePasswordAuthenticationFilter 主要用于处理登录认证的逻辑。

然而,它并不适用于所有情况,有时需要实现自定义的认证方式以及让其在Filter Chain 中使用。这时,强行使用UsernamePasswordAuthenticationFilter 会导致许多问题,例如:

  1. 只支持 HTTP POST 方法提交表单数据,不支持其他方法和请求数据格式。
  2. 无法处理多个身份验证源,例如自定义密钥、非对称加密等方法。
  3. 无法自定义身份验证失败时的处理方式。
  4. 在过滤器链中的默认位置可能不符合我们的需求。

因此,建议使用基于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)
                .

相关内容

热门资讯

透视线上!wepoker脚本下... 透视线上!wepoker脚本下载,hhpoker德州挂真的有吗,透明挂教程(素来真的是有挂);原来确...
透视计算!aapoker透视软... 透视计算!aapoker透视软件,德州机器人代打脚本,技巧教程(起初真的是有挂);超受欢迎的aapo...
透视攻略!hhpoker透视脚... 透视攻略!hhpoker透视脚本安卓,wepoker软件靠谱么,解密教程(固有真的是有挂)1、这是跨...
透视app!wepoker透视... 透视app!wepoker透视脚本,wpk插件辅助,第三方教程(从来真的是有挂);1.wepoker...
透视好友房!wpk辅助购买,w... 透视好友房!wpk辅助购买,wepoker软件靠谱么,曝光教程(原本是有挂);wpk透视辅助官方版是...
透视脚本!wepoker底牌透... 透视脚本!wepoker底牌透视脚本app,pokerworld破解版下载,揭秘攻略(都是存在有挂)...
透视透视!wepoker透视脚... 透视透视!wepoker透视脚本免费,we poker辅助器下载,辅助教程(先前是真的有挂);科技安...
透视系统!hhpoker辅助下... 透视系统!hhpoker辅助下载,hhpoker是真的假的,解密教程(好像真的有挂);hhpoker...
透视工具!wepoker透视脚... 透视工具!wepoker透视脚本,竞技联盟透视插件,科技教程(好像是有挂)需要回顾用户提供的搜索结果...
透视规律!aapoker透视插... 透视规律!aapoker透视插件,sohoo poker辅助,总结教程(本来真的有挂);支持多人共享...