SpringSecurity CookieTheftException异常

SpringSecurity的前端把储存在Cookie的session和token改了以后就会报错,应该是从tokenRepository里取出的token与接收到的解码后的cookie不一致,然后导致抛出CookieTheftException异常。问题原因知道,想问问有啥办法捕获这个异常呢(全局异常处理肯定不行,试过了,那个好像只能捕获控制层的),我看httpSecurity.rememberMe()只有成功事件没有失败事件呢

img


img


img


img


类似问题:https://ask.csdn.net/questions/7547447

可不可以重写相关的类,通过继承重写相关的方法,在把这个对象代替原对象注入到spring里面去,达到捕捉异常的目的,以及保持编码与解码一致

以下答案引用自GPT-3大模型,请合理使用:

案例。

解决这个问题的方法是在你的应用中定义一个CookieTheftExceptionHandler,它实现Spring Security的AuthenticationFailureHandler接口,如下:

public class CookieTheftExceptionHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        if (exception instanceof CookieTheftException) {
            // Do what you need to do here
        }
    }
}

然后将该handler添加到HttpSecurity中:

http.authorizeRequests()
    .and()
    .rememberMe()
    .authenticationFailureHandler(new CookieTheftExceptionHandler());

如果我的回答解决了您的问题,请采纳我的回答