You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Spring Security使登录认证失败时返回401而非登录页

解决方案

你需要在formLogin配置段追加自定义登录失败处理器,覆盖Spring Security默认的「跳转登录页」逻辑,直接返回401状态码和空响应即可。

修改后的配置代码如下:

@Override
public void configure(final AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable()
            .authorizeRequests()
            .antMatchers("/**").hasAuthority("Business_User")
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginProcessingUrl("/login")
            .usernameParameter("username")
            .passwordParameter("password")
            // 新增登录失败处理逻辑
            .failureHandler((request, response, exception) -> {
                response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().flush();
            });
    http.headers().frameOptions().disable();
}

逻辑说明

  • failureHandler是Spring Security提供的认证失败回调入口,所有用户名不存在、密码错误、账号状态异常等认证失败场景,都会触发该处理器的逻辑
  • 处理器内直接将响应状态码设为401(SC_UNAUTHORIZED常量对应值就是401),刷写响应流后返回,响应体为空,完全符合需求
  • 如果你使用的Spring Security版本不支持lambda写法,可单独定义实现类实现AuthenticationFailureHandler接口,重写onAuthenticationFailure方法实现相同逻辑后,将类实例传入failureHandler方法即可

内容的提问来源于stack exchange,提问作者user8473984

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 10:39:04