Springsecurity使用浏览器登录失败返回302(跨域问题),前后端分离

问题:
在使用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());
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值