简体   繁体   中英

Setting up CsrfPreventionFilter in Tomcat

I am attempting to set up the inbuilt CsrfPreventionFilter in Tomcat 8.

I think I have read all the questions and answers in StackOverflow on this subject, but I can still not solve my problem.

I have home.jsp and reports.jsp

The URL of home.jsp (once it has been subjected to response.encodeUrl() ) is www.example.com/home.jsp?org.apache.catalina.filters.CSRF_NONCE=5E4BD8FEE1B4CC1DA79D874905015911

This is rendered correctly, not because the nonce is working, but because I set home.jsp to be an EntryPoint. However it does seem to prove that the CSRFPreventionFilter is up and running and generating nonces successfully.

If I press CTRL+N and then type in www.example.com/reports.jsp and then I add the same nonce, ie www.example.com/reports.jsp?org.apache.catalina.filters.CSRF_NONCE=5E4BD8FEE1B4CC1DA79D874905015911 then I get page 403. reports.jsp is not set up as an EntryPoint, but I would expect it to render successfully, as it has been supplied with a nonce.

What am I doing wrong?

(My question is somewhat similar to Getting 403 error when using CSRF filter with tomcat 6.0.32 ; but I feel that the answer is probably not in the way the CSRFPrevention Filter is set up, but perhaps some issue in the way I am dealing with the response/request internally, akin to @Pankaj Kumar's answer in Not able to authenticate post request for CSRF token with tomcat )

UPDATE

Here is the web.xml configuration

<filter>
    <filter-name>CSRFPreventionFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CsrfPreventionFilter</filter-class>
        <init-param>
            <param-name>entryPoints</param-name>
            <param-value>/images/404.JPG,/login.jsp,/home.jsp,/images/im_login.gif,/js/events.js,/js/menu.js,/js/amount_validation.js,/js/calendar.js,/js/toolbar.js,/js/tablesort.js,/js/scripts.js,/css/style.css</param-value>
        </init-param>
</filter>

<filter-mapping>
    <filter-name>CSRFPreventionFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>  

You need to remove js, css and image paths from entryPoints and setup filter mapping for CsrfPreventionFilter in such a way that it does not include them.

The reason is that in tomcat the nonceCache has a size of 5 by default. In your case when js, css are requested, tomcat generates a new nonce (since they are in entryPoints) and adds it to cache, after 5 such requests your initial nonce (generated for home.jsp) is flushed out of nonceCache and is no longer valid. So you get a 403 when you send a legit request with that nonce.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM