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.
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?