Reputation: 1937
Having the XSRF-TOKEN
cookie set with HttpOnly creates problem for Angular Framework in picking it up from the document.cookie
function.
Is there any way around this? I cannot make the XSRF-TOKEN
non HttpOnly
I thought that perhaps I can intercept every incoming request in Middle Tier (Spring Boot), check through the cookies and if it is a POST/PUT/DELETE request and it has XSRF-TOKEN
, I shall add the X-XSRF-TOKEN
header ?
Upvotes: 1
Views: 3006
Reputation: 688
AngularJS accesses the cookies in a manner such as 'document.cookies...' i.e. via javascript itself, and in this case HttpOnly just won't work. You should regardless translate Spring cookies to something that angular expects and understands ('XSRF-TOKEN'). This can be done in a filter like this:
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.setSecure(true);
cookie.setPath(request.getContextPath() + "/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
}
Upvotes: 0