Authorization

Authorizer

The authorizer grants access tokens and authentication codes via query string parameters and URI fragments sent to redirect URIs. Optionally a “scope” kwarg of one or more AccessRange objects can be passed to verify that granted tokens can only be used to access specific scopes.

In the event of an error the Authorizer:error_response() method will return a redirect response to the client’s redirect_uri with information on the error passed as query string parameters.

If a request is authorized, Authorizer:grant_response() will serialize an object into a JSON response will return a redirect response to the client’s redirect_uri with information on the authorization code passed as query string parameters (response_type CODE) or access token passed as URI fragments.

from oauth2app.authorize import Authorizer, MissingRedirectURI, AuthorizationException
from oauth2app.models import AccessRange

@login_required
def authorize(request):
    scope = AccessRange.objects.get(key="last_login")
    authorizer = Authorizer(scope=scope)
    try:
        # Validate the request.
        authorizer.validate(request)
    except MissingRedirectURI, e:
        # No redirect_uri was specified.
        return HttpResponseRedirect("/oauth2/missing_redirect_uri")
    except AuthorizationException, e:
        # The request is malformed or invalid. Redirect to redirect_uri with error params.
        return authorizer.error_redirect()
    if request.method == 'GET':
        template = {}
        # Use any form, make sure it has CSRF protections.
        template["form"] = AuthorizeForm()
        # Appends the original OAuth2 parameters.
        template["form_action"] = '/oauth2/authorize?%s' % authorizer.query_string
        return render_to_response(
            'oauth2/authorize.html',
            template,
            RequestContext(request))
    elif request.method == 'POST':
        form = AuthorizeForm(request.POST)
        if form.is_valid():
            if request.POST.get("connect") == "Yes":
                # User agrees. Redirect to redirect_uri with success params.
                return authorizer.grant_redirect()
            else:
                # User refuses. Redirect to redirect_uri with error params.
                return authorizer.error_redirect()
    return HttpResponseRedirect("/")

Module Reference

OAuth 2.0 Authorization

exception oauth2app.authorize.AccessDenied[source]

The resource owner or authorization server denied the request.

exception oauth2app.authorize.AuthorizationException[source]

Authorization exception base class.

class oauth2app.authorize.Authorizer(scope=None, authentication_method=1, refreshable=True, response_type=2)[source]

Access authorizer. Validates access credentials and generates a response with an authorization code passed as a parameter to the redirect URI, an access token passed as a URI fragment to the redirect URI, or both.

Kwargs:

  • scope: An iterable of oauth2app.models.AccessRange objects representing the scope the authorizer can grant. Default None
  • authentication_method: Type of token to generate. Possible values are: oauth2app.consts.MAC and oauth2app.consts.BEARER Default oauth2app.consts.BEARER
  • refreshable: Boolean value indicating whether issued tokens are refreshable. Default True
error_redirect()[source]

In the event of an error, return a Django HttpResponseRedirect with the appropriate error parameters.

Raises MissingRedirectURI if no redirect_uri is available.

Returns HttpResponseRedirect

grant_redirect()[source]

On successful authorization of the request, return a Django HttpResponseRedirect with the appropriate authorization code parameters or access token URI fragments..

Raises UnvalidatedRequest if the request has not been validated.

Returns HttpResponseRedirect

query_string

Returns the a url encoded query string useful for resending request parameters when a user authorizes the request via a form POST.

Raises UnvalidatedRequest if the request has not been validated.

Returns str

validate(request)[source]

Validate the request. Raises an AuthorizationException if the request fails authorization, or a MissingRedirectURI if no redirect_uri is available.

Args:

  • request: Django HttpRequest object.

Returns None

exception oauth2app.authorize.InvalidClient[source]

Client authentication failed (e.g. unknown client, no client credentials included, multiple client credentials included, or unsupported credentials type).

exception oauth2app.authorize.InvalidRequest[source]

The request is missing a required parameter, includes an unsupported parameter or parameter value, or is otherwise malformed.

exception oauth2app.authorize.InvalidScope[source]

The requested scope is invalid, unknown, or malformed.

exception oauth2app.authorize.MissingRedirectURI[source]

Neither the request nor the client specify a redirect_url.

exception oauth2app.authorize.UnauthenticatedUser[source]

The provided user is not internally authenticated, via user.is_authenticated()

exception oauth2app.authorize.UnauthorizedClient[source]

The client is not authorized to request an authorization code using this method.

exception oauth2app.authorize.UnsupportedResponseType[source]

The authorization server does not support obtaining an authorization code using this method.

exception oauth2app.authorize.UnvalidatedRequest[source]

The method requested requires a validated request to continue.

Table Of Contents

Previous topic

Django OAuth 2.0 Server App

Next topic

Authentication