spring security抛出AuthenticationException异常的原因

本文深入探讨了使用MD5或其他加密算法保护密码时的密码验证机制,并强调了在UsernamePasswordAuthenticationFilter的子类中如何正确处理认证逻辑,确保用户名和密码验证的责任归属UserDetailsService。同时介绍了如何在attemptAuthentication方法中进行验证码检测、用户名提取、处理不同入口类型并最终通过UserDetailsService进行用户认证的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可能是因为密码不正确,特别是密码使用md5或者其它的加密算法加密之后,更是如此。

还有一点:

在UsernamePasswordAuthenticationFilter的子类中的attemptAuthentication方法中,只要去验证你自己的逻辑就可以了,不要在这里验证用户名,密码是否正确,因为这是UserDetailsService要干的事情。

比如我的attemptAuthentication方法中就是这样:

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
           if (!request.getMethod().equals("POST")) {  
                throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());  
            }  
            //检测验证码  
            checkValidateCode(request); 
            String username = obtainUsername(request);  
            String password = obtainPassword(request);  
            
            //为了辨别从前台进入的,还是从后台进入的
            String type=request.getParameter(ENTRY);
            request.getSession().setAttribute(USER_ENTRY, type);
            if("bg".equals(type))
            {
                username="bg_"+username;
            }else if("fg".equals(type))
            {
                username="fg_"+username;
            }
            
              
            //这里的username会传给UserDetailsService的loadUserByUsername方法,作为loadUserByUsername的参数。
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);  
              
            // 允许子类设置详细属性  
            setDetails(request, authRequest);  
              
            // 运行UserDetailsService的loadUserByUsername 再次封装Authentication  
            AuthenticationManager authenticationManager = this.getAuthenticationManager();
            Authentication authentication=authenticationManager.authenticate(authRequest);
            return authentication;  
    }

 

### 处理Spring Security中导致401 Unauthorized响应的内部异常 当应用程序使用Spring Security保护资源时,未经身份验证或未经授权访问受保护资源会触发`401 Unauthorized`响应。这种情况下通常涉及的是`AuthenticationException`[^2]。 为了更友好地处理这些情况并返回定制化的错误消息给客户端,在Spring Security配置中可以实现`AuthenticationEntryPoint`接口来指定未认证请求应如何被处理[^3]: ```java import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CustomAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName()); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); } @Override public void afterPropertiesSet() throws Exception { setRealmName("My Application"); super.afterPropertiesSet(); } } ``` 接着需要将这个入口点注册到安全配置里去: ```java @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint; @Autowired public WebSecurityConfig(CustomAuthenticationEntryPoint customAuthenticationEntryPoint){ this.customAuthenticationEntryPoint = customAuthenticationEntryPoint; } @Override protected void configure(HttpSecurity http) throws Exception { http.exceptionHandling() .authenticationEntryPoint(customAuthenticationEntryPoint); // Other configurations... } // ... } ``` 通过这种方式,每当有未经过适当的身份验证尝试访问受限资源的情况发生时,就会调用上述方法,并按照设定的方式向客户端发送带有特定信息的状态码和头部字段。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值