简体   繁体   中英

CSRF token per request in spring security

How to implement csrf per request in spring security 3.2.Currently it is handled per session .This is a must requirement

Please post the changes that needs to be performed.

in securitycontext.xml

  <http>
    <csrf />
    </http>

is given and application is working with token per session

You can change the default implementation of CsrfTokenRepository by providing your own implementation of this interface and configure it like:

<http>
    <csrf token-repository-ref="myRequestCsrfTokenRepository"/>
</http>
<b:bean id="myRequestCsrfTokenRepository"
        class="com.company.security.RequestCsrfTokenRepository"/>

But... although you wrote that this is a must requirement, you should really rethink it again. I would even advice to try convincing the other end that this change could bring more security to the app users but can also bring a lot of inconveniences, sometimes strange behaviors and in general decrease the usability and user experience. Eg see Different csrf token per request in Spring security

I have implemented a custom csrf token repository which generates a new token for every http POST/DELETE req. I don't think token should be renewed for http GET, and if you look into source code of spring CsrfFilter class, it has a inner class DefaultRequiresCsrfFilter, which pass token checking for GET method.

The custom csrf token repository needs to implement interface CsrfTokenRepository. Actually I have reuse most of code of HttpSessionCsrfTokenRepository, which is spring default. The function that needs custom implementation is loadToken()

/*Customized loading token function, which invalidate the CSRF token once it is consumed. A new token is generated on next http req.*/

    public CsrfToken loadToken(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        CsrfToken token = session == null ? null : (CsrfToken)session.getAttribute(this.sessionAttributeName);
        if (/*HERE http request can be checked to see if it is a POST/DELETE */) {
            if (session != null) {
                //Remove the old token from session, and new token will be generated for next req 
                session.removeAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME);
            }
        }
        return token;
    }

And to get custom csrf token repository loaded, it needs to be configured in security.xml, as described in answers above.

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