I have a REST API using Spring. I’ve created an Interceptor:
@Component
public class CSRFInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// code here
return true;
}
}
Every request made is using JSON with the following corresponding Java class:
public class CSRFTokenContainer<T> {
private T data;
private String csrf;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getCsrf() {
return csrf;
}
public void setCsrf(String csrf) {
this.csrf = csrf;
}
}
In my Controller it all works well using for example:
@Controller
@RequestMapping("/persons")
public class PersonController {
@RequestMapping(method=RequestMethod.POST)
public @ResponseBody String create(@RequestBody CSRFTokenContainer<Person> account, HttpServletResponse response) {
// do something
return "test";
}
}
Now I’d like to do the following: The Controller should just receive the Person object without the CSRF Token. The CSRF Token should get processed inside the Interceptor. How can I do this? I think the main problem is, that I don’t know how to get my CSRFTokenContainer object inside the Interceptor. Afterwards I’d like to modify the request to only contain the “data” part.
Some code example would be nice.
Thank you!
I’ve solved the CSRF problem this way:
I create the token on server side and place it inside the GWT host page via JSP. The token also gets stored in the Session:
myPage.jsp:
myTags.tld:
CSRFTokenTag:
GWT reads the token via JSNI:
And with every request the web application sends the token inside a custom HTTP header, for example like this:
Within Spring I’ve created an Interceptor, that for every request reads the token from the submitted header and checks it:
It’s maybe not perfect, but it seems to work pretty well!