18.5.1 Timeouts

One issue is that the expected CSRF token is stored in the HttpSession, so as soon as the HttpSession expires your configured AccessDeniedHandler will receive a InvalidCsrfTokenException. If you are using the default AccessDeniedHandler, the browser will get an HTTP 403 and display a poor error message.

One might ask why the expected CsrfToken isn’t stored in a cookie by default. This is because there are known exploits in which headers (i.e. specify the cookies) can be set by another domain. This is the same reason Ruby on Rails no longer skips CSRF checks when the header X-Requested-With is present. See this webappsec.org thread for details on how to perform the exploit. Another disadvantage is that by removing the state (i.e. the timeout) you lose the ability to forcibly terminate the token if it is compromised.

A simple way to mitigate an active user experiencing a timeout is to have some JavaScript that lets the user know their session is about to expire. The user can click a button to continue and refresh the session.

Alternatively, specifying a custom AccessDeniedHandler allows you to process the InvalidCsrfTokenException any way you like. For an example of how to customize the AccessDeniedHandler refer to the provided links for both xml and Java configuration.

Finally, the application can be configured to use CookieCsrfTokenRepository which will not expire. As previously mentioned, this is not as secure as using a session, but in many cases can be good enough.

https://docs.spring.io/spring-security/site/docs/4.2.3.RELEASE/reference/htmlsingle/#csrf-timeouts

What is the best way to handle Invalid CSRF token found in the request when session times out in Spring security

The easiest way I found to handle invalidate CSRF token when session times out at the login page is one of the followings:

  1. Redirect the request again to the login page again vi CustomAccessDeniedHandler:

    static class CustomAccessDeniedHandler extends AccessDeniedHandlerImpl{
    
        @Override
    public void handle(HttpServletRequest request,
    HttpServletResponse response, AccessDeniedException accessDeniedException)
    throws IOException, ServletException {
    if (accessDeniedException instanceof MissingCsrfTokenException
    || accessDeniedException instanceof InvalidCsrfTokenException) { if(request.getRequestURI().contains("login")){
    response.sendRedirect(request.getContextPath()+"/login");
    }
    } super.handle(request, response, accessDeniedException); }
    }
  2. Add refresh header as Neil McGuigan suggested:

<meta http-equiv="refresh" content="${pageContext.session.maxInactiveInterval}">

  1. Furthermore you must create a bean for the new CustomAccessDeniedHandler and register it. The following example shows this for Java config.

In any config class:

@Bean
public AccessDeniedHandler accessDeniedHandler() {
return new CustomAccessDeniedHandler();
}

In your security config modify the configure method as follows:

@Override
protected void configure(final HttpSecurity http) throws Exception {
http
// ...
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
}

Also see here.

a more Optimum solution will be for Spring security to handle this situation in their framework.

https://stackoverflow.com/questions/32446903/what-is-the-best-way-to-handle-invalid-csrf-token-found-in-the-request-when-sess

未找到预期的CSRF令牌。您的会话已过期403
https://gxnotes.com/article/245164.html

Spring Security – Customize the 403 Forbidden/Access Denied Page
http://www.baeldung.com/spring-security-custom-access-denied-page

What is the best way to handle Invalid CSRF token found in the request when session times out in Spring security的更多相关文章

  1. Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

    Spring Security :HTTP Status 403-Invalid CSRF Token 'null' was found on the request parameter '_csrf ...

  2. Spring Security Oauth2 使用 token 访问资源服务器出现异常:Invalid token does not contain resource id (oauth2)

    异常如图 查看资源服务器的日志 p.a.OAuth2AuthenticationProcessingFilter : Authentication request failed: error=&quo ...

  3. Cross Site Request Forgery (CSRF)--spring security -转

    http://docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/csrf.html 13. Cross ...

  4. Java 安全之:csrf防护实战分析

    上文总结了csrf攻击以及一些常用的防护方式,csrf全称Cross-site request forgery(跨站请求伪造),是一类利用信任用户已经获取的注册凭证,绕过后台用户验证,向被攻击网站发送 ...

  5. CSRF 详解:攻击,防御,Spring Security应用等

    本文原创,更多内容可以参考: Java 全栈知识体系.如需转载请说明原处. CSRF(Cross-site request forgery跨站请求伪造,也被称成为"one click att ...

  6. SpringSecurity基本使用

    SpringSecurity web 安全管理框架 需要依赖多 shiro 轻量 SSM+Shiro SpringBoot/SpringCloud+SpringSecurity 配置用户名密码 配置文 ...

  7. 执行CSRF令牌所有形式使用POST方法

    从而在并未授权的情况下执行在权限保护之下的操作,有很大的危害性. php CSRF Guardfunction csrfguard_generate_token($unique_form_name){ ...

  8. Spring Security4.1.3实现拦截登录后向登录页面跳转方式(redirect或forward)返回被拦截界面

    一.看下内部原理 简化后的认证过程分为7步: 用户访问网站,打开了一个链接(origin url). 请求发送给服务器,服务器判断用户请求了受保护的资源. 由于用户没有登录,服务器重定向到登录页面 填 ...

  9. Spring Security(三十六):12. Spring MVC Test Integration

    Spring Security provides comprehensive integration with Spring MVC Test Spring Security提供与Spring MVC ...

随机推荐

  1. OpenCV 求外接矩形以及旋转角度

    程序没有写完整,大概功能就是实现了,希望大家分享学习,把他改对 // FindRotation-angle.cpp : 定义控制台应用程序的入口点. // // findContours.cpp : ...

  2. Leetcode_217_Contains Duplicate

    本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/46271159 Given an array of inte ...

  3. ListView 与ContextMenu的关联管理

    <span style="font-family: Arial, Helvetica, sans-serif;">package com.example.listvie ...

  4. shell脚本里面相互调用时路径不要用pwd获取

    shellA调用shellB,如果shellB 里面需要使用路径作为变量,去寻找其它文件.那么要注意,不用pwd,其返回的是系统中用户当前所在位置的路径,也就是shellA的路径,这样就错了.应该用d ...

  5. $("li")是对象类型不是数组类型

  6. 代码托管工具 git

    p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px "Helvetica Neue"; color: #454545 } p. ...

  7. css区分ie8/ie9/ie10/ie11 chrome firefox的代码

    以下是几个主要浏览器的css  hack汇总: 现有css样式为: .class{ color:red; } 判断IE8以上的浏览器才执行的代码/* IE8+ */ .class{ color:red ...

  8. TopShelf安装多实例

    Topshelf 安装多实例命令: .\ConsoleApp1.exe -instance "newinstallname" install 多实例有一个好处就是容灾,当一个服务部 ...

  9. 多重影分身——C#中多线程的使用三(调用方法和传参)

    对Thread: 1.使用ThreadStart static void Main(string[] args) { Thread th1=new Thread(new ThreadStart(Say ...

  10. BugFix:URL or HTTP headers are too long (IP=127.0.0.1)

    错误提示: URL or HTTP headers are too long (IP=127.0.0.1) com.caucho.server.dispatch.BadRequestException ...