********************************** Authenticate with OAuth 2 and OIDC ********************************** Servers in production usually require a token of OAuth 2, issued by an identity provider which speaks OpenID Connect (OIDC), such as Keycloak, Microsoft Entra ID or Auth0. The client sends every request through the transport, so the authentication lives entirely in the transport (see :doc:`transports`): the client asks the transport anew for every request and every page, and never caches a token itself. Which flow to use depends on who calls the server. We cover the three typical cases: * a service calls the server on its own behalf (the client credentials flow), * an application calls the server on behalf of a user (the authorization code flow, with refresh tokens), and * you obtain the tokens yourself, for example, from a secret store or a platform identity. The examples need an identity provider, and are not run by the tests of the client. Replace the URLs, the identifiers and the secrets with yours. A Service: the Client Credentials Flow ====================================== A service which runs without a user, such as a gateway which synchronizes the shells, authenticates as itself with its client ID and secret. `authlib`_ gives a :py:class:`requests.Session` which fetches the token, and fetches a new one before the old one expires: .. _authlib: https://pypi.org/project/Authlib/ .. skip-live-test: The live tests have no identity provider. .. code-block:: python from authlib.integrations.requests_client import OAuth2Session from aas_client3_2 import ( http as aas_client_http, requests_transport as aas_client_requests_transport, submodel_repository as aas_client_submodel_repository, ) session = OAuth2Session( client_id="my-service", client_secret="my-secret", scope="openid", token_endpoint=( "https://keycloak.example.com" "/realms/aas/protocol/openid-connect/token" ), grant_type="client_credentials", ) session.fetch_token() server = aas_client_http.Server( transport=aas_client_requests_transport.RequestsTransport( session ), base_url="https://aas.example.com/api/v3.2", ) page = aas_client_submodel_repository.get_all_submodels( server, limit=10 ) Keep the secret out of the code, for example, in an environment variable or a secret store. An Application: the Authorization Code Flow =========================================== An application which acts on behalf of a user lets the user log in at the identity provider, and receives an access token together with a refresh token. How you obtain the first token depends on your application (a web application handles the redirect, a command-line tool might open the browser); once you have it, `requests-oauthlib`_ refreshes it for you whenever it expires: .. _requests-oauthlib: https://pypi.org/project/requests-oauthlib/ .. skip-live-test: The live tests have no identity provider. .. code-block:: python from typing import Any, Dict from requests_oauthlib import OAuth2Session from aas_client3_2 import ( http as aas_client_http, requests_transport as aas_client_requests_transport, ) token_url = ( "https://keycloak.example.com" "/realms/aas/protocol/openid-connect/token" ) def save_token(token: Dict[str, Any]) -> None: """Store the refreshed token, so that the user need not log in.""" session = OAuth2Session( client_id="my-application", # The token from the login of the user, with its refresh token token=token_from_login, auto_refresh_url=token_url, auto_refresh_kwargs={"client_id": "my-application"}, token_updater=save_token, ) server = aas_client_http.Server( transport=aas_client_requests_transport.RequestsTransport( session ), base_url="https://aas.example.com/api/v3.2", ) The server then decides by the roles or the claims of the user which operations it allows; it responds with 403 for the others, and the client raises :py:class:`~aas_client3_2.errors.Forbidden`. Your Own Tokens =============== If you obtain the tokens elsewhere, for example, from a secret store, from the identity of the platform your service runs on, or with a library of your identity provider, wrap the transport so that it asks for the current token on every request, as described in :doc:`transports`. The endpoints of the identity provider are listed in its OpenID configuration, so you need only the address of the issuer. For example, a provider of the tokens by the client credentials flow, with plain `requests`_: .. _requests: https://pypi.org/project/requests/ .. skip-live-test: The live tests have no identity provider. .. code-block:: python import time from typing import Optional import requests class ClientCredentialsTokenProvider: def __init__( self, issuer: str, client_id: str, client_secret: str ) -> None: configuration = requests.get( f"{issuer}/.well-known/openid-configuration", timeout=10 ).json() self.token_endpoint = configuration["token_endpoint"] self.client_id = client_id self.client_secret = client_secret self._token: Optional[str] = None self._expires_at = 0.0 def token(self) -> str: # Fetch a new token a bit before the old one expires. if ( self._token is None or time.monotonic() > self._expires_at - 30 ): response = requests.post( self.token_endpoint, data={"grant_type": "client_credentials"}, auth=(self.client_id, self.client_secret), timeout=10, ) response.raise_for_status() payload = response.json() self._token = payload["access_token"] self._expires_at = time.monotonic() + payload.get( "expires_in", 60 ) return self._token def invalidate(self) -> None: self._token = None Use it with the ``BearerTransport`` of :doc:`transports`, which also retries once with a fresh token if the server rejects the token before it expires, for example, because it has been revoked: .. skip-live-test: The live tests have no identity provider. .. code-block:: python provider = ClientCredentialsTokenProvider( issuer="https://keycloak.example.com/realms/aas", client_id="my-service", client_secret="my-secret", ) server = aas_client_http.Server( transport=BearerTransport( aas_client_requests_transport.RequestsTransport( requests.Session() ), provider, ), base_url="https://aas.example.com/api/v3.2", ) When the Token Is Refused ========================= If the server does not accept the token, the client raises :py:class:`~aas_client3_2.errors.Unauthorized`, with the response of the server. The header ``WWW-Authenticate`` of the response tells why, for example, ``error="invalid_token"`` for an expired or revoked token, or ``error="insufficient_scope"`` if the token lacks a scope: .. skip-live-test: The live tests have no identity provider. .. code-block:: python from aas_client3_2 import ( errors as aas_client_errors, ) try: aas_client_submodel_repository.get_all_submodels(server) except aas_client_errors.Unauthorized as error: print( aas_client_http.find_header( error.response.headers, "WWW-Authenticate" ) ) Check that the token is issued for the server, the *audience*, if your identity provider issues tokens for several services; a server rightly refuses a token meant for another one.