-1

I am working on csrf and using spring 5. Spring 5 automatically provide supports for csrf and on enabling csrf protection on the server side I am getting

403: Invalid X-CSRF token

So this means a token needs to come from frontend?

My understanding is that backend generates csrf token and sends as a response to frontend browser and then it uses this token and send it as cookies to the backend server and then backend will validate it. is my understanding is correct?

when manually generating the hidden token for csrf, How backend will know it is a valid csrf token?

Second Scenario: Suppose two users are logged in to my website and frontend is sending this token to backend then how the application will differentiate which token is for which user?

Also please explain how it works internally means we enabled csrf protection in the backend and manually generated a token on the front end then what it does behind the scenes?

consider my frontend is JS pages

Is there is any specialty of Spring 5 which take care's of sessions for each user and validate tokens automagically for each user?. I tried finding it on the official website but didn't get it anywhere

Ofir Lana
  • 383
  • 5
  • 13
zaib7777
  • 89
  • 3
  • 14

1 Answers1

0

Hi Zaib the csrf token is generated from back-end as you stated, once it is generated is automatically sent to the front-end which must take care to retrieve from the model and re-post for each "POST" requests. You can share the csrf token via different way mostly i used header or html parameter.

A token is related to a specific session so is not really important if you have a logged user or not , even not authenticated users must send the csrf token for "POST".

The csrf token is validated via a filter placed in the front of the filter chain defined by Spring security itself, if you search in the documentation there is a table showing you the position of each "default" filter enabled by Spring security. Moreover if you enable debug on Spring ( </debug> is enough in your xml configuration) you will have printed all the filters used while processing an http request. So each time a request with "POST" method pass through that filter , it will check if in the parameters there is the csrf token or header.

I never used as cookie so it may a different case for you if specifically need that but it does not differ on how it works.

Here is the details of csrf implementation on Spring: https://docs.spring.io/spring-security/site/docs/5.0.7.RELEASE/reference/htmlsingle/#csrf-configure

I said "POST" method but actually the token is checked for any method that is related to a change of state , you can refer to doc here: https://docs.spring.io/spring-security/site/docs/4.2.5.RELEASE/apidocs/org/springframework/security/web/csrf/CsrfFilter.html

Hope this help clarifying a bit the usage of the csrf token.

Stefano
  • 129
  • 2
  • 14