OpenID Connect 1.0¶
This part of the documentation covers the specification of OpenID Connect. Learn how to use it in Flask OIDC Provider and Django OIDC Provider.
OpenID Grants¶
- class authlib.oidc.core.grants.OpenIDToken¶
Bases:
object
- generate_user_info(user, scope)¶
Provide user information for the given scope. Developers MUST implement this method in subclass, e.g.:
from authlib.oidc.core import UserInfo def generate_user_info(self, user, scope): user_info = UserInfo(sub=user.id, name=user.name) if "email" in scope: user_info["email"] = user.email return user_info
- Parameters:
user – user instance
scope – scope of the token
- Returns:
authlib.oidc.core.UserInfo
instance
- get_audiences(request)¶
Parse aud value for id_token, default value is client id. Developers MAY rewrite this method to provide a customized audience value.
- get_jwt_config(grant)¶
Get the JWT configuration for OpenIDCode extension. The JWT configuration will be used to generate
id_token
. Developers MUST implement this method in subclass, e.g.:def get_jwt_config(self, grant): return { "key": read_private_key_file(key_path), "alg": "RS256", "iss": "issuer-identity", "exp": 3600, }
- Parameters:
grant – AuthorizationCodeGrant instance
- Returns:
dict
- class authlib.oidc.core.grants.OpenIDCode(require_nonce=False)¶
Bases:
OpenIDToken
An extension from OpenID Connect for “grant_type=code” request. Developers MUST implement the missing methods:
class MyOpenIDCode(OpenIDCode): def get_jwt_config(self, grant): return {...} def exists_nonce(self, nonce, request): return check_if_nonce_in_cache(request.payload.client_id, nonce) def generate_user_info(self, user, scope): return {...}
The register this extension with AuthorizationCodeGrant:
authorization_server.register_grant( AuthorizationCodeGrant, extensions=[MyOpenIDCode()] )
- exists_nonce(nonce, request)¶
Check if the given nonce is existing in your database. Developers MUST implement this method in subclass, e.g.:
def exists_nonce(self, nonce, request): exists = AuthorizationCode.query.filter_by( client_id=request.payload.client_id, nonce=nonce ).first() return bool(exists)
- Parameters:
nonce – A string of “nonce” parameter in request
request – OAuth2Request instance
- Returns:
Boolean
- class authlib.oidc.core.grants.OpenIDImplicitGrant(request: OAuth2Request, server)¶
Bases:
ImplicitGrant
- exists_nonce(nonce, request)¶
Check if the given nonce is existing in your database. Developers should implement this method in subclass, e.g.:
def exists_nonce(self, nonce, request): exists = AuthorizationCode.query.filter_by( client_id=request.payload.client_id, nonce=nonce ).first() return bool(exists)
- Parameters:
nonce – A string of “nonce” parameter in request
request – OAuth2Request instance
- Returns:
Boolean
- generate_user_info(user, scope)¶
Provide user information for the given scope. Developers MUST implement this method in subclass, e.g.:
from authlib.oidc.core import UserInfo def generate_user_info(self, user, scope): user_info = UserInfo(sub=user.id, name=user.name) if "email" in scope: user_info["email"] = user.email return user_info
- Parameters:
user – user instance
scope – scope of the token
- Returns:
authlib.oidc.core.UserInfo
instance
- get_audiences(request)¶
Parse aud value for id_token, default value is client id. Developers MAY rewrite this method to provide a customized audience value.
- get_jwt_config()¶
Get the JWT configuration for OpenIDImplicitGrant. The JWT configuration will be used to generate
id_token
. Developers MUST implement this method in subclass, e.g.:def get_jwt_config(self): return { "key": read_private_key_file(key_path), "alg": "RS256", "iss": "issuer-identity", "exp": 3600, }
- Returns:
dict
- class authlib.oidc.core.grants.OpenIDHybridGrant(request: OAuth2Request, server)¶
Bases:
OpenIDImplicitGrant
- AUTHORIZATION_CODE_LENGTH = 48¶
Generated “code” length
- GRANT_TYPE = 'code'¶
Designed for which “grant_type”
- generate_authorization_code()¶
“The method to generate “code” value for authorization code data. Developers may rewrite this method, or customize the code length with:
class MyAuthorizationCodeGrant(AuthorizationCodeGrant): AUTHORIZATION_CODE_LENGTH = 32 # default is 48
- save_authorization_code(code, request)¶
Save authorization_code for later use. Developers MUST implement it in subclass. Here is an example:
def save_authorization_code(self, code, request): client = request.client auth_code = AuthorizationCode( code=code, client_id=client.client_id, redirect_uri=request.payload.redirect_uri, scope=request.payload.scope, nonce=request.payload.data.get("nonce"), user_id=request.user.id, ) auth_code.save()
OpenID Endpoints¶
- class authlib.oidc.core.UserInfoEndpoint(server: AuthorizationServer | None = None, resource_protector: ResourceProtector | None = None)¶
Bases:
object
OpenID Connect Core UserInfo Endpoint.
This endpoint returns information about a given user, as a JSON payload or as a JWT. It must be subclassed and a few methods needs to be manually implemented:
class UserInfoEndpoint(oidc.core.UserInfoEndpoint): def get_issuer(self): return "https://auth.example" def generate_user_info(self, user, scope): return UserInfo( sub=user.id, name=user.name, ... ).filter(scope) def resolve_private_key(self): return server_private_jwk_set()
It is also needed to pass a
ResourceProtector
instance with a registeredTokenValidator
at initialization, so the access to the endpoint can be restricter to valid token bearers:resource_protector = ResourceProtector() resource_protector.register_token_validator(BearerTokenValidator()) server.register_endpoint( UserInfoEndpoint(resource_protector=resource_protector) )
And then you can plug the endpoint to your application:
@app.route("/oauth/userinfo", methods=["GET", "POST"]) def userinfo(): return server.create_endpoint_response("userinfo")
- generate_user_info(user, scope: str) UserInfo ¶
Generate a
UserInfo
object for an user:def generate_user_info(self, user, scope: str) -> UserInfo: return UserInfo( given_name=user.given_name, family_name=user.last_name, email=user.email, ... ).filter(scope)
This method must be implemented by developers.
- get_issuer() str ¶
The OP’s Issuer Identifier URL.
The value is used to fill the
iss
claim that is mandatory in signed userinfo:def get_issuer(self) -> str: return "https://auth.example"
This method must be implemented by developers to support JWT userinfo.
- resolve_private_key()¶
Return the server JSON Web Key Set.
This is used to sign userinfo payloads:
def resolve_private_key(self): return server_private_jwk_set()
This method must be implemented by developers to support JWT userinfo signing.
OpenID Claims¶
- class authlib.oidc.core.claims.IDToken(payload, header, options=None, params=None)¶
Bases:
JWTClaims
- validate(now=None, leeway=0)¶
Validate everything in claims payload.
- validate_acr()¶
OPTIONAL. Authentication Context Class Reference. String specifying an Authentication Context Class Reference value that identifies the Authentication Context Class that the authentication performed satisfied. The value “0” indicates the End-User authentication did not meet the requirements of ISO/IEC 29115 level 1. Authentication using a long-lived browser cookie, for instance, is one example where the use of “level 0” is appropriate. Authentications with level 0 SHOULD NOT be used to authorize access to any resource of any monetary value. An absolute URI or an RFC 6711 registered name SHOULD be used as the acr value; registered names MUST NOT be used with a different meaning than that which is registered. Parties using this claim will need to agree upon the meanings of the values used, which may be context-specific. The acr value is a case sensitive string.
- validate_amr()¶
OPTIONAL. Authentication Methods References. JSON array of strings that are identifiers for authentication methods used in the authentication. For instance, values might indicate that both password and OTP authentication methods were used. The definition of particular values to be used in the amr Claim is beyond the scope of this specification. Parties using this claim will need to agree upon the meanings of the values used, which may be context-specific. The amr value is an array of case sensitive strings.
- validate_at_hash()¶
OPTIONAL. Access Token hash value. Its value is the base64url encoding of the left-most half of the hash of the octets of the ASCII representation of the access_token value, where the hash algorithm used is the hash algorithm used in the alg Header Parameter of the ID Token’s JOSE Header. For instance, if the alg is RS256, hash the access_token value with SHA-256, then take the left-most 128 bits and base64url encode them. The at_hash value is a case sensitive string.
- validate_auth_time()¶
Time when the End-User authentication occurred. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time. When a max_age request is made or when auth_time is requested as an Essential Claim, then this Claim is REQUIRED; otherwise, its inclusion is OPTIONAL.
- validate_azp()¶
OPTIONAL. Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value.
- validate_nonce()¶
String value used to associate a Client session with an ID Token, and to mitigate replay attacks. The value is passed through unmodified from the Authentication Request to the ID Token. If present in the ID Token, Clients MUST verify that the nonce Claim Value is equal to the value of the nonce parameter sent in the Authentication Request. If present in the Authentication Request, Authorization Servers MUST include a nonce Claim in the ID Token with the Claim Value being the nonce value sent in the Authentication Request. Authorization Servers SHOULD perform no other processing on nonce values used. The nonce value is a case sensitive string.
- class authlib.oidc.core.claims.CodeIDToken(payload, header, options=None, params=None)¶
Bases:
IDToken
- class authlib.oidc.core.claims.ImplicitIDToken(payload, header, options=None, params=None)¶
Bases:
IDToken
- validate_at_hash()¶
If the ID Token is issued from the Authorization Endpoint with an access_token value, which is the case for the response_type value id_token token, this is REQUIRED; it MAY NOT be used when no Access Token is issued, which is the case for the response_type value id_token.
- class authlib.oidc.core.claims.HybridIDToken(payload, header, options=None, params=None)¶
Bases:
ImplicitIDToken
- validate(now=None, leeway=0)¶
Validate everything in claims payload.
- validate_c_hash()¶
Code hash value. Its value is the base64url encoding of the left-most half of the hash of the octets of the ASCII representation of the code value, where the hash algorithm used is the hash algorithm used in the alg Header Parameter of the ID Token’s JOSE Header. For instance, if the alg is HS512, hash the code value with SHA-512, then take the left-most 256 bits and base64url encode them. The c_hash value is a case sensitive string. If the ID Token is issued from the Authorization Endpoint with a code, which is the case for the response_type values code id_token and code id_token token, this is REQUIRED; otherwise, its inclusion is OPTIONAL.
- class authlib.oidc.core.claims.UserInfo¶
The standard claims of a UserInfo object. Defined per Section 5.1.
- REGISTERED_CLAIMS = ['sub', 'name', 'given_name', 'family_name', 'middle_name', 'nickname', 'preferred_username', 'profile', 'picture', 'website', 'email', 'email_verified', 'gender', 'birthdate', 'zoneinfo', 'locale', 'phone_number', 'phone_number_verified', 'address', 'updated_at']¶
registered claims that UserInfo supports
- filter(scope: str)¶
Return a new UserInfo object containing only the claims matching the scope passed in parameter.
Dynamic client registration¶
The OpenID Connect Dynamic Client Registration implementation is based on RFC7591: OAuth 2.0 Dynamic Client Registration Protocol. To handle OIDC client registration, you can extend your RFC7591 registration endpoint with OIDC claims:
from authlib.oauth2.rfc7591 import ClientMetadataClaims as OAuth2ClientMetadataClaims
from authlib.oauth2.rfc7591 import ClientRegistrationEndpoint
from authlib.oidc.registration import ClientMetadataClaims as OIDCClientMetadataClaims
class MyClientRegistrationEndpoint(ClientRegistrationEndpoint):
...
def get_server_metadata(self):
...
authorization_server.register_endpoint(
MyClientRegistrationEndpoint(
claims_classes=[OAuth2ClientMetadataClaims, OIDCClientMetadataClaims]
)
)
- class authlib.oidc.registration.ClientMetadataClaims(payload, header, options=None, params=None)¶
Bases:
BaseClaims
- classmethod get_claims_options(metadata)¶
Generate claims options validation from Authorization Server metadata.
- validate_application_type()¶
Kind of the application.
The default, if omitted, is web. The defined values are native or web. Web Clients using the OAuth Implicit Grant Type MUST only register URLs using the https scheme as redirect_uris; they MUST NOT use localhost as the hostname. Native Clients MUST only register redirect_uris using custom URI schemes or loopback URLs using the http scheme; loopback URLs use localhost or the IP loopback literals 127.0.0.1 or [::1] as the hostname. Authorization Servers MAY place additional constraints on Native Clients. Authorization Servers MAY reject Redirection URI values using the http scheme, other than the loopback case for Native Clients. The Authorization Server MUST verify that all the registered redirect_uris conform to these constraints. This prevents sharing a Client ID across different types of Clients.
- validate_default_acr_values()¶
Default requested Authentication Context Class Reference values.
Array of strings that specifies the default acr values that the OP is being requested to use for processing requests from this Client, with the values appearing in order of preference. The Authentication Context Class satisfied by the authentication performed is returned as the acr Claim Value in the issued ID Token. The acr Claim is requested as a Voluntary Claim by this parameter. The acr_values_supported discovery element contains a list of the supported acr values supported by the OP. Values specified in the acr_values request parameter or an individual acr Claim request override these default values.
- validate_default_max_age()¶
Default Maximum Authentication Age.
Specifies that the End-User MUST be actively authenticated if the End-User was authenticated longer ago than the specified number of seconds. The max_age request parameter overrides this default value. If omitted, no default Maximum Authentication Age is specified.
- validate_id_token_encrypted_response_alg()¶
JWE alg algorithm [JWA] REQUIRED for encrypting the ID Token issued to this Client.
If this is requested, the response will be signed then encrypted, with the result being a Nested JWT, as defined in [JWT]. The default, if omitted, is that no encryption is performed.
- validate_id_token_encrypted_response_enc()¶
JWE enc algorithm [JWA] REQUIRED for encrypting the ID Token issued to this Client.
If id_token_encrypted_response_alg is specified, the default id_token_encrypted_response_enc value is A128CBC-HS256. When id_token_encrypted_response_enc is included, id_token_encrypted_response_alg MUST also be provided.
- validate_id_token_signed_response_alg()¶
JWS alg algorithm [JWA] REQUIRED for signing the ID Token issued to this Client.
The value none MUST NOT be used as the ID Token alg value unless the Client uses only Response Types that return no ID Token from the Authorization Endpoint (such as when only using the Authorization Code Flow). The default, if omitted, is RS256. The public key for validating the signature is provided by retrieving the JWK Set referenced by the jwks_uri element from OpenID Connect Discovery 1.0 [OpenID.Discovery].
- validate_initiate_login_uri()¶
RI using the https scheme that a third party can use to initiate a login by the RP, as specified in Section 4 of OpenID Connect Core 1.0 [OpenID.Core].
The URI MUST accept requests via both GET and POST. The Client MUST understand the login_hint and iss parameters and SHOULD support the target_link_uri parameter.
- validate_request_object_encryption_alg()¶
JWE [JWE] alg algorithm [JWA] the RP is declaring that it may use for encrypting Request Objects sent to the OP.
This parameter SHOULD be included when symmetric encryption will be used, since this signals to the OP that a client_secret value needs to be returned from which the symmetric key will be derived, that might not otherwise be returned. The RP MAY still use other supported encryption algorithms or send unencrypted Request Objects, even when this parameter is present. If both signing and encryption are requested, the Request Object will be signed then encrypted, with the result being a Nested JWT, as defined in [JWT]. The default, if omitted, is that the RP is not declaring whether it might encrypt any Request Objects.
- validate_request_object_encryption_enc()¶
JWE enc algorithm [JWA] the RP is declaring that it may use for encrypting Request Objects sent to the OP.
If request_object_encryption_alg is specified, the default request_object_encryption_enc value is A128CBC-HS256. When request_object_encryption_enc is included, request_object_encryption_alg MUST also be provided.
- validate_request_object_signing_alg()¶
JWS [JWS] alg algorithm [JWA] that MUST be used for signing Request Objects sent to the OP.
All Request Objects from this Client MUST be rejected, if not signed with this algorithm. Request Objects are described in Section 6.1 of OpenID Connect Core 1.0 [OpenID.Core]. This algorithm MUST be used both when the Request Object is passed by value (using the request parameter) and when it is passed by reference (using the request_uri parameter). Servers SHOULD support RS256. The value none MAY be used. The default, if omitted, is that any algorithm supported by the OP and the RP MAY be used.
- validate_request_uris()¶
Array of request_uri values that are pre-registered by the RP for use at the OP.
These URLs MUST use the https scheme unless the target Request Object is signed in a way that is verifiable by the OP. Servers MAY cache the contents of the files referenced by these URIs and not retrieve them at the time they are used in a request. OPs can require that request_uri values used be pre-registered with the require_request_uri_registration discovery parameter. If the contents of the request file could ever change, these URI values SHOULD include the base64url-encoded SHA-256 hash value of the file contents referenced by the URI as the value of the URI fragment. If the fragment value used for a URI changes, that signals the server that its cached value for that URI with the old fragment value is no longer valid.
- validate_require_auth_time()¶
Boolean value specifying whether the auth_time Claim in the ID Token is REQUIRED.
It is REQUIRED when the value is true. (If this is false, the auth_time Claim can still be dynamically requested as an individual Claim for the ID Token using the claims request parameter described in Section 5.5.1 of OpenID Connect Core 1.0 [OpenID.Core].) If omitted, the default value is false.
- validate_sector_identifier_uri()¶
URL using the https scheme to be used in calculating Pseudonymous Identifiers by the OP.
The URL references a file with a single JSON array of redirect_uri values. Please see Section 5. Providers that use pairwise sub (subject) values SHOULD utilize the sector_identifier_uri value provided in the Subject Identifier calculation for pairwise identifiers.
- validate_subject_type()¶
subject_type requested for responses to this Client.
The subject_types_supported discovery parameter contains a list of the supported subject_type values for the OP. Valid types include pairwise and public.
- validate_token_endpoint_auth_signing_alg()¶
JWS [JWS] alg algorithm [JWA] that MUST be used for signing the JWT [JWT] used to authenticate the Client at the Token Endpoint for the private_key_jwt and client_secret_jwt authentication methods.
All Token Requests using these authentication methods from this Client MUST be rejected, if the JWT is not signed with this algorithm. Servers SHOULD support RS256. The value none MUST NOT be used. The default, if omitted, is that any algorithm supported by the OP and the RP MAY be used.
- validate_userinfo_encrypted_response_alg()¶
JWE [JWE] alg algorithm [JWA] REQUIRED for encrypting UserInfo Responses.
If both signing and encryption are requested, the response will be signed then encrypted, with the result being a Nested JWT, as defined in [JWT]. The default, if omitted, is that no encryption is performed.
- validate_userinfo_encrypted_response_enc()¶
JWE enc algorithm [JWA] REQUIRED for encrypting UserInfo Responses.
If userinfo_encrypted_response_alg is specified, the default userinfo_encrypted_response_enc value is A128CBC-HS256. When userinfo_encrypted_response_enc is included, userinfo_encrypted_response_alg MUST also be provided.
- validate_userinfo_signed_response_alg()¶
JWS alg algorithm [JWA] REQUIRED for signing UserInfo Responses.
If this is specified, the response will be JWT [JWT] serialized, and signed using JWS. The default, if omitted, is for the UserInfo Response to return the Claims as a UTF-8 [RFC3629] encoded JSON object using the application/json content-type.