How to properly pass the csrf token to the frontend?

I'm planning to migrate my project from thymeleaf to React.js. The problem is that most pages require authentication to access -> need to make a post request to log in -> need to have a csrf token. According to most of the instructions I've found on this topic, I've set CookieCsrfTokenRepositoty.withHttpOnlyFalse() in SecurityConfiguration. When a post request is sent, the js retrieves the csrf token from the cookie, which is initially empty. When the post request reaches the server, the frontend receives the csrf token and stores it in the cookie. However, this is no longer useful, as tokens are generated for each new request. As a result, I have an infinite Invalid CSRF token. When I disable csrf protection, everything works as expected
10 Replies
JavaBot
JavaBot5mo ago
This post has been reserved for your question.
Hey @JVyacheslav! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
dan1st
dan1st5mo ago
Just don't create a new token every time/reuse it? or ensure that the cookie value is the same as the token value as the check
JVyacheslav
JVyacheslavOP5mo ago
Was it possible??????
dan1st
dan1st5mo ago
?
JVyacheslav
JVyacheslavOP5mo ago
I mean, how can I avoid recreating the token?
dan1st
dan1st5mo ago
store it with the session?
Zer00tje
Zer00tje5mo ago
no, normally you should create a new token every time (otherwise it kinda defeats the purpose of csrf protection). what I usually do is to have a single "GET user info" endpoint and make sure the csrf is present there. that will be your initial token and prevent the whole cycle. essentially you have to follow this part of the documentation: https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html#csrf-integration-javascript-spa normally if you implement that SpaCsrfTokenRequestHandler, it will no longer defer the csrf token generation you can finetune when the csrfToken.get() happens to only happen for certain requests, or leave it as is. it's important that you do an initial GET-call somewhere in your react app to obtain the first csrf token though (could be part of your authentication flow, if you have any)
JVyacheslav
JVyacheslavOP5mo ago
Thank you, you helped a lot
JavaBot
JavaBot5mo ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
JavaBot
JavaBot5mo ago
Post Closed
This post has been closed by <@917367712525742090>.

Did you find this page helpful?