API¶
Flask-pyoidc extension¶
-
class
flask_pyoidc.
OIDCAuthentication
(provider_configurations, app=None, redirect_uri_config=None)¶ OIDCAuthentication object for Flask extension.
Parameters: - provider_configurations (Mapping[str, ProviderConfiguration]) – provider configurations by name
- app (flask.app.Flask) – optional Flask app
- redirect_uri_config (RedirectUriConfig) – optional redirect URI config to use instead of ‘OIDC_REDIRECT_URI’ config parameter.
-
access_control
(provider_name: str, scopes_required: list = None)¶ This decorator serves dual purpose that is it can do both token based authorization and oidc based authentication. If your API needs to be accessible by either modes, use this decorator otherwise use either oidc_auth or token_auth.
Parameters: - provider_name (str) – Name of the provider registered with OIDCAuthorization.
- scopes_required (list, optional) – List of valid scopes associated with the endpoint.
Raises: Forbidden
– If accesss_token is invalid.Examples
auth = OIDCAuthentication({'default': provider_config}) @app.route('/') @auth.access_control(provider_name='default') def index(): ...
You can also specify scopes required by the endpoint:
@auth.access_control(provider_name='default', scopes_required=['read', 'write'])
-
introspect_token
(request, client, scopes: list = None) → Optional[oic.extension.message.TokenIntrospectionResponse]¶ RFC 7662: Token Introspection The Token Introspection extension defines a mechanism for resource servers to obtain information about access tokens. With this spec, resource servers can check the validity of access tokens, and find out other information such as which user and which scopes are associated with the token.
Parameters: - request (flask.Request) – flask request object.
- client (flask_pyoidc.pyoidc_facade.PyoidcFacade) – PyoidcFacade object contains metadata of the provider and client.
- scopes (list, optional) – Specify scopes required by your endpoint.
Returns: result – If access_token is valid or None if invalid.
Return type: TokenIntrospectionResponse or None
-
token_auth
(provider_name, scopes_required: list = None)¶ Token based authorization.
Parameters: - provider_name (str) – Name of the provider registered with OIDCAuthorization.
- scopes_required (list, optional) – List of valid scopes associated with the endpoint.
Raises: Unauthorized
– flask.abort(401) if authorization field is missing.Forbidden
– flask.abort(403) if access token is invalid.
Examples
auth = OIDCAuthentication({'default': provider_config}) @app.route('/') @auth.token_auth(provider_name='default') def index(): ...
You can also specify scopes required by the endpoint.
@auth.token_auth(provider_name='default', scopes_required=['read', 'write'])
-
valid_access_token
(force_refresh=False)¶ Returns a valid access token.
- If the current access token in the user session is valid, return that.
- If the current access token has expired and there is a refresh token in the user session, make a refresh token request and return the new access token.
- If the token refresh fails, either due to missing refresh token or token error response, return None.
Parameters: force_refresh (bool) – whether to perform the refresh token request even if the current access token is valid Returns: valid access token Return type: Option[str]
Configuration¶
-
class
flask_pyoidc.provider_configuration.
ClientMetadata
(client_id=None, client_secret=None, **kwargs)¶ Parameters: - client_id (str) – client identifier representing the client
- client_secret (str) – client secret to authenticate the client with the OP
- kwargs (dict) – key-value pairs
-
class
flask_pyoidc.provider_configuration.
ClientRegistrationInfo
(*args, **kwargs)¶ Parameters: - args (List[Tuple[String, String]]) – key-value pairs to store
- kwargs (Dict[string, string]) – key-value pairs to store
-
class
flask_pyoidc.provider_configuration.
OIDCData
(*args, **kwargs)¶ Basic OIDC data representation providing validation of required fields.
Parameters: - args (List[Tuple[String, String]]) – key-value pairs to store
- kwargs (Dict[string, string]) – key-value pairs to store
-
class
flask_pyoidc.provider_configuration.
ProviderConfiguration
(issuer=None, provider_metadata=None, userinfo_http_method='GET', client_registration_info=None, client_metadata=None, auth_request_params=None, session_refresh_interval_seconds=None, requests_session=None)¶ Metadata for communicating with an OpenID Connect Provider (OP).
-
auth_request_params
¶ Extra parameters, as key-value pairs, to include in the query parameters of the authentication request
Type: dict
-
registered_client_metadata
¶ The client metadata registered with the provider.
Type: ClientMetadata
-
requests_session
¶ Requests object to use when communicating with the provider.
Type: requests.Session
-
session_refresh_interval_seconds
¶ Number of seconds between updates of user data (tokens, user data, etc.) fetched from the provider. If None is specified, no silent updates should be made user data will be made.
Type: int
-
userinfo_endpoint_method
¶ HTTP method (“GET” or “POST”) to use when making the UserInfo Request. If None is specified, no UserInfo Request will be made.
Type: str
Parameters: - issuer (str) – OP Issuer Identifier. If this is specified discovery will be used to fetch the provider metadata, otherwise provider_metadata must be specified.
- provider_metadata (ProviderMetadata) – OP metadata,
- userinfo_http_method (Optional[str]) – HTTP method (GET or POST) to use when sending the UserInfo Request. If none is specified, no userinfo request will be sent.
- client_registration_info (ClientRegistrationInfo) – Client metadata to register your app dynamically with the provider. Either this or registered_client_metadata must be specified.
- client_metadata (ClientMetadata) – Client metadata if your app is statically registered with the provider. Either this or client_registration_info must be specified.
- auth_request_params (dict) – Extra parameters that should be included in the authentication request.
- session_refresh_interval_seconds (int) – Length of interval (in seconds) between attempted user data refreshes.
- requests_session (requests.Session) – custom requests object to allow for example retry handling, etc.
-
-
class
flask_pyoidc.provider_configuration.
ProviderMetadata
(issuer=None, authorization_endpoint=None, jwks_uri=None, token_endpoint=None, userinfo_endpoint=None, introspection_endpoint=None, registration_endpoint=None, **kwargs)¶ OpenID Providers have metadata describing their configuration.
Parameters: - issuer (str, Optional) – OP Issuer Identifier.
- authorization_endpoint (str, Optional) – URL of the OP’s OAuth 2.0 Authorization Endpoint.
- jwks_uri (str, Optional) – URL of the OP’s JSON Web Key Set [JWK] document.
- token_endpoint (str, Optional) – URL of the OP’s OAuth 2.0 Token Endpoint.
- userinfo_endpoint (str, Optional) – URL of the OP’s UserInfo Endpoint.
- introspection_endpoint (str, Optional) – URL of the OP’s token introspection endpoint.
- registration_endpoint (str, Optional) – URL of the OP’s Dynamic Client Registration Endpoint.
- **kwargs (dict, Optional) – Extra arguments to [OpenID Provider Metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata)
User session handling¶
-
exception
flask_pyoidc.user_session.
UninitialisedSession
¶
-
class
flask_pyoidc.user_session.
UserSession
(session_storage, provider_name=None)¶ Session object for user login state.
Wraps comparison of times necessary for session handling.
-
is_authenticated
()¶ flask_session is empty when the session hasn’t been initialised or has expired. Thus checking for existence of any item is enough to determine if we’re authenticated.
-
update
(*, access_token=None, expires_in=None, id_token=None, id_token_jwt=None, userinfo=None, refresh_token=None)¶ Parameters: - access_token (str) –
- expires_in (int) –
- id_token (Mapping[str, str]) –
- id_token_jwt (str) –
- userinfo (Mapping[str, str]) –
-
Internals¶
-
exception
flask_pyoidc.auth_response_handler.
AuthResponseErrorResponseError
(error_response)¶ Parameters: error_response (Mapping[str, str]) – OAuth error response containing ‘error’ and ‘error_description’
-
exception
flask_pyoidc.auth_response_handler.
AuthResponseMismatchingSubjectError
¶
-
exception
flask_pyoidc.auth_response_handler.
AuthResponseProcessError
¶
-
exception
flask_pyoidc.auth_response_handler.
AuthResponseUnexpectedStateError
¶
-
class
flask_pyoidc.auth_response_handler.
AuthenticationResult
(access_token, expires_in, id_token_claims, id_token_jwt, userinfo_claims, refresh_token)¶ Create new instance of AuthenticationResult(access_token, expires_in, id_token_claims, id_token_jwt, userinfo_claims, refresh_token)
-
access_token
¶ Alias for field number 0
-
expires_in
¶ Alias for field number 1
-
id_token_claims
¶ Alias for field number 2
-
id_token_jwt
¶ Alias for field number 3
-
refresh_token
¶ Alias for field number 5
-
userinfo_claims
¶ Alias for field number 4
-
-
exception
flask_pyoidc.auth_response_handler.
InvalidIdTokenError
¶
-
class
flask_pyoidc.pyoidc_facade.
PyoidcFacade
(provider_configuration, redirect_uri)¶ Wrapper around pyoidc library, coupled with config for a simplified API for flask-pyoidc.
Parameters: provider_configuration (flask_pyoidc.provider_configuration.ProviderConfiguration) – -
authentication_request
(state, nonce, extra_auth_params)¶ Parameters: - state (str) – authentication request parameter ‘state’
- nonce (str) – authentication request parameter ‘nonce’
- extra_auth_params (Mapping[str, str]) – extra authentication request parameters
Returns: the authentication request
Return type: AuthorizationRequest
-
client_credentials_grant
(scope: list = None, **kwargs) → oic.oauth2.message.AccessTokenResponse¶ Public method to request access_token using client_credentials flow. This is useful for service to service communication where user-agent is not available which is required in authorization code flow. Your service can request access_token in order to access APIs of other services.
On API call, token introspection will ensure that only valid token can be used to access your APIs.
Parameters: - scope (list, optional) – List of scopes to be requested.
- **kwargs (dict, optional) – Extra arguments to client credentials flow.
Returns: Return type: AccessTokenResponse
Examples
auth = OIDCAuthentication({'default': provider_config}, access_token_required=True) auth.init_app(app) auth.clients['default'].client_credentials_grant()
Optionally, you can specify scopes for the access token.
auth.clients['default'].client_credentials_grant( scope=['read', 'write'])
You can also specify extra keyword arguments to client credentials flow.
auth.clients['default'].client_credentials_grant( scope=['read', 'write'], audience=['client_id1', 'client_id2'])
Requests tokens from an authorization code.
Parameters: - authorization_code (str) – authorization code issued to client after user authorization
- state (str) – state is used to keep track of responses to outstanding requests.
- extra_token_args (Mapping[str, Any]) – extra arguments to pass to pyoidc
Returns: The parsed token response, or None if no token request was performed.
Return type: Union[AccessTokenResponse, TokenErrorResponse, None]
-
login_url
(auth_request)¶ Parameters: auth_request (AuthorizationRequest) – authentication request Returns: Authentication request as a URL to redirect the user to the provider. Return type: str
-
parse_authentication_response
(response_params)¶ Parameters: response_params (Mapping[str, str]) – authentication response parameters. Returns: The parsed authorization response. Return type: Union[AuthorizationResponse, AuthorizationErrorResponse]
-
refresh_token
(refresh_token: str)¶ Requests new tokens using a refresh token.
Parameters: refresh_token (str) – refresh token issued to client after user authorization. Returns: The parsed token response, or None if no token request was performed. Return type: Union[AccessTokenResponse, TokenErrorResponse, None]
-
userinfo_request
(access_token: str)¶ Retrieves ID token.
Parameters: access_token (str) – Bearer access token to use when fetching userinfo. Returns: Return type: Union[OpenIDSchema, UserInfoErrorResponse, ErrorResponse, None]
-
verify_id_token
(id_token, auth_request)¶ Verifies the ID Token.
Parameters: - id_token (Mapping[str, str]) – ID token claims
- auth_request (Mapping[str, str]) – original authentication request parameters to validate against (nonce, acr_values, max_age, etc.)
Raises: PyoidcError
– If the ID token is invalid.
-