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

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

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

时间: 2024-10-14 20:27:30

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

Invalid CSRF Token &#39;null&#39; was found on the request parameter &#39;_csrf&#39; or header &#39;X-CSRF-TOKEN&#39;

Spring Security :HTTP Status 403-Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'. 原因:1.Spring Security 4.0之后,引入了CSRF,默认是开启.CSRF默认支持的方法: GET|HEAD|TRACE|OPTIONS,不支持POST. Spring Security 3默认关闭csrf,Spring Sec

structs2源码分析

一.到网上下载struts2的源代码: http://mirrors.cnnic.cn/apache//struts/source/struts-2.3.16.3-src.zip 我把项目的源码路径定向到下载到的源代码: 这份是webwork的核心源码,读取配置文件的核心代码就在于此: 二.下面是struts本尊,基本实现的就是请求的分发: 二.从项目本身去做分析: 好多大牛大师傅都不断强调,去看源码分析源码,但是却从来很少人,告诉你怎么去看,经过多年的摸索我总算找到一个分析源代码的套路,特别对

SpringSecurity的防Csrf攻击

CSRF(Cross-site request forgery)跨站请求伪造,也被称为One Click Attack或者Session Riding,通常缩写为CSRF或XSRF,是一种对网站的恶意利用.尽管听起来像跨站脚本(XSS),但它与XSS非常不同,XSS利用站点内的信任用户,而CSRF则通过伪装成受信任用户的请求来利用受信任的网站.与XSS攻击相比,CSRF攻击往往不大流行(因此对其进行防范的资源也相当稀少)和难以防范,所以被认为比XSS更具危险性. CSRF是一种依赖web浏览器的

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

一.看下内部原理 简化后的认证过程分为7步: 用户访问网站,打开了一个链接(origin url). 请求发送给服务器,服务器判断用户请求了受保护的资源. 由于用户没有登录,服务器重定向到登录页面 填写表单,点击登录 浏览器将用户名密码以表单形式发送给服务器 服务器验证用户名密码.成功,进入到下一步.否则要求用户重新认证(第三步) 服务器对用户拥有的权限(角色)判定: 有权限,重定向到origin url; 权限不足,返回状态码403("forbidden"). 从第3步,我们可以知道

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

从而在并未授权的情况下执行在权限保护之下的操作,有很大的危害性. php CSRF Guardfunction csrfguard_generate_token($unique_form_name){if (function_exists("hash_algos") and in_array("sha512",hash_algos())){$token=hash("sha512",mt_rand(0,mt_getrandmax()));}else

LDAP启动cacao提示Invalid file permission

问题处理步骤: 1.LDAP实例停止 2.DSCC控制台启动,提示cacao已停止…… 3.启动caocao[email protected] bin]# ./cacaoadm startInvalid file permission: [/home/ldap/dsee6/cacao_2/etc/opt/sun/cacao/instances/default/security] [rwxrwxr-x]. Problem validating security keys. Please regen

IIS问题解决:URL中制表符引起的Bad Request - Invalid URL

昨天处理好了Google网站管理员中的500错误,今天处理了一些400处理,比如下面的以制表符(tab)结尾的URL: http://www.cnblogs.com/me-sa/archive/2008/05/16/1200329.html%09 http://www.cnblogs.com/JimmyZhang/archive/2007/12/20/1006555.html%09 ... 访问这些URL时,IIS会返回400 bad request的错误: Bad Request - Inva

IT忍者神龟之com.octo.captcha.service.CaptchaServiceException: Invalid ID, could not validate unexisting o

<p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;">先说明错误原因:用spring安全拦截器进行验证码的验证的时候抛出异常.</p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;">thr

ThoughtWorks笔试题之Merchant&#39;s Guide To The Galaxy解析

一.背景 在某网站上看到ThoughtWorks在武汉招人,待遇在本地还算不错,就投递了简历.第二天HR就打开电话,基本了解了一下情况(工作环境不错,男人妹子比例:1:1,双休,六险一金,满一年年假15天,病假8天,月薪1W--2W).然后立马收到一封:Coding Assignment的笔试题目.网上搜索了一下,发现这个公司还是挺大的,公司面试流程是出了名的繁杂和苛刻.据说有8轮:电话面试=>笔试=>Homework=>结对编程(中午管饭)=>技术面试=>PM面试=>