In this blog, We will see how to configure CSRF protection and how to make AngularJS allowed to send information with a CSRF token to the server.
In AngularJS, $http service reads a token from a cookie which is named by default
XSRF-TOKEN and sets it in HTTP header with name
X-XSRF-TOKEN. Once it is configured, now spring running on server is supposed to insert token in cookie inside HTTP header. Now server can verify that the cookie matches X-XSRF-TOKEN HTTP header.
Let's see how it can be configured with Spring.
Step 1. Configure and enable CSRF.
Spring security comes with CSRF protection enabled. Please have a look of my previous
blog.
Step 2. Configure Cookie in HTTP Header to enable CSRF for AngularJS
Here is the code below in your security configuration -
http.csrf()
.csrfTokenRepository(csrfTokenRepository())
.and().addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class);
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
Here in the second section of code, I have defined the CSRF token repository to just defined the header name which is set to the CSRF configuration.
Here the point to notice - Class CsrfHeaderFilter. Here is the code for the class.
package com.multipli.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.WebUtils;
public class CsrfHeaderFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) httpServletRequest.getAttribute(CsrfToken.class.getName());
if(csrf != null) {
Cookie cookie = WebUtils.getCookie(httpServletRequest, "XSRF-TOKEN");
String token = csrf.getToken();
if(cookie == null || (token != null && !token.equals(cookie.getValue()))) {
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
httpServletResponse.addCookie(cookie);
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
In the code above, the class extends OncePerRequestFilter . As name suggests, Filter applied just once for very first HTTP request. It creates the cookie with token for AngularJS.
Hope this would help you.
That's it.
Thanks. Happy coding.
0 Comment(s)