The authorization code flow is the most common way to use OAuth2, and is the one most users are familiar with. If you’ve ever logged into an application by typing your Google credentials into a Google form, then you’ve used this flow.
There are two important things to understand about this grant type.
Given this, applications that don’t use a client-server architecture (i.e., simple mobile apps) or applications that aren’t web-based (i.e., server applications) should use another grant type such as client credentials or user credentials.
The authorization code flow is a three-legged protocol. That means broadly there are three steps:
The first step is for the client to request an authorization code from the OAuth provider. To start the process, the client must redirect the user to the OAuth provider login page.
Here’s some example Javascript to redirect the user to the login page.
var payload = { 'scope' : 'profile-read, profile-write',
'state' : 'some_random_string',
'redirect_uri' : OAUTH_REDIRECT,
'response_type' : 'code',
'client_id' : CLIENT_ID,
'access_type' : 'offline'};
res.redirect("192.168.56.110:8080/auth" + '?' + qs.stringify(payload));
Let’s go over each of the parameters.
foo Comma-delimited set of strings Indicates which scopes the application needs to use. Since client applications already define the set of scopes they use, this parameter is optional and should consist of a subset of the client application scopes.
After specifying these parameters, we just need to redirect the user to login portal. You’ll want to replace “192.168.56.110” with the IP address of your provider (or if you’re using some social media provider, use the appropriate authorization URL).
Once the user has authenticated, the client application will receive a response from the OAuth provider at the specified redirect uri. A successful response will contain a code parameter and the state parameter. Finally, give the authorization code, we can finally post a request to the token endpoint to retrieve an access token.
request.post({
url: '192.168.56.110:8080/token',
qs: { 'code' : auth_code,
'client_id' : CLIENT_ID,
'client_secret' : CLIENT_SECRET,
'grant_type' : 'authorization_code',
'redirect_uri' : OAUTH_REDIRECT}});
If successful, the response will be a JSON object:
{
"access_token": "axb2y-...",
"refresh_token": "rya9z-...",
"expires_in":3600,
"token_type":"Bearer"
}
Every access token will eventually expire (ours will expire in 3600 seconds), at which time the access token will no longer work. Also, note that while OAuth supports different “types” of access tokens, the most common one (and the only one that Oauth.Us supports) is the “Bearer” type.
In the case of an error, you will receive a JSON object with a status code 400 (or above) with the following structure:
{
"error": "invalid_access_token",
"error_description": "Invalid access token"
}