Models

class oauth2_provider.models.AbstractAccessToken(*args, **kwargs)

An AccessToken instance represents the actual access token to access user’s resources, as in RFC6749 Section 5.

Fields:

  • user The Django user representing resources” owner

  • source_refresh_token If from a refresh, the consumed RefeshToken

  • token Access token

  • application Application instance

  • expires Date and time of token expiration, in DateTime format

  • scope Allowed scopes

  • resource RFC 8707 resource indicator(s) - JSON-encoded array of URIs

  • claims The OIDC claims request (Core 5.5) the token was issued for

allow_scopes(scopes)

Check if the token allows the provided scopes

Parameters:

scopes – An iterable containing the scopes to check

allows_audience(audience_uri)

Check if the token is authorized for the given audience URI.

RFC 8707: Validates that the token includes the specified resource indicator using the configured resource validator (RESOURCE_SERVER_TOKEN_RESOURCE_VALIDATOR).

If the token has no resource indicators (empty list), it is unrestricted and allows any audience (backward compatibility).

Parameters:

audience_uri – The URI of the resource server to check

Returns:

True if the token is authorized for this audience, False otherwise

is_expired()

Check token expiration with timezone awareness

is_valid(scopes=None)

Checks if the access token is valid.

Parameters:

scopes – An iterable containing the scopes to check or None

revoke()

Convenience method to uniform tokens” interface, for now simply remove this token from the database in order to revoke it.

property scopes

Returns a dictionary of allowed scope names (as keys) with their descriptions (as values)

class oauth2_provider.models.AbstractApplication(*args, **kwargs)

An Application instance represents a Client on the Authorization server. Usually an Application is created manually by client’s developers after logging in on an Authorization Server.

Fields:

  • client_id The client identifier issued to the client during the

    registration process as described in RFC6749 Section 2.2

  • user ref to a Django user

  • redirect_uris The list of allowed redirect uri. The string

    consists of valid URLs separated by space

  • post_logout_redirect_uris The list of allowed redirect uris after

    an RP initiated logout. The string consists of valid URLs separated by space

  • client_type Client type as described in RFC6749 Section 2.1

  • authorization_grant_type Authorization flows available to the

    Application

  • client_secret Confidential secret issued to the client during

    the registration process as described in RFC6749 Section 2.2

  • name Friendly name for the Application

  • registration_source How the Application was registered: manual

    for manually created Applications, dcr for those registered via Dynamic Client Registration (RFC 7591), cimd for Client ID Metadata Document

  • cimd_expires_at When the cached metadata document should be

    re-fetched, for CIMD applications

  • require_pushed_authorization_requests Whether this client may only

    start an authorization request via PAR (RFC6749 Section 9126). None defers to the server-wide setting.

  • can_introspect Whether this client may call the token

    introspection endpoint (RFC6749 Section 7662), with an access token issued to it or, if it is confidential, by authenticating as itself.

  • userinfo_signed_response_alg The JWS alg the UserInfo response is

    signed with (OpenID Connect Core 1.0 section 5.3.2). Blank returns plain JSON.

class RegistrationSource(*values)
clean() → None

Validate the application, reporting each problem on the field it belongs to.

Raises a ValidationError keyed by field name, so callers get a per-field message_dict and a ModelForm renders each message next to its input. Every problem found is reported, not just the first one.

property default_redirect_uri

Returns the default redirect_uri, if only one is registered.

get_allowed_origin_validator() → Callable[[str], None]

Returns the validator clean() applies to each entry in allowed_origins. By default, builds one from the ALLOWED_ORIGIN_VALIDATOR setting.

Follows the same factory contract as get_redirect_uri_validator(). An origin whose scheme is outside ALLOWED_SCHEMES is still rejected at request time by is_origin_allowed() even if a custom validator lets it be stored.

get_allowed_schemes()

Returns the list of redirect schemes allowed by the Application. By default, returns ALLOWED_REDIRECT_URI_SCHEMES.

get_client_secret_hmac_jwk()

Return the oct JWK derived from the plaintext client secret, used to verify client_secret_jwt assertions (RFC 7523 section 2.2).

Distinct from jwk_key, which is the key the server signs ID tokens with; this one verifies what the client signed.

get_client_signing_jwks()

Return the inline jwk.JWKSet used to verify this client’s RFC 7523 assertions, or None when no inline JWKS is registered.

Remote client_jwks_uri resolution deliberately lives in oauth2_provider.authorization_server.client_assertions so the model stays network-free.

get_redirect_uri_validator() → Callable[[str], None]

