Angular 2/Spring Security CSRF implementation problems

后端 未结 1 1791
半阙折子戏
半阙折子戏 2021-01-20 17:40

I\'m trying to build an Angular 2 page on top of a Spring Boot API. I have configured CORS (correctly I believe), but I am getting blocked by Spring Security\'s CSRF protect

相关标签:
1条回答
  • 2021-01-20 18:02

    I know it's late but, I ran into same problem and managed to solve it. Problem in angular http request:

    return this.http.post(tokenUrl, JSON.stringify(model), {headers: headers1});
    

    You need to adjust it to send like that :

    return this.http.post(tokenUrl, JSON.stringify(model), {headers: headers1, withCredentials: true});
    

    You have to add withCredentials: true to all your http requests. Why you need it? Each time you send http request(OPTIONS, POST etc) to Spring(server) it will generate new XSRF-TOKEN and issue it to client, withCredentials: true will save this new XSRF-TOKEN in browser and later on used for new http request, so in case one of your http requests doesn't have withCredentials: true it will simply ignore new XSRF-TOKEN and use old(expired) XSRF-TOKEN for http request.

    0 讨论(0)
提交回复
热议问题