Kalyan Pradhan Kalyan Pradhan - 1 year ago 142
Java Question

Can we specify the CSRF token expiry timeout?

I am using spring security and Java configurations in my project.

The Java configurations for spring security by default have csrf enabled.

Is it possible to set the timeout after which the csrf token expires? This was a requirement to specify the timeout for the token based application.

After going through some blogs and articles I noticed that the behaviour of csrf token is unpredictable to make it more secured.

Here is a sample code for configuring spring security.

protected void configure(HttpSecurity http) throws Exception {

If there is some way by which I can set up the timeout that would save me a lot of work.

I would really appreciate your help and Thanks in advance.

dur dur
Answer Source

See Spring Security Reference:

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.

That means, you could change the session timeout in your web.xml to expire the CSRF token, see for example WebLogic:

<session-timeout> | optional | The number of minutes after which sessions in this Web application expire

Another way is to write your own CsrfTokenRepository:

An API to allow changing the method in which the expected CsrfToken is associated to the HttpServletRequest. For example, it may be stored in HttpSession.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download