Returns the validator clean() applies to each entry in redirect_uris and post_logout_redirect_uris. By default, builds one from the REDIRECT_URI_VALIDATOR setting.

The setting names a factory called with this application; the object it returns is called once per URI and raises ValidationError for anything unacceptable. Because the factory runs once per clean() rather than once per URI, a policy backed by the database queries once per save. Note this application may be unsaved (pk is None) when registration goes through Dynamic Client Registration, CIMD or the admin add form, so an override must not assume reverse relations exist.

This gates what may be stored. At request time a redirect uri is still matched by exact string comparison (see check_redirect_to_uri_allowed()), and the scheme is separately gated by get_allowed_schemes(), which no validator here can relax.

is_usable(request)

Determines whether the application can be used.

Parameters:

request – The oauthlib.common.Request being processed.

origin_allowed(origin)

Checks if given origin is one of the items in allowed_origins string

Parameters:

origin – Origin to check

post_logout_redirect_uri_allowed(uri: str) → bool

Checks if given URI is one of the items in post_logout_redirect_uris string

Parameters:

uri – URI to check

redirect_uri_allowed(uri: str) → bool

Checks if given url is one of the items in redirect_uris string

Parameters:

uri – Url to check

class oauth2_provider.models.AbstractDeviceGrant(*args, **kwargs)
is_expired()

Check device flow session expiration and set the status to “expired” if current time is past the “expires” deadline.

class oauth2_provider.models.AbstractGrant(*args, **kwargs)

A Grant instance represents a token with a short lifetime that can be swapped for an access token, as described in RFC6749 Section 4.1.2

Fields:

  • user The Django user who requested the grant

  • code The authorization code generated by the authorization server

  • application Application instance this grant was asked for

  • expires Expire time in seconds, defaults to

    settings.AUTHORIZATION_CODE_EXPIRE_SECONDS

  • redirect_uri Self explained

  • scope Required scopes, optional

  • code_challenge PKCE code challenge

  • code_challenge_method PKCE code challenge transform algorithm

  • resource RFC 8707 resource indicator(s), JSON-encoded array of URIs

is_expired()

Check token expiration with timezone awareness

class oauth2_provider.models.AbstractIDToken(*args, **kwargs)

An IDToken instance represents the token used to authenticate the user and convey claims to the client, as in OpenID Connect Core 1.0 Section 2.

Fields:

  • user The Django user representing resources’ owner

  • jti ID token JWT Token ID, to identify an individual token

  • application Application instance

  • expires Date and time of token expiration, in DateTime format

  • scope Allowed scopes

  • created Date and time of token creation, in DateTime format

  • updated Date and time of token update, in DateTime format

allow_scopes(scopes)

Check if the token allows the provided scopes

Parameters:

scopes – An iterable containing the scopes to check

is_expired()

Check token expiration with timezone awareness

is_valid(scopes=None)

Checks if the access token is valid.

Parameters:

scopes – An iterable containing the scopes to check or None

revoke()

Convenience method to uniform tokens’ interface, for now simply remove this token from the database in order to revoke it.

property scopes

Returns a dictionary of allowed scope names (as keys) with their descriptions (as values)

class oauth2_provider.models.AbstractRefreshToken(*args, **kwargs)

A RefreshToken instance represents a token that can be swapped for a new access token when it expires.

Fields:

  • user The Django user representing resources” owner

  • token Token value

  • application Application instance

  • access_token AccessToken instance this refresh token is

    bounded to

  • revoked Timestamp of when this refresh token was revoked

  • resource RFC 8707 resource indicator(s), JSON-encoded array of URIs

revoke()

Mark this refresh token revoked and revoke related access token

classmethod revoke_family(token_family: UUID | None) → None

Revoke every live refresh token sharing token_family and delete the family’s access tokens, in a constant number of queries.

