Core / shared settings
OAUTH2_SERVER_CLASS
The import string for the server_class (or oauthlib.oauth2.Server subclass)
used in the OAuthLibMixin that implements OAuth2 grant types. It defaults
to oauthlib.oauth2.Server, except when OpenID Connect is enabled, when the
default is oauth2_provider.authorization_server.oidc.server.Server (see
OIDC_SERVER_CLASS).
When OIDC_ENABLED is True and OAUTH2_SERVER_CLASS is not explicitly
configured, OIDC_SERVER_CLASS is used as the fallback.
OAUTH2_VALIDATOR_CLASS
The import string of the oauthlib.oauth2.RequestValidator subclass that
validates every step of the OAuth2 process.
OAUTH2_BACKEND_CLASS
The import string for the oauthlib_backend_class used by the view mixins, to get a
Server instance. Defaults to
oauth2_provider.core.backends_oauthlib.OAuthLibCore, which reads request bodies as
application/x-www-form-urlencoded as required by the OAuth specifications.
(The pre-4.0 alias oauth2_provider.oauth2_backends.OAuthLibCore still resolves but is
deprecated.)
A custom backend that overrides create_authorization_response() must, before raising
access_denied, call OAuthLibCore.validate_authorization_redirect_uri() and redirect to the
URI it returns, not to credentials["redirect_uri"]: the method raises an error for a
redirect_uri the client has not registered, and returns the client’s default redirect URI when
the request has none.
Note
The oauth2_provider.core.backends_oauthlib.JSONOAuthLibCore backend value is deprecated
(since 3.4.1) and will be removed in 4.0. It makes the OAuth token, introspection, and
revocation endpoints
read application/json request bodies, but those endpoints are defined to use
application/x-www-form-urlencoded (RFC 6749, RFC 7662, RFC 7009). The JSON mode is
non-standard and breaks interoperability with spec-compliant clients; every client can
send a form-encoded body, so it provides no capability that the default backend lacks.
Set REQUIRE_FORM_ENCODED_REQUEST_BODY to reject the non-standard bodies outright
rather than misreporting them as a missing parameter.
SCOPES_BACKEND_CLASS
New in 0.12.0. The import string for the scopes backend class.
Defaults to oauth2_provider.core.scopes.SettingsScopes, which reads scopes through the settings defined below.
(The pre-4.0 alias oauth2_provider.scopes.SettingsScopes still resolves but is deprecated.)
See Custom scopes backend for how to write your own backend (for example to store scopes in the
database).
SCOPES
Note
(0.12.0+) Only used if SCOPES_BACKEND_CLASS is set to the SettingsScopes default.
A dictionary mapping each scope name to its human description.
DEFAULT_SCOPES
Note
(0.12.0+) Only used if SCOPES_BACKEND_CLASS is set to the SettingsScopes default.
A list of scopes that should be returned by default.
This is a subset of the keys of the SCOPES setting.
By default this is set to '__all__' meaning that the whole set of SCOPES will be returned.
DEFAULT_SCOPES = ['read', 'write']
READ_SCOPE
The name of the read scope. Unlike SCOPES/DEFAULT_SCOPES, this is used regardless of
SCOPES_BACKEND_CLASS – the read/write permission helpers (TokenHasReadWriteScope,
TokenHasResourceScope, rw_protected_resource, ReadWriteScopedResourceMixin) read it
directly from settings. A custom scopes backend must therefore expose a scope with this name from
get_available_scopes() so a token can actually be granted it (requested scopes are validated
against get_available_scopes(); see OAuth2Validator.validate_scopes). rw_protected_resource
and ReadWriteScopedResourceMixin additionally require it to be in get_all_scopes() and raise
ImproperlyConfigured otherwise (see Custom scopes backend).
WRITE_SCOPE
The name of the write scope. Like READ_SCOPE, this is used regardless of
SCOPES_BACKEND_CLASS by the read/write permission helpers, so a custom scopes backend must
expose a scope with this name from get_available_scopes() (so it can be granted) and, for
rw_protected_resource / ReadWriteScopedResourceMixin, from get_all_scopes() (see
Custom scopes backend).
GRANT_MODEL
The import string of the class (model) representing your grants. Overwrite
this value if you wrote your own implementation (subclass of
oauth2_provider.models.Grant).
APPLICATION_ADMIN_CLASS
The import string of the class (model) representing your application admin class.
Overwrite this value if you wrote your own implementation (subclass of
oauth2_provider.authorization_server.admin.ApplicationAdmin).
ACCESS_TOKEN_ADMIN_CLASS
The import string of the class (model) representing your access token admin class.
Overwrite this value if you wrote your own implementation (subclass of
oauth2_provider.authorization_server.admin.AccessTokenAdmin).
GRANT_ADMIN_CLASS
The import string of the class (model) representing your grant admin class.
Overwrite this value if you wrote your own implementation (subclass of
oauth2_provider.authorization_server.admin.GrantAdmin).
REFRESH_TOKEN_ADMIN_CLASS
The import string of the class (model) representing your refresh token admin class.
Overwrite this value if you wrote your own implementation (subclass of
oauth2_provider.authorization_server.admin.RefreshTokenAdmin).
CLEAR_EXPIRED_TOKENS_BATCH_SIZE
Default: 10000
The size of delete batches used by cleartokens management command.
CLEAR_EXPIRED_TOKENS_BATCH_INTERVAL
Default: 0
Time of sleep in seconds used by cleartokens management command between batch deletions.
Set this to a non-zero value (e.g. 0.1) to add a pause between batch sizes to reduce system
load when clearing large batches of expired tokens.
Authorization Server settings
CLIENT_ID_GENERATOR_CLASS
The import string of the class responsible for generating client identifiers.
These are usually random strings.
CLIENT_SECRET_GENERATOR_CLASS
The import string of the class responsible for generating client secrets.
These are usually random strings.
CLIENT_SECRET_GENERATOR_LENGTH
The length of the generated secrets, in characters. If this value is too low,
secrets may become subject to bruteforce guessing.
CLIENT_SECRET_HASHER
The hasher for storing generated secrets. By default library will use the first hasher in PASSWORD_HASHERS.
ACCESS_TOKEN_GENERATOR
Import path of a callable used to generate access tokens.
oauthlib.oauth2.rfc6749.tokens.random_token_generator is (normally) used if not provided.
REFRESH_TOKEN_GENERATOR
See ACCESS_TOKEN_GENERATOR. This is the same but for refresh tokens.
Defaults to access token generator if not provided.
ACCESS_TOKEN_EXPIRE_SECONDS
Default: 36000
How long an access token remains valid. Requesting a protected resource after this
duration will fail. Keep this value high enough so clients can cache the token for a
reasonable amount of time.
Accepted values:
an int (or float) number of seconds;
a datetime.timedelta;
a callable taking the current oauthlib.common.Request and returning either of
the above, so the lifetime can vary per client, grant type, scope or session;
a dotted import path to such a callable, e.g. "myapp.oauth.access_token_expires_in"
– useful because a Django settings module often cannot import a callable that touches
models at settings-load time.
The resolved value drives both the expires_in member of the token response and the
stored AccessToken.expires, so the two always agree. A static value must be
positive; a misconfigured one is reported at startup as oauth2_provider.E006.
See Varying the access token lifetime per request for worked examples, and note that
EXTRA_SERVER_KWARGS ["token_expires_in"], if set, overrides this setting.
AUTHORIZATION_CODE_EXPIRE_SECONDS
Default: 60
The number of seconds an authorization code remains valid. Requesting an access
token after this duration will fail. RFC6749 Section 4.1.2 recommends expire after a short lifetime,
with 10 minutes (600 seconds) being the maximum acceptable.
REFRESH_TOKEN_EXPIRE_SECONDS
How long a refresh token remains valid. Can be an Int or datetime.timedelta.
Defaults to None, which means refresh tokens never expire (they last until
revoked or rotated).
Expiry is idle-based: a refresh token is rejected REFRESH_TOKEN_EXPIRE_SECONDS
after its paired access token expires. Because the access token’s expiry advances
every time the refresh token is used, an actively-used refresh token keeps sliding
forward and never expires on its own; only a refresh token that has been dormant for
longer than REFRESH_TOKEN_EXPIRE_SECONDS past its last access token’s expiry is
rejected.
When set, this is enforced in two places:
at validation time – a refresh token past its lifetime is rejected when presented,
regardless of whether cleartokens has run; and
by the cleartokens management command, which deletes expired refresh tokens from
the database (see the cleartokens management command).
A value of 0 (or datetime.timedelta(0)) is treated the same as None –
expiry is disabled – consistent with cleartokens.
Note
Deployments that already set REFRESH_TOKEN_EXPIRE_SECONDS should be aware that,
as of the release that introduced validation-time enforcement, refresh tokens that
are already past their configured lifetime are rejected on their next use, which may
force affected clients to re-authenticate.
Note
Security guidance. Refresh-token rotation (ROTATE_REFRESH_TOKEN, on by default)
is the primary defense against a leaked refresh token; see RFC 9700 Security Best Current Practice. As
additional defense-in-depth, consider setting a finite REFRESH_TOKEN_EXPIRE_SECONDS
so a refresh token that leaks and is then left idle cannot be redeemed indefinitely.
The default None places no upper bound on an idle refresh token’s lifetime.
REFRESH_TOKEN_GRACE_PERIOD_SECONDS
The number of seconds a refresh token can still be used after it has been
revoked, for example because it was consumed by refresh token rotation. The
most common use case is native mobile applications that run into issues of
network connectivity during the refresh cycle and are unable to complete the
full request/response life cycle. Without a grace period the app has only a
consumed refresh token and the only recourse is to have the user
re-authenticate. A suggested value, if this is enabled, is 2 minutes. The
value must not be negative.
The cleartokens management command removes revoked refresh tokens once the
grace period has passed, unless REFRESH_TOKEN_REUSE_PROTECTION is enabled.
Check cleartokens management command for further info.
The grace period only ever shields a refresh token that a rotation superseded — the
token a client retries when it did not receive the rotated response. A refresh token that
was deliberately revoked (through the /revoke/ endpoint, the admin, RP-initiated
logout, or by revoking its access token) is rejected immediately, whatever the grace
period: RFC6749 Section 7009#section-2.1 requires that a revoked token “cannot be used again after
the revocation”. The same applies to a token that has already been rotated past — see
REFRESH_TOKEN_REUSE_PROTECTION below.
With ROTATE_REFRESH_TOKEN disabled nothing supersedes a refresh token, so the grace
period has no effect: the same token stays valid until it is revoked or expires.
REFRESH_TOKEN_REUSE_PROTECTION
When this is set to True (default False), and ROTATE_REFRESH_TOKEN is used, the server will check
if a previously, already revoked refresh token is used a second time. If it detects a reuse, it will automatically
revoke all related refresh tokens.
A reused refresh token indicates a breach. Since the server can’t determine which request came from the legitimate
user and which from an attacker, it will end the session for both. The user is required to perform a new login.
Can be used in combination with REFRESH_TOKEN_GRACE_PERIOD_SECONDS
The family is revoked as a set, by RefreshToken.revoke_family(), in a fixed number of
queries however large the family is. This matters because a rotating session keeps every
refresh token it has ever been issued in the same family: the family only grows, and a
client that keeps replaying the same stale token pays for the sweep on every request.
token_family is indexed for this. If you swap in your own refresh token model, run
makemigrations to pick up that index, and if you override revoke() override
revoke_family() to match, so both paths revoke a token the same way.
This requires ROTATE_REFRESH_TOKEN: replay is detected by recognizing a token that a
previous rotation superseded, and without rotation nothing ever does. Enabling reuse
protection while rotation is off raises the oauth2_provider.W012 system check.
More details at https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-29#name-recommendations
ROTATE_REFRESH_TOKEN
When is set to True (default) a new refresh token is issued to the client when the client refreshes an access token.
If False, it will reuse the same refresh token and only update the access token with a new token value.
See also: validator’s rotate_refresh_token method can be overridden to make this variable
(could be usable with expiring refresh tokens, in particular, so that they are rotated
when close to expiration, theoretically).
ERROR_RESPONSE_WITH_SCOPES
When authorization fails due to insufficient scopes include the required scopes in the response.
Only applicable when used with Django REST Framework
REQUEST_APPROVAL_PROMPT
Can be 'force' or 'auto'.
The strategy used to display the authorization form. Refer to Skip authorization form.
ALLOWED_REDIRECT_URI_SCHEMES
Default: ["http", "https"]
A list of schemes that the redirect_uris and post_logout_redirect_uris fields will be
validated against.
Setting this to ["https"] only in production is strongly recommended.
For Native Apps the http scheme can be safely used with loopback addresses in the
Application ([::1] or 127.0.0.1). In this case the redirect_uri can be
configured without explicit port specification, so that the Application accepts randomly
assigned ports.
Note that you may override Application.get_allowed_schemes() to set this on
a per-application basis. For policy a static list cannot express – schemes held in the database,
a blacklist, or review-gated approval – replace the validator itself; see
REDIRECT_URI_VALIDATOR below.
Native apps using an RFC 8252 §7.1 private-use URI scheme should add that scheme here
(e.g. ["https", "com.example.app"]) and register the redirect URI in the single-slash
form the RFC prescribes, com.example.app:/oauth2redirect. A private-use scheme has no
naming authority, so the single-slash and double-slash spellings are different URIs and
are not interchangeable at request time. The redundant com.example.app:///oauth2redirect
and the rootless com.example.app:oauth2redirect are rejected. Schemes that require an
authority (http, https, ws, wss, ftp) must still include a host.
ALLOWED_SCHEMES
Default: ["https"]
A list of schemes that the allowed_origins field will be validated against.
Setting this to ["https"] only in production is strongly recommended.
Adding "http" to the list is considered to be safe only for local development and testing.
Note that OAUTHLIB_INSECURE_TRANSPORT
environment variable should be also set to allow HTTP origins.
For origin policy a static list cannot express, replace the validator itself; see
ALLOWED_ORIGIN_VALIDATOR below.
ALLOW_URI_WILDCARDS
Default: False
SECURITY WARNING: Enabling this setting can introduce security vulnerabilities. Only enable
this setting if you understand the risks. https://datatracker.ietf.org/doc/html/rfc6749#section-3.1.2
states “The redirection endpoint URI MUST be an absolute URI as defined by [RFC3986] Section 4.3.” The
intent of the URI restrictions is to prevent open redirects and phishing attacks. If you do enable this
ensure that the wildcards restrict URIs to resources under your control. You are strongly encouraged not
to use this feature in production.
When set to True, the server will allow wildcard characters in the domains for allowed_origins and
redirect_uris.
* is the only wildcard character allowed.
* can only be used as a prefix to a domain, must be the first character in
the domain, and cannot be in the top or second level domain. Matching is done using an
endsWith check.
For example,
https://*.example.com is allowed,
https://*.sub.example.com is allowed,
https://*-myproject.example.com is allowed,
https://*--sitename.netlify.app is allowed for Netlify deploy previews,
https://*.com is not allowed, and
https://example.*.com is not allowed.
Single-dash patterns such as https://*-sitename.netlify.app are syntactically allowed for
backward compatibility, but they are unsafe for Netlify because they can match unrelated hosts such
as something-sitename.netlify.app. Use the double-dash form for Netlify deploy previews.
This feature is useful for working with CI service such as cloudflare, netlify, and vercel that offer branch
deployments for development previews and user acceptance testing.
REDIRECT_URI_VALIDATOR
Default: "oauth2_provider.validators.default_redirect_uri_validator"
A callable that builds the validator applied to each entry in an application’s redirect_uris
and post_logout_redirect_uris when the application is validated. Use it for redirect-uri policy
that a static scheme list cannot express – schemes stored in the database, a blacklist, or a scheme
accepted only once the client has been reviewed.
The setting names a factory, not the validator itself. It is called with the application and
returns a callable that takes one URI string and raises
ValidationError when the URI is unacceptable:
factory(application) -> callable(uri)
Application.clean() calls the factory once per validation pass, so a factory backed by the
database queries once per save rather than once per URI. The application may be unsaved
(pk is None) when it is registered through Dynamic Client Registration (RFC6749 Section 7591),
CIMD or the admin add form, so a factory must not assume its reverse relations exist.
A class is a callable too, so a validator can subclass oauth2_provider.validators.AllowedURIValidator
and take the application in __init__, inheriting all of its RFC6749 Section 3986 / RFC6749 Section 8252 parsing:
from oauth2_provider.validators import AllowedURIValidator
class DBSchemeValidator(AllowedURIValidator):
def __init__(self, application):
schemes = list(application.approved_schemes.values_list("scheme", flat=True))
super().__init__(schemes, name="redirect uri", allow_path=True, allow_query=True)
OAUTH2_PROVIDER = {
"REDIRECT_URI_VALIDATOR": "myapp.validators.DBSchemeValidator",
}
To set the policy per application instead of server-wide, override
Application.get_redirect_uri_validator() on a swapped application model.
Unlike RESOURCE_SERVER_TOKEN_RESOURCE_VALIDATOR, this setting may not be None: skipping
redirect-uri validation entirely is an open-redirect risk, so an empty value raises at first access.
A deliberate no-op is still available, spelled explicitly as a factory returning lambda uri: None.
Warning
This gates what may be stored, not what is accepted at request time. An incoming
redirect_uri is still matched against the stored values by exact string comparison per
RFC6749 Section 9700 section 2.1, which no validator here can relax – a validator that permits a sloppy
URI merely stores a value that never matches.
Conversely, permitting a new scheme here is not enough on its own: the scheme is separately
gated at request time by Application.get_allowed_schemes() (see
ALLOWED_REDIRECT_URI_SCHEMES above), so a URI accepted here can still be refused when the
redirect is issued. Widen both, and remember that widening the accepted set widens the
open-redirect and phishing surface.
The RFC6749 Section 9700 deploy checks W008 and W009 read ALLOWED_REDIRECT_URI_SCHEMES and
ALLOW_URI_WILDCARDS statically, so they cannot see through a custom validator and may both
false-positive and false-negative. A custom validator owns its own RFC6749 Section 9700 section 2.1 posture.
On the Dynamic Client Registration and CIMD paths the validator is the only check on redirect
uri syntax, and its message is surfaced verbatim to the registering client in
error_description. Write client-facing messages there.
ALLOWED_ORIGIN_VALIDATOR
Default: "oauth2_provider.validators.default_allowed_origin_validator"
A callable that builds the validator applied to each entry in an application’s allowed_origins.
It follows exactly the same factory contract as REDIRECT_URI_VALIDATOR above, including the
prohibition on None, and is overridable per application as
Application.get_allowed_origin_validator().
Warning
As above, this gates only what may be stored. An origin whose scheme is outside
ALLOWED_SCHEMES is still rejected at request time by is_origin_allowed(), so a custom
validator that permits one must widen ALLOWED_SCHEMES too.
ALLOW_LOCALHOST_LOOPBACK
Default: False
RFC 8252 section 7.3 requires the
authorization server to accept any port on a loopback redirect_uri at request time, so a native
app can bind whatever ephemeral port the OS assigns. The toolkit applies that exemption to the loopback
IP literals 127.0.0.1 and [::1] unconditionally. Section 8.3 notes that localhost redirect URIs
“function similarly” but that their use is NOT RECOMMENDED, so localhost is not granted the
any-port exemption by default.
Some native clients nonetheless register http://localhost/callback and then receive the callback on
an ephemeral port. When set to True, the http://localhost hostname is treated as loopback and
granted the same any-port exemption as the IP literals. The hostname must still match exactly, so
localhost is never conflated with 127.0.0.1 / [::1], and scheme, path, and query matching
are unchanged.
SECURITY WARNING: Per RFC 8252 section 8.3, prefer registering the loopback IP literals over
localhost: a localhost redirect can resolve to a non-loopback interface on a host with
misconfigured name resolution, whereas 127.0.0.1 / [::1] cannot. Only enable this if you must
support clients that register localhost.
REQUIRE_FORM_ENCODED_REQUEST_BODY
Default: False
When True, a POST to an endpoint that takes the parameters making up the request in an
application/x-www-form-urlencoded body is answered with 415 Unsupported Media Type and an
invalid_request error unless it is sent with that media type. It covers the token
(RFC6749 Section 4.1.3, RFC6749 Section 4.3.2, RFC6749 Section 4.4.2 and RFC6749 Section 6), revocation (RFC 7009 section 2.1), introspection
(RFC 7662 section 2.1), device
authorization (RFC 8628 section 3.1) and pushed authorization request
(RFC 9126 section 2.1) endpoints.
Media type parameters are ignored, so application/x-www-form-urlencoded; charset=UTF-8 is
accepted. GET requests are never affected: the introspection endpoint, the only covered one
that accepts a GET, takes its parameters from the query string there.
Some endpoints are deliberately not covered. Dynamic Client Registration takes
application/json bodies per RFC 7591. The
OpenID Connect UserInfo endpoint accepts a POST whose only credential is the Authorization
header (OpenID Connect Core section 5.3.1); the form-encoding
requirement of RFC 6750 section 2.2 is a condition on a client putting
the access token in the body, not a constraint on the endpoint. Your own protected resources
are likewise untouched.
Deprecated since version 3.5: The False default is deprecated and is scheduled to become True in 4.0. Until then
a non-compliant body is still passed through, but every one emits a DeprecationWarning
and an oauth2_provider logger warning naming the change to come. Nothing is emitted for
a compliant request, so a deployment whose clients already send form-encoded bodies stays
quiet – and for it the coming default flip is a no-op. Set the setting to True to adopt
the behavior now and silence the warnings.
The default is False because turning enforcement on rejects two kinds of request that
previously worked:
application/json bodies, read by the deprecated JSONOAuthLibCore value of
OAUTH2_BACKEND_CLASS. Combining that backend with this setting rejects every request
before the backend can parse it, so manage.py check raises oauth2_provider.E006.
multipart/form-data bodies. No specification permits them here, but Django parses them
into request.POST so they have always worked – including from Django’s own test client,
whose client.post(url, data={...}) sends multipart unless a content_type is passed.
If your test suite posts to these endpoints that way, it is the source of the warnings, and
it will need a content_type before 4.0.
While enforcement is off, a request sent with any other media type reaches the view with no
parameters at all (Django only populates request.POST for form-encoded and multipart
bodies), which surfaces as a misleading error about a parameter the client did send – a JSON
token request, for instance, is rejected as unsupported_grant_type.
PAR_REQUEST_URI_LIFETIME_SECONDS
Default: 60
The lifetime, in seconds, of a request_uri issued by the PAR endpoint. RFC 9126 §2.2 suggests a
relatively short value (typically between 5 and 600 seconds).
REQUIRE_PUSHED_AUTHORIZATION_REQUESTS
Default: False
When True, the authorization endpoint only accepts requests that were pushed to the PAR
endpoint (i.e. that carry a request_uri), and the metadata document advertises
require_pushed_authorization_requests. Enforcement can also be required per client via the
application’s require_pushed_authorization_requests field; the server-wide setting is a floor
that a per-client value never relaxes.
RFC 9700 gates (COMPLIANT_BCP_RFC9700_*)
Each of these booleans covers one RFC 9700
(OAuth 2.0 Security Best Current Practice) recommendation: True enforces the
compliant behavior, False (the current default) preserves the legacy behavior. The
request-time gates emit a DeprecationWarning each time the discouraged behavior is
used while the gate is False; the two ambient gates
(COMPLIANT_BCP_RFC9700_AUTHZ_RESPONSE_ISS and COMPLIANT_BCP_RFC9700_TOKEN_STORAGE)
would fire on every request and are instead surfaced by manage.py check --deploy.
The defaults are scheduled to flip to True in the 4.0 release. See RFC 9700 Security Best Current Practice
for the full mapping and a copy/paste compliant settings block.
COMPLIANT_BCP_RFC9700_IMPLICIT_GRANTDefault: False. When True, the implicit grant (token / id_token
response types) is rejected and no longer advertised (RFC 9700 §2.1.2). implicit
stays in grant_types_supported while a hybrid response type is still advertised,
since hybrid response types need it and are not rejected by this setting.
COMPLIANT_BCP_RFC9700_PASSWORD_GRANTDefault: False. When True, the resource owner password credentials grant
is rejected and no longer advertised (RFC 9700 §2.4).
COMPLIANT_BCP_RFC9700_PKCE_METHODDefault: False. When True, the PKCE plain code_challenge_method is
rejected and dropped from metadata; only S256 is accepted (RFC 9700 §2.1.1).
COMPLIANT_BCP_RFC9700_ACCESS_TOKEN_TRANSPORTDefault: False. When True, access tokens presented in the URI query
string are rejected at the resource server (RFC 9700 §4.3.2).
COMPLIANT_BCP_RFC9700_AUTHZ_RESPONSE_ISSDefault: False. When True, the
RFC 9207 iss parameter is
added to every authorization response, including error redirects, and advertised
in metadata (RFC 9700 §4.4).
COMPLIANT_BCP_RFC9700_TOKEN_STORAGEDefault: False. When True, access and refresh tokens are stored hashed
rather than in cleartext (RFC 9700 §4). Incompatible with a non-zero
REFRESH_TOKEN_GRACE_PERIOD_SECONDS (manage.py check --deploy raises
oauth2_provider.E001).
The remaining gates are config-validation gates: they do not change runtime behavior
or replace the settings they cover — the canonical setting stays in control. They set
the severity of the manage.py check --deploy message when the covered setting is on
a non-compliant value: False (default) → Warning, True → Error.
COMPLIANT_BCP_RFC9700_REFRESH_TOKENDefault: False. Flags REFRESH_TOKEN_REUSE_PROTECTION = False
(RFC 9700 §4.14.2) as W007 / E002.
COMPLIANT_BCP_RFC9700_REDIRECT_URI_SCHEMEDefault: False. Flags "http" in ALLOWED_REDIRECT_URI_SCHEMES
(RFC 9700 §2.1) as W008 / E003.
COMPLIANT_BCP_RFC9700_REDIRECT_URI_MATCHINGDefault: False. Flags ALLOW_URI_WILDCARDS = True (RFC 9700 §4.1.1) as
W009 / E004.
COMPLIANT_BCP_RFC9700_PKCE_REQUIREDDefault: False. Flags PKCE_REQUIRED = False (RFC 9700 §2.1.1) as W010 /
E005. A callable PKCE_REQUIRED (per-client policy) is not flagged.
OAUTH2_RESPONSE_TYPES_SUPPORTED
Default: ["code", "token"]
The response types advertised by the OAuth 2.0 Authorization Server Metadata endpoint.
A multi-valued response_type is an order-independent set (RFC6749 Section 6749#section-3.1.1,
OAuth 2.0 Multiple Response Type Encoding Practices §4),
so an entry may list its values in any order: the authorization endpoint maps
"token id_token" to the "id_token token" that oauthlib registers. An entry the
configured server does not register in any order is never served as advertised – with
the stock validator it is rejected with unsupported_response_type, or with
unauthorized_client when the entry contains code. manage.py check --deploy
reports any such entry as oauth2_provider.W013.
OAUTH2_GRANT_TYPES_SUPPORTED
Default:
[
"authorization_code",
"implicit",
"password",
"client_credentials",
"refresh_token",
"urn:ietf:params:oauth:grant-type:device_code",
]
The grant types advertised as grant_types_supported by the OAuth 2.0 Authorization Server Metadata
endpoint and, when OpenID Connect is enabled, by the OpenID Connect discovery document
(/.well-known/openid-configuration). With COMPLIANT_BCP_RFC9700_IMPLICIT_GRANT or
COMPLIANT_BCP_RFC9700_PASSWORD_GRANT enabled, implicit or password is left out;
implicit stays while a hybrid response type is still advertised, since those need it.
OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED
Default: ["client_secret_post", "client_secret_basic"]
The token endpoint authentication methods advertised by the OAuth 2.0 Authorization Server Metadata endpoint.
Add "private_key_jwt" and/or "client_secret_jwt" to advertise RFC 7523 JWT client
authentication; the metadata document then also emits the matching
*_auth_signing_alg_values_supported fields. Advertising "private_key_jwt" here (and, with
OpenID Connect enabled, in OIDC_TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED as well) is also what lets
CIMD register a client whose metadata document chooses that method.
OpenID Connect Provider settings
These settings configure the OpenID Connect Provider (OP) — the identity layer on
top of the Authorization Server. See OpenID Connect for the full guide.
OIDC_ENABLED
Default: False
Whether or not OpenID Connect support is enabled.
OIDC_SERVER_CLASS
Default: "oauth2_provider.authorization_server.oidc.server.Server"
The import string for the OIDC server_class used when OIDC_ENABLED is
True and OAUTH2_SERVER_CLASS is not explicitly configured.
The default derives from oauthlib.openid.Server and adds a UserInfo endpoint that
can sign its response (see Signed UserInfo responses). A custom class should derive from
it. With
one that derives from oauthlib.openid.Server directly, UserInfo is always plain
JSON: signing is not advertised, registration refuses userinfo_signed_response_alg,
and, when an OIDC_RSA_PRIVATE_KEY is configured, the oauth2_provider.I001 system
check reports it.
OIDC_RSA_PRIVATE_KEY
Default: ""
The RSA private key used to sign OIDC ID tokens. If not set, OIDC is disabled.
The ID Tokens of RS256 applications presented to the server are verified with this
key too: as bearer tokens on a protected resource, and as the id_token_hint of
RP-Initiated Logout. If it is removed, or replaced by something that is not a usable
key, while RS256 applications exist, the server rejects those tokens and logs an
error on the oauth2_provider logger for each one.
OIDC_RSA_PRIVATE_KEYS_INACTIVE
Default: []
An array of inactive RSA private keys. These keys are not used to sign tokens,
but are published in the jwks_uri location.
This is useful for providing a smooth transition during key rotation.
OIDC_RSA_PRIVATE_KEY can be replaced, and recently decommissioned keys
should be retained in this inactive list.
OIDC_JWKS_MAX_AGE_SECONDS
Default: 3600
The max-age value for the Cache-Control header on jwks_uri.
This enables the verifier to safely cache the JWK Set and not have to re-download
the document for every token.
OIDC_USERINFO_ENDPOINT
Default: ""
The url of the userinfo endpoint. Used to advertise the location of the
endpoint in the OIDC discovery metadata. Changing this does not change the URL
that django-oauth-toolkit adds for the userinfo endpoint, so if you change
this you must also provide the service at that endpoint.
If unset, the default location is used, eg if django-oauth-toolkit is
mounted at /o/, it will be <server-address>/o/userinfo/.
OIDC_USERINFO_CORS_ENABLED
Default: True
Whether the userinfo endpoint answers CORS preflight (OPTIONS) requests and sends
Access-Control-Allow-Origin: * on its responses, so browser-based (JavaScript) clients can
call it cross-origin without extra middleware. OpenID Connect Core 1.0 section 5.3 says the endpoint SHOULD
support CORS.
The origin cannot be narrowed to the calling application’s Allowed origins: the preflight
request carries no access token, so there is no application to resolve at that point. The
wildcard is safe because claims are still only released to a caller holding a valid access
token, and Access-Control-Allow-Credentials is never sent, so browsers will not attach
ambient cookies to the request.
Set this to False to send no CORS headers from the userinfo endpoint at all, for instance if
you prefer to control them with CORS middleware such as django-cors-headers. Note that when that middleware is
installed it answers every CORS preflight before any view runs, so the userinfo path has to be
allowed there too even when this setting is left on.
OIDC_USERINFO_JWT_EXPIRE_SECONDS
Default: None
The lifetime of a signed UserInfo response (see Signed UserInfo responses), as a positive number
of seconds or a datetime.timedelta. When set, the JWT carries an exp claim that many
seconds after its iat. Any other value is reported by manage.py check as
oauth2_provider.E007. None leaves
exp out: OpenID Connect Core 1.0 section 5.3.2 does not require it,
and the response is only ever returned directly to the client that asked for it.
OIDC_COMPLIANT_SCOPE_CLAIMS
Default: False
Controls where the claims requested through the profile, email, address and
phone scope values are returned. OpenID Connect Core 1.0 section 5.4 says they are returned
from the UserInfo endpoint when the response type issues an access token, and in the ID Token
only when no access token is issued (response_type=id_token).
When True, those claims are left out of every ID Token except the one issued for
response_type=id_token, and are returned from the UserInfo endpoint. sub and claims
gated by custom scopes are not affected. The scope values that are treated this way are listed
in OAuth2Validator.oidc_userinfo_only_scopes.
When False (the legacy behavior), the claims are returned in both the ID Token and the
UserInfo response. This default is scheduled to change to True in the 4.0 release; set it
to True now to adopt the compliant behavior early. Relying parties that read profile or
email claims from the ID Token must call the UserInfo endpoint instead.
OIDC_CLAIMS_PARAMETER_ENABLED
Default: False
Honours the claims authorization request parameter of OpenID Connect Core 1.0 section 5.5, which lets a client
request individual claims for the ID Token and for the UserInfo response, in addition to the
claims its scopes request. See Requesting individual claims with the claims parameter for how claims are selected.
When True, a malformed claims value is refused with invalid_request, the requested
claims are listed on the consent page and stored on the access token (AccessToken.claims)
for the UserInfo endpoint and refreshes, and discovery publishes
claims_parameter_supported: true.
When False, the parameter is ignored as before and discovery publishes
claims_parameter_supported: false. The authorization code still records the requested
claims, as it always has, so a code issued just before the setting is enabled and redeemed
just after (within AUTHORIZATION_CODE_EXPIRE_SECONDS) is honoured without the consent
page having listed them.
OIDC_ISS_ENDPOINT
Default: ""
The URL of the issuer that is used in the ID token JWT and advertised in the
OIDC discovery metadata. Clients use this location to retrieve the OIDC
discovery metadata from OIDC_ISS_ENDPOINT +
/.well-known/openid-configuration.
If unset, the default location is used, eg if django-oauth-toolkit is
mounted at /o, it will be <server-address>/o.
OIDC_RESPONSE_TYPES_SUPPORTED
Default:
[
"code",
"token",
"id_token",
"id_token token",
"code token",
"code id_token",
"code id_token token",
]
The response types that are advertised to be supported by this server. Only consulted
when OIDC_ENABLED is True. As with OAUTH2_RESPONSE_TYPES_SUPPORTED, a
multi-valued entry may list its values in any order, and manage.py check --deploy
reports entries that cannot be served as oauth2_provider.W013.
OIDC_SUBJECT_TYPES_SUPPORTED
Default: ["public"]
The subject types that are advertised to be supported by this server.
OIDC_ACR_VALUES_SUPPORTED
Default: []
The Authentication Context Class References published as acr_values_supported
in the OpenID Connect discovery document, which leaves the field out when the list
is empty. List the values your validator’s get_acr can return in the acr
claim of the ID Token; see Reporting the authentication context (acr).
OIDC_TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED
Default: ["client_secret_post", "client_secret_basic"]
The authentication methods that are advertised to be supported by this server. Add
"private_key_jwt" and/or "client_secret_jwt" to advertise RFC 7523 JWT client
authentication; the discovery document then also emits
token_endpoint_auth_signing_alg_values_supported. With OpenID Connect enabled, CIMD
registers a client whose metadata document chooses "private_key_jwt" only when it is advertised
both here and in OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED.
OIDC_REQUEST_OBJECTS_ENABLED
Default: False
Whether the authorization endpoint accepts request objects (OpenID
Connect Core 1.0 section 6) in the request and request_uri parameters. Only takes effect
with OIDC_ENABLED. When off, such requests are answered with request_not_supported or
request_uri_not_supported. Pushed authorization request URIs are resolved either way.
OIDC_REQUEST_OBJECT_SIGNING_ALGS
Default: ["none", "RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "PS256", "PS384", "PS512"]
The JWS algorithms accepted for request objects (OpenID Connect Core
1.0 section 6), and the values a client may register as request_object_signing_alg. "none"
accepts unsigned request objects; remove it to require signed ones. Signed request objects are
verified with the client’s registered client_jwks or client_jwks_uri, so only asymmetric
algorithms are supported. Published as request_object_signing_alg_values_supported when request
objects are enabled.
OIDC_REQUEST_URI_FETCHER
Default: "oauth2_provider.authorization_server.oidc.request_objects.SafeRequestURIFetcher"
Import path of the class that fetches the request object a request_uri refers to. Its instances
must have a fetch(request_uri) method returning the document as a string and raising
oauth2_provider.authorization_server.oidc.request_objects.RequestURIFetchError on failure. The
default only fetches https URLs on public addresses, without following redirects; replace it
only to change the transport, for example for a test environment.
OIDC_REQUEST_URI_FETCH_TIMEOUT_SECONDS
Default: 5
Total time allowed for fetching a request_uri, across every address its host resolves to.
OIDC_REQUEST_URI_FAILURE_BACKOFF_SECONDS
Default: 60
How long a request_uri that could not be fetched is answered with invalid_request_uri
without fetching it again (the fragment is ignored). Kept in the default Django cache, so
deployments running multiple instances need a shared cache backend for it to apply across them.
0 or None disables it.
OIDC_REQUEST_OBJECT_STORE_LIFETIME_SECONDS
Default: 60
How long, in seconds, a resolved request object stays stored on the server for the authorization
endpoint to continue with it (see Request objects). A user who is not logged in has to
register within this time. Sending the user to log in, because they are not logged in or because
the authorization request asks for a login (prompt=login or an elapsed max_age), stores
the request again for PAR_REQUEST_URI_LIFETIME_SECONDS, as for a pushed authorization request.
OIDC_REQUEST_URI_MAX_CONCURRENT_FETCHES
Default: 10
How many request_uri fetches may run at once in a process. A request arriving while that many
are in flight is answered with invalid_request_uri at once rather than waiting, since fetches
run before the end-user logs in. 0 or None disables the cap.
OIDC_REQUEST_URI_MAX_SIZE
Default: 65536
Maximum size, in bytes, of the request object a request_uri refers to. A valid request object
is kept on the server, so only this limit bounds it, not the length of any URL; see
Request objects.
OIDC_RP_INITIATED_REGISTRATION_ENABLED
Default: False
Whether to allow the Relying Party (RP) to direct a user to an OpenID
Provider (OP) to create a new account rather than authenticate with an
existing one, per OpenID Connect Prompt Create 1.0.
This is done by adding a prompt=create parameter to the
authorization request. When enabled,
OIDC_RP_INITIATED_REGISTRATION_URL must also be set.
Only unauthenticated users are redirected to registration. For a user
with an existing authenticated session, create is a no-op and the
authorization request proceeds as if it was not present — matching 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. prompt=create login.
OIDC_RP_INITIATED_REGISTRATION_URL
Default: None
Where users are sent to create an account when an authorization request
contains prompt=create. Like LOGIN_URL, the value is resolved with
django.shortcuts.resolve_url() and so accepts a URL pattern name, a
path, or an absolute URL. For example, with django-allauth:
OAUTH2_PROVIDER = {
# ...
"OIDC_RP_INITIATED_REGISTRATION_ENABLED": True,
"OIDC_RP_INITIATED_REGISTRATION_URL": "account_signup",
}
The registration page receives a next query parameter pointing back to
the authorization endpoint, and must redirect the user there after a
successful registration so the OAuth flow can complete.
This setting is required when OIDC_RP_INITIATED_REGISTRATION_ENABLED is
True: if it is unset or cannot be resolved, ImproperlyConfigured is
raised when a prompt=create request is received.
OIDC_RP_INITIATED_LOGOUT_ALWAYS_PROMPT
Default: True
Whether to always prompt the Resource Owner (End User) to confirm a logout requested by a
Client (Relying Party). If it is disabled the Resource Owner (End User) will only be prompted if required by the standard.
OIDC_RP_INITIATED_LOGOUT_STRICT_REDIRECT_URIS
Default: False
Enable this setting to require https in post logout redirect URIs. http is only allowed when a Client is confidential.
While RP-Initiated Logout is enabled (OIDC_ENABLED and OIDC_RP_INITIATED_LOGOUT_ENABLED),
the rule is applied both when a logout is requested and by Application.clean(), so the admin, the
application management views, createapplication and
Dynamic Client Registration refuse an http entry in a
non-confidential application’s post_logout_redirect_uris.
OIDC_RP_INITIATED_LOGOUT_ACCEPT_EXPIRED_TOKENS
Default: True
Whether expired ID tokens are accepted for RP-Initiated Logout. The token must still be
signed by the OP, carry a matching iss claim, and resolve to a stored IDToken;
only the exp and nbf claims are skipped.
The default is True because OpenID Connect RP-Initiated Logout 1.0 treats id_token_hint
as a previously issued ID token, used only as a hint about which session to end. Logout
frequently happens long after the ID token’s (typically short) exp, so rejecting an
expired hint would break the normal logout flow. Set this to False if you additionally
want to require that the id_token_hint is still within its validity period.
OIDC_RP_INITIATED_LOGOUT_DELETE_TOKENS
Default: True
Whether to delete the access, refresh and ID tokens of the user that is being logged out.
The types of applications for which tokens are deleted can be customized with RPInitiatedLogoutView.token_types_to_delete.
The default is to delete the tokens of all applications if this flag is enabled.
Resource Server settings
RESOURCE_SERVER_INTROSPECTION_URL
The introspection endpoint for validating token remotely (RFC7662). This URL requires an
authorization token (RESOURCE_SERVER_AUTH_TOKEN), HTTP Basic Auth client credentials
(RESOURCE_SERVER_INTROSPECTION_CREDENTIALS), or an RFC 7523 client assertion configuration
(RESOURCE_SERVER_INTROSPECTION_JWT_*).
RESOURCE_SERVER_AUTH_TOKEN
The bearer token to authenticate the introspection request towards the introspection endpoint (RFC7662).
RESOURCE_SERVER_INTROSPECTION_CREDENTIALS
The HTTP Basic Auth Client_ID and Client_Secret to authenticate the introspection request
towards the introspect endpoint (RFC7662) as a tuple: (client_id, client_secret).
RESOURCE_SERVER_INTROSPECTION_JWT_CLIENT_ID
Default: None
The client_id to authenticate the introspection request with an RFC 7523 private_key_jwt
client assertion (see JWT client authentication (RFC 7523)). All of RESOURCE_SERVER_INTROSPECTION_JWT_CLIENT_ID,
RESOURCE_SERVER_INTROSPECTION_JWT_PRIVATE_KEY and RESOURCE_SERVER_INTROSPECTION_JWT_AUDIENCE
must be set; RESOURCE_SERVER_AUTH_TOKEN and RESOURCE_SERVER_INTROSPECTION_CREDENTIALS take
precedence when configured. A fresh assertion (new jti, short expiry) is generated per request.
RESOURCE_SERVER_INTROSPECTION_JWT_PRIVATE_KEY
Default: None
The signing key for the introspection client assertion: a private-key PEM string or a JWK JSON
string.
RESOURCE_SERVER_INTROSPECTION_JWT_AUDIENCE
Default: None
The aud claim for the introspection client assertion — the remote authorization server’s
issuer or its introspection endpoint URL, per the remote server’s policy.
RESOURCE_SERVER_INTROSPECTION_JWT_ALG
Default: None
The JWS algorithm for the introspection client assertion. None infers it from the key type
(RSA → RS256, EC → ES256/ES384/ES512 by curve).
RESOURCE_SERVER_INTROSPECTION_JWT_LIFETIME
Default: 60
Lifetime in seconds of each generated introspection client assertion.
RESOURCE_SERVER_INTROSPECTION_JWT_KID
Default: None
Optional kid header for the introspection client assertion; defaults to the signing key’s own
kid when it has one.
RESOURCE_SERVER_INTROSPECTION_TIMEOUT_SECONDS
Default: 5
The timeout in seconds for the HTTP request to the remote introspection endpoint. Every request
carrying a bearer token goes through this call when RESOURCE_SERVER_INTROSPECTION_URL is set, so
without a bound an authorization server that accepts the connection and then stalls would hold a
worker per inbound request. On timeout the token is treated as invalid, as for any other failed
introspection request.
RESOURCE_SERVER_TOKEN_CACHING_SECONDS
The number of seconds an authorization token received from the introspection endpoint remains valid.
If the expire time of the received token is less than RESOURCE_SERVER_TOKEN_CACHING_SECONDS the expire time
will be used.
RESOURCE_SERVER_TOKEN_RESOURCE_VALIDATOR
Default: "oauth2_provider.resource_server.validators.validate_resource_as_url_prefix"
(the pre-4.0 alias oauth2_provider.oauth2_validators.validate_resource_as_url_prefix still resolves).
A callable that validates whether an access token’s audience (RFC 8707 resource indicators) matches
a request URI. The callable receives (request_uri, audiences) where request_uri is a string
and audiences is a list of audience URIs from the token. Returns True if the token
is authorized for the request, False otherwise.
The default validator uses prefix matching: a token with audience https://api.example.com/v1
will accept requests to https://api.example.com/v1/users but reject https://api.example.com/v2.
The default validator expects both the request URI and the audience values to be absolute URIs
with a scheme and host, without userinfo or fragment components, because it compares
(scheme, host, port) and then the path. A query component is permitted on resource indicators
(RFC 8707 allows one) but plays no part in matching: the request URI is compared with its query
string stripped. Other absolute-URI forms, such as URNs, never match. Supporting them requires
both a custom validator here (for matching on the resource server) and a custom
OAUTH2_VALIDATOR_CLASS overriding _validate_resource_uris() (the authorization server
rejects authority-less URIs at issuance).
To use exact matching instead:
def exact_match_validator(request_uri, audiences):
if not audiences:
return True # Unrestricted token
return request_uri in audiences
OAUTH2_PROVIDER = {
'RESOURCE_SERVER_TOKEN_RESOURCE_VALIDATOR': 'myapp.validators.exact_match_validator',
}
Set to None to disable automatic audience validation entirely.
AUTHENTICATION_SERVER_EXP_TIME_ZONE
Deprecated since version 3.3.1: This setting is deprecated and will be removed in a future release.
Token introspection exp (expiration) values are Unix timestamps and are interpreted as UTC per
RFC6749 Section 7662 and RFC6749 Section 7519. For backwards compatibility, setting this to a non-UTC time zone keeps
the previous workaround behavior of reinterpreting the exp wall-clock time as being in the
configured time zone, but configuring it now emits a DeprecationWarning.
OAUTH2_PROTECTED_RESOURCE_IDENTIFIER
Default: ""
The resource identifier advertised by the OAuth 2.0 Protected Resource Metadata
endpoint. When empty it is derived from the request URL.
OAUTH2_PROTECTED_RESOURCE_AUTHORIZATION_SERVERS
Default: []
The authorization_servers advertised by the OAuth 2.0 Protected Resource Metadata
endpoint. When empty, this server’s own authorization-server issuer is used
(OIDC_ISS_ENDPOINT or the RFC 8414 route).