'Discord OAuth2: State parameter best practice

Looking at the Discord OAuth2 API, and frankly this is probably similar in other API's, they want a state parameter that is a unique nonce to avoid clickjacking.

What is the best or standard practice for this value?

Should it be...

  1. Bcrypt hashing the id of the user in the database?
  2. Generating a uuidv4 nonce, saving it in the database and retrieving it on the callback?
  3. Creating a JWT with the user id and signing it?

Also, in what way does having a nonce passed to the authorization page, and giving it back in the callback help avoid cross-site request forgery(CSRF) and clickjacking?

Before we dive into the semantics of the different OAuth2 grants, we should stop and discuss security, specifically the use of the state parameter. Cross-site request forgery, or CSRF, and Clickjacking are security vulnerabilities that must be addressed by individuals implementing OAuth. This is typically accomplished using the state parameter. state is sent in the authorization request and returned back in the response and should be a value that binds the user's request to their authenticated state. For example, state could be a hash of the user's session cookie, or some other nonce that can be linked to the user's session.

When a user begins an authorization flow on the client, a state is generated that is unique to that user's request. This value is stored somewhere only accessible to the client and the user, i.e. protected by the same-origin policy. When the user is redirected, the state parameter is returned. The client validates the request by checking that the state returned matches the stored value. If they match, it is a valid authorization request. If they do not match, it's possible that someone intercepted the request or otherwise falsely authorized themselves to another user's resources, and the request should be denied.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source