This is the set-based equivalent of calling revoke() on each member of the family, which is what reuse protection needs: a rotating client adds a row to its family on every refresh, so revoking row by row cost one SELECT ... FOR UPDATE round trip per token ever issued to that session, paid again on every replay of the stale token (#1809). A model that overrides revoke() to do more should override this too.

Rows are not locked up front: unlike rotation this path mints nothing, so there is no read-then-write to protect. The statements take their locks in the same order as revoke() – refresh token, then access token – so a concurrent rotation in the family cannot deadlock against the sweep.

One timezone.now() is stamped across the whole family. That is safe because token_checksum is unique on its own: two live members cannot share a checksum, so the shared timestamp has no uniqueness to collide with (#1816).

class oauth2_provider.models.AbstractStoredAuthorizationRequest(*args, **kwargs)

A validated authorization request kept by the authorization server.

The request is referenced by a single-use, client-bound request_uri in the urn:ietf:params:oauth:request_uri: namespace (RFC6749 Section 9126#section-2.2), so the authorization endpoint can be called with only client_id and request_uri instead of the full parameter set. Requests pushed to the pushed authorization request endpoint (RFC6749 Section 9126) are stored here, and so is a request carried across a login. Only requests that have already been validated in full are stored; see oauth2_provider.authorization_server.stored_requests.

Fields:

  • request_uri The single-use urn:ietf:params:oauth:request_uri:*

    reference given to the client.

  • client_id The client the request URI is bound to (RFC6749 Section 9126#section-2.2).

  • parameters The authorization-request parameters, stored as a JSON

    mapping (client-authentication parameters excluded).

  • expires When the request URI ceases to be valid.

is_expired() → bool

Whether the request URI has passed its expires deadline.

class oauth2_provider.models.AccessToken(id, user, source_refresh_token, token, token_checksum, id_token, application, expires, scope, resource, claims, created, updated)
exception DoesNotExist
exception MultipleObjectsReturned
exception NotUpdated
class oauth2_provider.models.Application(id, client_id, user, redirect_uris, post_logout_redirect_uris, client_type, authorization_grant_type, client_secret, hash_client_secret, name, skip_authorization, created, updated, algorithm, userinfo_signed_response_alg, token_endpoint_auth_method, client_jwks, client_jwks_uri, client_uri, logo_uri, policy_uri, tos_uri, request_uris, request_object_signing_alg, allowed_origins, registration_source, cimd_expires_at, require_pushed_authorization_requests, can_introspect)
exception DoesNotExist
exception MultipleObjectsReturned
exception NotUpdated
class oauth2_provider.models.ClaimsRequestJSONField(verbose_name=None, name=None, encoder=None, decoder=None, **kwargs)

The normalized OIDC claims request (Core 5.5) behind a token: a JSON object.

An empty request is {}, never NULL, and anything but an object is refused.

pre_save(model_instance: Model, add: bool) → dict

The field is not nullable; treat None as an empty claims request.

The type is checked here, on save, rather than in get_db_prep_value, which also prepares the scalar operands of key lookups such as claims__userinfo__name__essential=True.

validate(value: object, model_instance: Model) → None

Validate value and raise ValidationError if necessary. Subclasses should override this to provide validation logic.

class oauth2_provider.models.ClientSecretField(*args, db_collation=None, **kwargs)
pre_save(model_instance, add)

Return field’s value just before saving.

class oauth2_provider.models.DeviceCodeResponse(verification_uri: str, expires_in: int, user_code: str, device_code: str, interval: int, verification_uri_complete: str | Callable | None = None)
class oauth2_provider.models.DeviceGrant(id, user, device_code, user_code, scope, interval, expires, status, client_id, last_checked)
exception DoesNotExist
exception MultipleObjectsReturned
exception NotUpdated
class oauth2_provider.models.DeviceRequest(client_id: str, scope: str | None = None)
class oauth2_provider.models.Grant(id, user, code, application, expires, redirect_uri, scope, created, updated, code_challenge, code_challenge_method, nonce, acr, claims, resource)
exception DoesNotExist
exception MultipleObjectsReturned
exception NotUpdated
class oauth2_provider.models.IDToken(id, user, jti, application, expires, scope, created, updated)
exception DoesNotExist
exception MultipleObjectsReturned
exception NotUpdated
class oauth2_provider.models.RefreshToken(id, user, token, token_checksum, application, access_token, token_family, resource, created, updated, revoked)
exception DoesNotExist
exception MultipleObjectsReturned
exception NotUpdated
class oauth2_provider.models.ResourceJSONField(verbose_name=None, name=None, encoder=None, decoder=None, **kwargs)

RFC 8707 - JSON array of resource URIs.

Empty list means not restricted to specific resource servers (unrestricted access).

get_db_prep_value(value, connection, prepared=False)

Validate before saving to database.

pre_save(model_instance, add)

The field is not nullable; treat None as “no resource restriction”.

class oauth2_provider.models.StoredAuthorizationRequest(id, request_uri, client_id, parameters, expires, created)
exception DoesNotExist
exception MultipleObjectsReturned
exception NotUpdated
class oauth2_provider.models.TokenChecksumField(*args, db_collation=None, **kwargs)
pre_save(model_instance, add)

Return field’s value just before saving.

oauth2_provider.models.check_redirect_to_uri_allowed(uri: str, allowed_uris: list[str]) → tuple[bool, list[tuple[str | None, str]]]

Same check as redirect_to_uri_allowed(), additionally reporting why the URI was rejected.

Returns (allowed, reasons). reasons is only meaningful when allowed is False: it holds one (candidate, reason) pair for every registered URI that failed to match, plus pairs with a None candidate for rejections of the requested URI itself. A reason names the component that differs instead of echoing the requested URI back, which callers log once and only after passing it through _loggable_uri().

Parameters:
  • uri – URI to check

  • allowed_uris – A list of URIs that are allowed

oauth2_provider.models.get_access_token_admin_class()

Return the AccessToken admin class that is active in this project.

oauth2_provider.models.get_access_token_model()

Return the AccessToken model that is active in this project.

oauth2_provider.models.get_application_admin_class()

Return the Application admin class that is active in this project.

oauth2_provider.models.get_application_model()

Return the Application model that is active in this project.

oauth2_provider.models.get_device_grant_model()

Return the DeviceGrant model that is active in this project.

oauth2_provider.models.get_grant_admin_class()

Return the Grant admin class that is active in this project.

oauth2_provider.models.get_grant_model()

Return the Grant model that is active in this project.

oauth2_provider.models.get_id_token_admin_class()

Return the IDToken admin class that is active in this project.

oauth2_provider.models.get_id_token_model()

Return the IDToken model that is active in this project.

oauth2_provider.models.get_refresh_token_admin_class()

Return the RefreshToken admin class that is active in this project.

oauth2_provider.models.get_refresh_token_model()

Return the RefreshToken model that is active in this project.

oauth2_provider.models.get_stored_authorization_request_model() → type[AbstractStoredAuthorizationRequest]

Return the StoredAuthorizationRequest model that is active in this project.

oauth2_provider.models.is_origin_allowed(origin, allowed_origins)

Checks if a given origin uri is allowed based on the provided allowed_origins configuration.

Parameters:
  • origin – Origin URI to check

  • allowed_origins – A list of Origin URIs that are allowed

oauth2_provider.models.redirect_to_uri_allowed(uri: str, allowed_uris: list[str]) → bool

Checks if a given uri can be redirected to based on the provided allowed_uris configuration.

On top of exact matches, this function also handles loopback IPs based on RFC 8252.

Parameters:
  • uri – URI to check

  • allowed_uris – A list of URIs that are allowed

oauth2_provider.models.refresh_token_expire_timedelta()

Return REFRESH_TOKEN_EXPIRE_SECONDS as a timedelta, or None when refresh tokens do not age-expire (the setting is unset, 0, or timedelta(0)).

Raises ImproperlyConfigured for a non-numeric, out-of-range, or negative value (like REFRESH_TOKEN_GRACE_PERIOD_SECONDS) so that both the validation-time enforcement and clear_expired fail the same way on a misconfiguration instead of raising an opaque TypeError/OverflowError.

oauth2_provider.models.revoke_access_token(access_token: AbstractAccessToken) → None

Revoke an access token and, if present, its bound refresh token.

Deleting the access token on its own leaves the refresh token usable (the RefreshToken.access_token FK is SET_NULL), so it can still be exchanged for a fresh access token, defeating the revocation. Per RFC6749 Section 7009#section-2.1 revoking an access token MAY also revoke the bound refresh token; revoking the refresh token also deletes the bound access token, so it covers both. When there is no refresh token, revoke the access token directly (which deletes it).

The bound refresh token is looked up with a forward query on the refresh token model rather than the reverse access_token.refresh_token accessor, whose name depends on the related_name a swapped refresh token model may override.

This is the single revoke path shared by the /revoke/ endpoint, the AuthorizedTokenDeleteView, and the admin “Revoke selected access tokens” action. Whether a refresh token may survive access-token revocation is a policy deferred to 4.x (see #1786).

oauth2_provider.models.set_token_value(token_instance: AbstractAccessToken | AbstractRefreshToken, raw_token: str) → None

Assign the raw token to a token instance, redacting the value stored at rest when COMPLIANT_BCP_RFC9700_TOKEN_STORAGE is enabled (RFC 9700).

The lookup checksum (token_checksum) is always derived from the raw token; when redacting, the raw value is stashed on _raw_token (used only to compute the checksum, see TokenChecksumField) and the token column is left blank so the reusable token is never persisted.

Plaintext storage is an ambient config posture exercised on every token issuance, so (unlike the request-time gates) it is surfaced by the --deploy system check W006 rather than a per-token warning here. See oauth2_provider.bcp.