HTTP Status 403 - Invalid CSRF Token '9ee6949c-c5dc-4d4b-9d55-46b75abc2994' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

冷暖自知 提交于 2019-12-07 00:27:27
SkyWalker

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

For those who are facing the same problem. Here is my solution.

  1. First I wasn't able to get the cookie using $cookies.get(). It's because that the cookie that I was returning from the backend didn't had a path configured.
  2. After the authentication where I get a token I make many other http requests and I was discarding the tokens returned by these requests. So, when Spring Security compared the tokens It used the authentication token which was invalid and not the token from the last request.

Hope this help someone.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!