package <%=packageName%>.web.filter;

import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * This filter is used to put the CSRF tocken generated by Spring in a cookie for use by Angular.
 * </p>
 */
public class CsrfTokenGeneratorFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // Spring put CSRF token in session attribut _csrf
        CsrfToken token = (CsrfToken) httpServletRequest.getAttribute("_csrf");

        // Session Cookie Based Approach for CSRF token
        String pCookieName = "CSRF-TOKEN";
        Cookie cookie = new Cookie(pCookieName, token.getToken());
        cookie.setMaxAge(-1);
        cookie.setHttpOnly(false);
        cookie.setPath("/");

        httpServletResponse.addCookie(cookie);

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

}

package <%=packageName%>.web.filter;

import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * This filter is used to put the CSRF tocken generated by Spring in a cookie for use by Angular.
 * </p>
 */
public class CsrfTokenGeneratorFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // Spring put CSRF token in session attribut _csrf
        CsrfToken token = (CsrfToken) httpServletRequest.getAttribute("_csrf");

        // Send a cookie only if the token have changed
        String oldToken = (String) httpServletRequest.getHeader("X-CSRF-TOKEN");
        if(oldToken == null || !oldToken.equals(token.getToken())) {
            // Session Cookie Based Approach for CSRF token
            String pCookieName = "CSRF-TOKEN";
            Cookie cookie = new Cookie(pCookieName, token.getToken());
            cookie.setMaxAge(-1);
            cookie.setHttpOnly(false);
            cookie.setPath("/");

            httpServletResponse.addCookie(cookie);
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

}

send CSRF cookie on token change only