I am building an application that is integrated with a 3rd party service provider and uses OAuth 2 to obtain permission from other users using the service to access their account information. Based on the documentation, the implementation process is:
A user clicks a frontend element of my application, which makes a call to my backend.
Before my backend sends the link to the user to redirect him to the 3rd party application's authentication page, I need to create a cookie to store a randomly generated md5 string as "state" at my backend, and the "state" variable is included in the URL link.
After the user uses the link to log into his account and grant my application the permission, a response containing authorization code is sent to my backend.
My backend first checks whether the "state" in cookie matches the "state" in the response. If it does, then my backend will use the authorization code to make a call to the 3rd party's backend to obtain a token.
The documentation states that a "state" variable is needed to protect against cross-site request forgery (CSRF). However, I cannot think of a way how CSRF can happen during this process. CSRF means that a malicious hacker tricks an authenticated user to send an unintended request to the application backend, which is often done by injecting html and javascript into the application's web page. However, in the process mentioned above, after the user is authenticated by the 3rd party, he is completely in the realm of the 3rd party application, which can be assumed to be safe from the 3rd party's point of view. Even if a CSRF does occur, I do not understand how the "state" variable can detect and prevent this.
In short, my questions is: How can a CSRF take place in the process mentioned above and why using the "state" variable can prevent it?