Views code and details
Generic
Generic views are intended to use in a “batteries included” fashion to protect own views with OAuth2 authentication and Scopes handling.
- class oauth2_provider.views.generic.ClientProtectedResourceMetadataView(**kwargs)
ClientProtectedResourceViewthat advertises RFC 9728 resource metadata.
- class oauth2_provider.views.generic.ClientProtectedResourceView(**kwargs)
View for protecting a resource with client-credentials method. This involves allowing access tokens, Basic Auth and plain credentials in request body.
- class oauth2_provider.views.generic.ClientProtectedScopedResourceView(**kwargs)
Impose scope restrictions if client protection fallsback to access token.
- class oauth2_provider.views.generic.ProtectedResourceMetadataView(**kwargs)
ProtectedResourceViewthat advertises RFC 9728 resource metadata.
- class oauth2_provider.views.generic.ProtectedResourceView(**kwargs)
Generic view protecting resources by providing OAuth2 authentication out of the box
- class oauth2_provider.views.generic.ReadWriteScopedProtectedResourceMetadataView(*args, **kwargs)
ReadWriteScopedResourceViewthat advertises RFC 9728 resource metadata.
- class oauth2_provider.views.generic.ReadWriteScopedResourceView(*args, **kwargs)
Generic view protecting resources with OAuth2 authentication and read/write scopes. GET, HEAD, OPTIONS http methods require “read” scope. Otherwise “write” scope is required.
- class oauth2_provider.views.generic.ScopedProtectedResourceMetadataView(**kwargs)
ScopedProtectedResourceViewthat advertises RFC 9728 resource metadata.
- class oauth2_provider.views.generic.ScopedProtectedResourceView(**kwargs)
Generic view protecting resources by providing OAuth2 authentication and Scopes handling out of the box
Mixins
These views are mainly for internal use, but advanced users may use them as basic components to customize OAuth2 logic inside their Django applications.
- class oauth2_provider.views.mixins.ClientProtectedResourceMixin
Mixin for protecting resources with client authentication as mentioned in rfc:3.2.1 This involves authenticating with any of: HTTP Basic Auth, Client Credentials and Access token in that order. Breaks off after first validation.
- class oauth2_provider.views.mixins.OAuthLibMixin
This mixin decouples Django OAuth Toolkit from OAuthLib.
Users can configure the Server, Validator and OAuthlibCore classes used by this mixin by setting the following class variables:
server_class
validator_class
oauthlib_backend_class
If these class variables are not set, it will fall back to using the classes specified in oauth2_settings (OAUTH2_SERVER_CLASS, OAUTH2_VALIDATOR_CLASS and OAUTH2_BACKEND_CLASS).
- authenticate_client(request)
Returns a boolean representing if client is authenticated with client credentials method. Returns True if authenticated.
- Parameters:
request – The current django.http.HttpRequest object
- create_authorization_response(request, scopes, credentials, allow)
A wrapper method that calls create_authorization_response on server_class instance.
- Parameters:
request – The current django.http.HttpRequest object
scopes – A space-separated string of provided scopes
credentials – Authorization credentials dictionary containing client_id, state, redirect_uri and response_type
allow – True if the user authorize the client, otherwise False
- create_device_authorization_response(request: HttpRequest)
A wrapper method that calls create_device_authorization_response on server_class instance. :param request: The current django.http.HttpRequest object
- create_revocation_response(request)
A wrapper method that calls create_revocation_response on the server_class instance.
- Parameters:
request – The current django.http.HttpRequest object
- create_token_response(request)
A wrapper method that calls create_token_response on server_class instance.
- Parameters:
request – The current django.http.HttpRequest object
- create_userinfo_response(request)
A wrapper method that calls create_userinfo_response on the server_class instance.
- Parameters:
request – The current django.http.HttpRequest object
- error_response(error, **kwargs)
Return an error to be displayed to the resource owner if anything goes awry.
- Parameters:
error –
OAuthToolkitError
- classmethod get_oauthlib_backend_class()
Return the OAuthLibCore implementation class to use
- classmethod get_oauthlib_core()
Cache and return OAuthlibCore instance so it will be created only on first request unless ALWAYS_RELOAD_OAUTHLIB_CORE is True.
- get_scopes()
This should return the list of scopes required to access the resources. By default it returns an empty list.
- classmethod get_server()
Return an instance of server_class initialized with a validator_class object
- classmethod get_server_class()
Return the OAuthlib server class to use
- classmethod get_validator_class()
Return the RequestValidator implementation class to use
- unauthenticated_response(request, oauthlib_request=None)
Response returned when a protected resource request fails authentication.
Defaults to a bare
403 Forbidden(the historical behaviour).ProtectedResourceMetadataMixinoverrides this to return an RFC 6750401carrying an RFC 9728WWW-Authenticatechallenge.- Parameters:
oauthlib_request – the oauthlib request produced by
verify_request, carrying anyoauth2_errordetail (Nonefor client-auth failures).
- validate_authorization_request(request)
A wrapper method that calls validate_authorization_request on server_class instance.
- Parameters:
request – The current django.http.HttpRequest object
- verify_request(request)
A wrapper method that calls verify_request on server_class instance.
- Parameters:
request – The current django.http.HttpRequest object
- class oauth2_provider.views.mixins.OIDCLogoutOnlyMixin
Mixin for views that should only be accessible when OIDC and OIDC RP-Initiated Logout are enabled.
If either is not enabled:
if DEBUG is True, raises an ImproperlyConfigured exception explaining why
otherwise, returns a 404 response, logging the same warning
- class oauth2_provider.views.mixins.OIDCOnlyMixin
Mixin for views that should only be accessible when OIDC is enabled.
If OIDC is not enabled:
if DEBUG is True, raises an ImproperlyConfigured exception explaining why
otherwise, returns a 404 response, logging the same warning
- class oauth2_provider.views.mixins.ProtectedResourceMetadataMixin
RFC 9728 opt-in: advertise protected-resource metadata on auth failure.
Mix this in before a protected-resource view/mixin (
ProtectedResourceMixin,ClientProtectedResourceMixin, …) to replace the default bare403 Forbiddendenial with a response carrying aWWW-Authenticate: Bearerchallenge and the RFC 9728resource_metadataparameter pointing at/.well-known/oauth-protected-resource. Per RFC 6750 the status is401 Unauthorizedfor a missing/invalid token and403 Forbiddenforinsufficient_scope. Opting in explicitly (rather than via a global flag) keeps the default views’ behaviour unchanged.It subclasses
OAuthLibMixinso that itsunauthenticated_responseis an unambiguous override of the base hook (rather than a value from an unrelated base class) when combined with a protected-resource view/mixin.Set
www_authenticate_realmto advertise a realm in the challenge. Setresource_metadata_url(or overrideget_resource_metadata_url()) to advertise a specific metadata document — e.g. the RFC 9728 path-component form for a path-based/multi-tenant resource — instead of this server’s root/.well-known/oauth-protected-resource.- get_resource_metadata_url(request)
URL advertised in
resource_metadata.Returns
resource_metadata_urlwhen set, otherwiseNoneso the challenge builder falls back to the server’s root metadata route. Override to derive the URL from the protected resource’s identifier/path.
- unauthenticated_response(request, oauthlib_request=None)
Response returned when a protected resource request fails authentication.
Defaults to a bare
403 Forbidden(the historical behaviour).ProtectedResourceMetadataMixinoverrides this to return an RFC 6750401carrying an RFC 9728WWW-Authenticatechallenge.- Parameters:
oauthlib_request – the oauthlib request produced by
verify_request, carrying anyoauth2_errordetail (Nonefor client-auth failures).
- class oauth2_provider.views.mixins.ProtectedResourceMixin
Helper mixin that implements OAuth2 protection on request dispatch, specially useful for Django Generic Views
- class oauth2_provider.views.mixins.ReadWriteScopedResourceMixin(*args, **kwargs)
Helper mixin that implements “read and write scopes” behavior
- get_scopes(*args, **kwargs)
Return the scopes needed to access the resource
- Parameters:
args – Support scopes injections from the outside (not yet implemented)
Base
Views needed to implement the main OAuth2 authorization flows supported by Django OAuth Toolkit.
- class oauth2_provider.views.base.AuthorizationView(**kwargs)
Implements an endpoint to handle Authorization Requests as in RFC6749 Section 4.1.1 and prompting the user with a form to determine if she authorizes the client application to access her data. This endpoint is reached two times during the authorization process: * first receive a
GETrequest from user asking authorization for a certain client application, a form is served possibly showing some useful info and prompting for authorize/do not authorize.then receive a
POSTrequest possibly after user authorized the access
Some information contained in the
GETrequest and needed to create a Grant token during thePOSTrequest would be lost between the two steps above, so they are temporarily stored in hidden fields on the form. A possible alternative could be keeping such information in the session.The endpoint is used in the following flows: * Authorization code * Implicit grant
- form_class
alias of
AllowForm
- form_valid(form)
If the form is valid, redirect to the supplied URL.
- get(request, *args, **kwargs)
Handle GET requests: instantiate a blank version of the form.
- get_initial()
Return the initial data to use for forms on this view.
- handle_no_permission()
Generate response for unauthorized users.
If the prompt parameter contains none, then we redirect with an error code as defined by OpenID Connect Core 1.0 section 3.1.2.6 (Authentication Error Response) <https://openid.net/specs/openid-connect-core-1_0.html#AuthError>.
If the prompt parameter contains create, then we redirect to the registration page.
If the prompt parameter contains login, then we redirect straight to the login flow with the prompt consumed, so the user is not sent to login a second time when they return to this endpoint authenticated.
Some code copied from OAuthLibMixin.error_response, but that is designed to operate on OAuth2Error from oauthlib wrapped in a OAuthToolkitError
- handle_prompt_create()
When the prompt parameter of the authorization request contains create, redirect unauthenticated users to the registration page. After registration, the user should be redirected back to the authorization endpoint, with create removed from the prompt parameter, to continue the OIDC flow.
For a user with an existing authenticated session, create is a no-op: None is returned and the authorization request proceeds as if create was not present. The spec leaves this case open (“whether the AS creates a brand new identity or helps the user authenticate an identity they already have is out of scope”) and this matches how major providers treat a signup hint alongside an active session. A Relying Party that wants re-authentication instead can combine prompt values, e.g. “create login”.
Implements OpenID Connect Prompt Create 1.0 specification. https://openid.net/specs/openid-connect-prompt-create-1_0.html
- class oauth2_provider.views.base.BaseAuthorizationView(**kwargs)
Implements a generic endpoint to handle Authorization Requests as in RFC6749 Section 4.1.1. The view does not implement any strategy to determine authorize/do not authorize logic. The endpoint is used in the following flows:
Authorization code
Implicit grant
- error_response(error, application, **kwargs)
Handle errors either by redirecting to redirect_uri with a json in the body containing error details or providing an error response
- class oauth2_provider.views.base.RevokeTokenView(**kwargs)
Implements an endpoint to revoke access or refresh tokens
- class oauth2_provider.views.base.TokenView(**kwargs)
Implements an endpoint to provide access tokens
The endpoint is used in the following flows: * Authorization code * Password * Client credentials * Device code flow (specifically for the device polling stage)