I confuse session id and CSRF token. so I search about that and understand a little bit. Session IDs are used to verify a user. CSRF tokens are used to verify request itself. My question is when server send CSRF token to user?
For example when client visit www.sample.com first time, sever send session id to client.(is that right?) client want to change his password. so he come to www.sample.com/change where client can change password and is located change button(post). And that time(when client visit www.sample.com/change) sever send CSRF token to client? or when client post their data then middleware send CSRF and compare before server got post data?
CodePudding user response:
The server sends the CSRF token when the client visit the www.sample.com/change
page. Usually, the CSRF token is embedded in the HTML file as a hidden html element such as <meta>
tag or hidden <input>
tag. Therefore, when the client sends a GET request to retrieve the www.sample.com/change
page, the CSRF token will be returned as part of the HTML page.
Resources:
Additional Consideration
Let's say we take the "middleware" approach described in your question. In that case, the CSRF token will be generated in the server upon receiving a POST/PUT request. Then, the server cannot discern whether the request is generated by the legitimate site (www.sample.com
) or the impersonating site (www.malicious.com
) because both requests can look exactly the same (note here that the malicious site can spoof request headers such as origin
). Therefore this approach cannot prevent CSRF attack. The CSRF token needs to be sent from the client so that the server can identify the requests originating from the legitimate website.