Sunday, December 3, 2017

HTTP Status 403 - Invalid CSRF Token 'xxx' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

XSRF is a technique by which an unauthorized site can gain your user's private data. Angular provides a mechanism to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie (by default, XSRF-TOKEN) and sets it as an HTTP header (X-XSRF-TOKEN).
If you set appropriate cookie, then it ensures that angular will take care of the header internally
So on that case, you need to check that server config won't need a new token each request
You need to send the csrf token when you submit your form. You need to add the following line in your HTML form:
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
Resource Link:
  1. Spring Rest Service - Invalid CSRF token when I attempt to login
As CodeMed suggested to add
.antMatchers("/send-pin").permitAll()
in SecurityConfiguration class. He got some issue as stated below:
To examine the Network tab of the Firefox debug tools, which showed that the following two cookies were sent with the request: JSESSIONID:"99192501E7CEA0EDEF853BD666AF3C35" and XSRF-TOKEN:"b50afb87-e15c-4bef-93ca-7c2fdf145fd8", even though the server log for the same request still boiled down to Invalid CSRF token found for http://localhost:9000/send-pin . This caused me to examine why the sent token was being rejected, and a few minutes later I noticed the missing antmatchers(...) for the url pattern, leading to this answer.
This change caused SecurityConfiguration.configure(...) method to now look like:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests()
        .antMatchers("/send-pin").permitAll() 
        .antMatchers("/check-pin").permitAll()
        .antMatchers("/index.html", "/", "/login", "/someotherrurl") 
        .permitAll().anyRequest().authenticated().and().csrf()
        .csrfTokenRepository(csrfTokenRepository()).and()
        .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
}  

Resource Link:

  1. How do I send CSRF tokens from AngularJS front end to Spring REST service backend?
  2. Spring Security - Token based API auth & user/password authentication

No comments:

Post a Comment