问题:
在使用Springsecurity时使用postman访问登录失败能得到自定义错误信息401,但是使用浏览器访问的时候,当登录成功时能正常进入自定义配置类,但是失败是直接给浏览器返回一个状态码302,并且通过查看断点并不能进入配置类
原因:
springsecurity对未认证的访问会默认重定向一个接口,因前后端分离,所以不能实现前端自定义跳转到登陆页面的逻辑,实际修改方案就是后台修改springsecurity框架默认的302执行逻辑。
解决方法:
实现AuthenticationEntryPoint接口,覆写commence方法,修改返回状态值为401,修改配置。让前端去获取状态码执行前端的逻辑。
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
}
}
@Configuration
public class BrowserSecurityConfig extends AbstractChannelSecurityConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
applyPasswordAuthenticationConfig(http);
http.apply(validateCodeSecurityConfig)
.and()
.apply(smsCodeAuthenticationSecurityConfig)
.and()
.apply(imoocSocialSecurityConfig)
.and()
.sessionManagement()
.invalidSessionStrategy(invalidSessionStrategy)
.maximumSessions(securityProperties.getBrowser().getSession().getMaximumSessions())
.maxSessionsPreventsLogin(securityProperties.getBrowser().getSession()
.isMaxSessionsPreventsLogin())
.expiredSessionStrategy(sessionInformationExpiredStrategy)
.and()
.and()
.logout()
.logoutSuccessHandler(onstepLogoutSuccessHandler)
.deleteCookies("JSESSIONID")
.and()
.authorizeRequests()
.antMatchers(
securityProperties.getBrowser().getLoginPage(),
securityProperties.getBrowser().getSignUpUrl())
.permitAll()
.anyRequest()
.authenticated()
.and()
.cors()
.and()
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint());
}
}
主要注意的代码:
1.response.setStatus(HttpStatus.UNAUTHORIZED.value());
2..exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint());
本文介绍在SpringSecurity框架中,如何自定义登录失败时的响应,避免默认的302重定向,通过实现AuthenticationEntryPoint接口并覆盖commence方法,设置HTTP状态码为401,使前后端分离项目能够正确处理登录失败的情况。
,前后端分离&spm=1001.2101.3001.5002&articleId=106946437&d=1&t=3&u=3dce1edfc51845d4bd5efd4b27239425)
1549

被折叠的 条评论
为什么被折叠?



