OAuth 2 Grant Type Authorization Code

OAuth 2 Grant Type Authorization Code Link

The authorization code grant type is the most commonly used because it is optimized for server-side applications, where source code is not publicly exposed, and Client Secret confidentiality can be maintained.

This is a redirection-based flow, which means that the application must be capable of interacting with the user-agent (i.e. the user’s web browser) and receiving API authorization codes that are routed through the user-agent.

Workflow

  1. The client application needs to first register with the authorization service
  2. The user is presented with an authorization code link in the app website, usually in the login page. When the user clicks the link, he will be redirected to the authorization service website.
  3. In the authorization service website, the user must first log in to authenticate their identity (unless they are already logged in). Then he will be prompted by the service to authorize or deny the application access to their account.
  4. If the user clicks “Authorize Application”, the service redirects the user-agent to the application redirect URI, which was specified during the client registration, along with an authorization code. The redirect link would look something like this (assuming the application is ”dropletbook.com“)
https://dropletbook.com/callback?code=AUTHORIZATION_CODE
  1. The application responds by passing the authorization code along with authentication details, including the client secret, to the authorization service API token endpoint. Here is an example POST request to DigitalOcean’s token endpoint
https://cloud.digitalocean.com/v1/oauth/token?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&grant_type=authorization_code&code=AUTHORIZATION_CODE&redirect_uri=CALLBACK_URL
  1. If the authorization is valid, the authorization service API will send a response containing the access token (and optionally, a refresh token) to the application. The entire response will look something like this:
{
  "access_token":"ACCESS_TOKEN",
  "token_type":"bearer",
  "expires_in":2592000,
  "refresh_token":"REFRESH_TOKEN",
  "scope":"read",
  "uid":100101,
  "info":{
    "name":"Mark E. Mark",
    "email":"mark@thefunkybunch.com"
  }
}

Now the application is authorized! It may use the token to access the user’s account via the service API, limited to the scope of access, until the token expires or is revoked. If a refresh token was issued, it may be used to request new access tokens if the original token has expired.

Reference

OAuth 2.0: In the authorization code flow, who eventually hands the access token to my web browser? - Stack Overflow