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);
    }

}

@@ -842,24 +842,234 @@
 (%22_csrf%22);%0A%0A
+        // Send a cookie only if the token have changed%0A        String oldToken = (String) httpServletRequest.getHeader(%22X-CSRF-TOKEN%22);%0A        if(oldToken == null %7C%7C !oldToken.equals(token.getToken())) %7B%0A    
         // S
@@ -1112,16 +1112,20 @@
 F token%0A
+    
         
@@ -1167,16 +1167,20 @@
         
+    
 Cookie c
@@ -1230,16 +1230,20 @@
 ken());%0A
+    
         
@@ -1264,32 +1264,36 @@
 ge(-1);%0A        
+    
 cookie.setHttpOn
@@ -1303,32 +1303,36 @@
 false);%0A        
+   
+ 
 cookie.setPath(%22
@@ -1333,24 +1333,28 @@
 Path(%22/%22);%0A%0A
+    
         http
@@ -1387,16 +1387,26 @@
 cookie);
+%0A        %7D
 %0A%0A      

send CSRF cookie on token change only