Authorization Code Grant

class oauthlib.oauth2.AuthorizationCodeGrant(request_validator=None, **kwargs)[source]

Authorization Code Grant

The authorization code grant type is used to obtain both access tokens and refresh tokens and is optimized for confidential clients. Since this is a redirection-based flow, the client must be capable of interacting with the resource owner’s user-agent (typically a web browser) and capable of receiving incoming requests (via redirection) from the authorization server:

| Resource |
|   Owner  |
|          |
+----|-----+          Client Identifier      +---------------+
|         -+----(A)-- & Redirection URI ---->|               |
|  User-   |                                 | Authorization |
|  Agent  -+----(B)-- User authenticates --->|     Server    |
|          |                                 |               |
|         -+----(C)-- Authorization Code ---<|               |
+-|----|---+                                 +---------------+
  |    |                                         ^      v
 (A)  (C)                                        |      |
  |    |                                         |      |
  ^    v                                         |      |
+---------+                                      |      |
|         |>---(D)-- Authorization Code ---------'      |
|  Client |          & Redirection URI                  |
|         |                                             |
|         |<---(E)----- Access Token -------------------'
+---------+       (w/ Optional Refresh Token)

Note: The lines illustrating steps (A), (B), and (C) are broken into two parts as they pass through the user-agent.

Figure 3: Authorization Code Flow

The flow illustrated in Figure 3 includes the following steps:

  1. The client initiates the flow by directing the resource owner’s user-agent to the authorization endpoint. The client includes its client identifier, requested scope, local state, and a redirection URI to which the authorization server will send the user-agent back once access is granted (or denied).
  2. The authorization server authenticates the resource owner (via the user-agent) and establishes whether the resource owner grants or denies the client’s access request.
  3. Assuming the resource owner grants access, the authorization server redirects the user-agent back to the client using the redirection URI provided earlier (in the request or during client registration). The redirection URI includes an authorization code and any local state provided by the client earlier.
  4. The client requests an access token from the authorization server’s token endpoint by including the authorization code received in the previous step. When making the request, the client authenticates with the authorization server. The client includes the redirection URI used to obtain the authorization code for verification.
  5. The authorization server authenticates the client, validates the authorization code, and ensures that the redirection URI received matches the URI used to redirect the client in step (C). If valid, the authorization server responds back with an access token and, optionally, a refresh token.

Generates an authorization grant represented as a dictionary.

create_authorization_response(request, token_handler)[source]

The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI using the “application/x-www-form-urlencoded” format, per Appendix B:

REQUIRED. Value MUST be set to “code” for standard OAuth2 authorization flow. For OpenID Connect it must be one of “code token”, “code id_token”, or “code token id_token” - we essentially test that “code” appears in the response_type.
REQUIRED. The client identifier as described in Section 2.2.
OPTIONAL. As described in Section 3.1.2.
OPTIONAL. The scope of the access request as described by Section 3.3.
RECOMMENDED. An opaque value used by the client to maintain state between the request and callback. The authorization server includes this value when redirecting the user-agent back to the client. The parameter SHOULD be used for preventing cross-site request forgery as described in Section 10.12.

The client directs the resource owner to the constructed URI using an HTTP redirection response, or by other means available to it via the user-agent.

  • request – oauthlib.commong.Request
  • token_handler – A token handler instace, for example of type oauthlib.oauth2.BearerToken.

headers, body, status


FatalClientError on invalid redirect URI or client id. ValueError if scopes are not set on the request object.

A few examples:

>>> from your_validator import your_validator
>>> request = Request(''
...                   '&')
>>> from oauthlib.common import Request
>>> from oauthlib.oauth2 import AuthorizationCodeGrant, BearerToken
>>> token = BearerToken(your_validator)
>>> grant = AuthorizationCodeGrant(your_validator)
>>> grant.create_authorization_response(request, token)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "oauthlib/oauth2/rfc6749/", line 513, in create_authorization_response
        raise ValueError('Scopes must be set on post auth.')
ValueError: Scopes must be set on post auth.
>>> request.scopes = ['authorized', 'in', 'some', 'form']
>>> grant.create_authorization_response(request, token)
(u'', None, None, 400)
>>> request = Request(''
...                   '&'
...                   '&response_type=code')
>>> request.scopes = ['authorized', 'in', 'some', 'form']
>>> grant.create_authorization_response(request, token)
(u'', None, None, 200)
>>> # If the client id or redirect uri fails validation
>>> grant.create_authorization_response(request, token)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "oauthlib/oauth2/rfc6749/", line 515, in create_authorization_response
        >>> grant.create_authorization_response(request, token)
    File "oauthlib/oauth2/rfc6749/", line 591, in validate_authorization_request
create_token_response(request, token_handler)[source]

Validate the authorization code.

The client MUST NOT use the authorization code more than once. If an authorization code is used more than once, the authorization server MUST deny the request and SHOULD revoke (when possible) all tokens previously issued based on that authorization code. The authorization code is bound to the client identifier and redirection URI.

prepare_authorization_response(request, token, headers, body, status)

Place token according to response mode.

Base classes can define a default response mode for their authorization response by overriding the static default_response_mode member.


Check the authorization request for normal and fatal errors.

A normal error could be a missing response_type parameter or the client attempting to access scope it is not allowed to ask authorization for. Normal errors can safely be included in the redirection URI and sent back to the client.

Fatal errors occur when the client_id or redirect_uri is invalid or missing. These must be caught by the provider and handled, how this is done is outside of the scope of OAuthLib but showing an error page describing the issue is a good idea.