Renaming Spring csrf Variable

My application runs under another portal application. Both are implemented in spring, and both use csrf protection.

My need is mainly to change the name of the csrf token in the session, so both tokens can work without conflict. So far, I have been trying to create another token repository and try to change the parameter name and session attribute name in the security configuration class.

final HttpSessionCsrfTokenRepository tokenRepository = new HttpSessionCsrfTokenRepository();
tokenRepository.setHeaderName("TOOLBIZ-CSRF-TOKEN");
tokenRepository.setParameterName("toolbiz_csfr");
//tokenRepository.setSessionAttributeName("toolbiz_csrf");

When I make a spring request, I don’t really like this new setting, and the log prints the following line:

Invalid CSRF token found

What should I do next? Did I miss something?

+1
source share
2 answers

This is what worked for me: -

@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class OptosoftWebfrontSecurity extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/assets/**").permitAll()
            .anyRequest().authenticated().and().formLogin().and()
            .httpBasic().disable()
            .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
            .csrf().csrfTokenRepository(csrfTokenRepository());
}

private CsrfTokenRepository csrfTokenRepository() {
    HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
    repository.setHeaderName("X-XSRF-TOKEN");
    repository.setParameterName("_csrf");
    return repository;
}

}

And filter: -

public class CsrfHeaderFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request,
            HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
                .getName());
        if (csrf != null) {
            Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
            String token = csrf.getToken();
            if (cookie == null || token != null
                    && !token.equals(cookie.getValue())) {
                cookie = new Cookie("XSRF-TOKEN", token);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        filterChain.doFilter(request, response);
    }
}

Have you redefined the WebSecurityConfigurerAdapter # configuration method?

+1

cookie, , . , , .

0

All Articles