Can we specify the CSRF token expiry timeout?

梦想的初衷 提交于 2020-12-12 07:59:43

问题


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 behavior of csrf token is unpredictable to make it more secured.

Here is a sample code for configuring spring security.

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().maximumSessions(1).expiredUrl("/login-expired.html").and().and()
                .authorizeRequests().antMatchers("/superadmin/**").access("hasRole('ROLE_SUPER_ADMIN')").and()
                .formLogin().loginPage("/signin.html").permitAll().failureUrl("/login-failed.html").permitAll()
                .and().exceptionHandling().accessDeniedPage("/403").and().logout().permitAll().and()
                .exceptionHandling().and().logout().logoutSuccessUrl("/logout.html").permitAll().and()
    }

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


回答1:


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.



来源:https://stackoverflow.com/questions/39754419/can-we-specify-the-csrf-token-expiry-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!