Repository navigation
SDK-2773-python-support-central-auth-tokens #467
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
mehmet-yoti
merged 2 commits into
development
from
SDK-2773-python-support-central-auth-tokens
Nov 18, 2026
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| # -*- coding: utf-8 -*- | ||
| from .authentication_token_generator import ( | ||
| AuthenticationTokenGenerator, | ||
| AuthenticationTokenGeneratorBuilder, | ||
| ) | ||
| from .create_authentication_token_response import CreateAuthenticationTokenResponse | ||
| from .exception import AuthException | ||
|
|
||
| __all__ = [ | ||
| "AuthenticationTokenGenerator", | ||
| "AuthenticationTokenGeneratorBuilder", | ||
| "CreateAuthenticationTokenResponse", | ||
| "AuthException", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,223 @@ | ||
| # -*- coding: utf-8 -*- | ||
| from __future__ import unicode_literals | ||
|
|
||
| import base64 | ||
| import json | ||
| import time | ||
| import uuid | ||
| from os import environ | ||
|
|
||
| import requests | ||
|
|
||
| from yoti_python_sdk.crypto import Crypto | ||
| from .create_authentication_token_response import CreateAuthenticationTokenResponse | ||
| from .exception import AuthException | ||
|
|
||
| DEFAULT_AUTH_API_URL = "https://auth.api.yoti.com/v1/oauth/token" | ||
| CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" | ||
| JWT_EXPIRY_SECONDS = 300 | ||
| DEFAULT_REQUEST_TIMEOUT_SECONDS = 30 | ||
|
|
||
|
|
||
| def _default_jwt_id_supplier(): | ||
| return str(uuid.uuid4()) | ||
|
|
||
|
|
||
| class AuthenticationTokenGenerator(object): | ||
| """ | ||
| Generates a central auth token that can be supplied to an SDK client | ||
| (e.g. DocScanClient, Client) instead of a PEM file, allowing the Relying | ||
| Business to authenticate using the new central auth scheme. | ||
|
|
||
| The SDK does not automatically refresh or cache the generated token; the | ||
| caller is responsible for generating a new one before it expires | ||
| (see CreateAuthenticationTokenResponse.expires_in). | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| sdk_id, | ||
| crypto, | ||
| auth_api_url, | ||
| jwt_id_supplier=None, | ||
| timeout=DEFAULT_REQUEST_TIMEOUT_SECONDS, | ||
| ): | ||
| self.__sdk_id = sdk_id | ||
| self.__crypto = crypto | ||
| self.__auth_api_url = auth_api_url | ||
| self.__jwt_id_supplier = jwt_id_supplier or _default_jwt_id_supplier | ||
| self.__timeout = timeout | ||
|
|
||
| @staticmethod | ||
| def builder(): | ||
| """ | ||
| Returns an instance of AuthenticationTokenGeneratorBuilder | ||
| """ | ||
| return AuthenticationTokenGeneratorBuilder() | ||
|
|
||
| def generate(self, scopes): | ||
| """ | ||
| Generates an authentication token for the supplied scopes | ||
|
|
||
| :param scopes: the scopes to request for the token | ||
| :type scopes: list[str] | ||
| :return: the generated token response | ||
| :rtype: CreateAuthenticationTokenResponse | ||
| :raises ValueError: if scopes is empty | ||
| :raises AuthException: if the token could not be generated | ||
| """ | ||
| if not scopes: | ||
| raise ValueError("scopes must not be empty") | ||
|
|
||
| client_assertion = self.__create_signed_jwt() | ||
| form_data = { | ||
| "grant_type": "client_credentials", | ||
| "client_assertion_type": CLIENT_ASSERTION_TYPE, | ||
| "client_assertion": client_assertion, | ||
| "scope": " ".join(scopes), | ||
| } | ||
|
|
||
| response = requests.post( | ||
| self.__auth_api_url, data=form_data, timeout=self.__timeout | ||
| ) | ||
|
|
||
| if response.status_code != 200: | ||
| raise AuthException("Failed to generate authentication token", response) | ||
|
|
||
| return CreateAuthenticationTokenResponse(json.loads(response.text)) | ||
|
|
||
| def __create_signed_jwt(self): | ||
| """ | ||
| Creates a PS384-signed JWT client assertion, identifying the SDK by | ||
| sdk_id and valid for JWT_EXPIRY_SECONDS | ||
| """ | ||
| issuer = "sdk:{0}".format(self.__sdk_id) | ||
| now = int(time.time()) | ||
|
|
||
| header = {"alg": "PS384", "typ": "JWT"} | ||
| payload = { | ||
| "iss": issuer, | ||
| "sub": issuer, | ||
| "jti": self.__jwt_id_supplier(), | ||
| "aud": self.__auth_api_url, | ||
| "iat": now, | ||
| "exp": now + JWT_EXPIRY_SECONDS, | ||
| } | ||
|
|
||
| signing_input = "{0}.{1}".format( | ||
| self.__base64url_encode(self.__json_dumps(header)), | ||
| self.__base64url_encode(self.__json_dumps(payload)), | ||
| ) | ||
| signature = self.__crypto.sign_ps384(signing_input.encode("utf-8")) | ||
|
|
||
| return "{0}.{1}".format(signing_input, self.__base64url_encode(signature)) | ||
|
|
||
| @staticmethod | ||
| def __json_dumps(data): | ||
| return json.dumps(data, separators=(",", ":"), sort_keys=True).encode("utf-8") | ||
|
|
||
| @staticmethod | ||
| def __base64url_encode(data): | ||
| return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") | ||
|
|
||
|
|
||
| class AuthenticationTokenGeneratorBuilder(object): | ||
| """ | ||
| Builder to assist in the creation of :class:`AuthenticationTokenGenerator` | ||
| """ | ||
|
|
||
| def __init__(self): | ||
| self.__sdk_id = None | ||
| self.__crypto = None | ||
| self.__auth_api_url = None | ||
| self.__jwt_id_supplier = None | ||
| self.__timeout = DEFAULT_REQUEST_TIMEOUT_SECONDS | ||
|
|
||
| def with_sdk_id(self, sdk_id): | ||
| """ | ||
| Sets the SDK ID to identify the token request | ||
|
|
||
| :param sdk_id: the SDK ID | ||
| :type sdk_id: str | ||
| :return: the builder | ||
| :rtype: AuthenticationTokenGeneratorBuilder | ||
| """ | ||
| self.__sdk_id = sdk_id | ||
| return self | ||
|
|
||
| def with_pem_file(self, pem_file): | ||
| """ | ||
| Sets the PEM file used to sign the JWT client assertion. Can be an | ||
| instance of yoti_python_sdk.crypto.Crypto or a path to a PEM file | ||
|
|
||
| :param pem_file: the PEM file or Crypto instance | ||
| :return: the builder | ||
| :rtype: AuthenticationTokenGeneratorBuilder | ||
| """ | ||
| if isinstance(pem_file, Crypto): | ||
| self.__crypto = pem_file | ||
| else: | ||
| self.__crypto = Crypto.read_pem_file(pem_file) | ||
|
|
||
| return self | ||
|
|
||
| def with_auth_api_url(self, auth_api_url): | ||
| """ | ||
| Overrides the default auth API URL | ||
|
|
||
| :param auth_api_url: the auth API URL | ||
| :type auth_api_url: str | ||
| :return: the builder | ||
| :rtype: AuthenticationTokenGeneratorBuilder | ||
| """ | ||
| self.__auth_api_url = auth_api_url | ||
| return self | ||
|
|
||
| def with_jwt_id_supplier(self, jwt_id_supplier): | ||
| """ | ||
| Overrides the callable used to generate the JWT ID (jti claim). | ||
| Defaults to generating a random UUID v4 for each token request | ||
|
|
||
| :param jwt_id_supplier: a callable returning a unique string | ||
| :type jwt_id_supplier: callable | ||
| :return: the builder | ||
| :rtype: AuthenticationTokenGeneratorBuilder | ||
| """ | ||
| self.__jwt_id_supplier = jwt_id_supplier | ||
| return self | ||
|
|
||
| def with_timeout(self, timeout): | ||
| """ | ||
| Overrides the timeout (in seconds) used for the auth token request | ||
|
|
||
| :param timeout: the timeout in seconds | ||
| :type timeout: float | ||
| :return: the builder | ||
| :rtype: AuthenticationTokenGeneratorBuilder | ||
| """ | ||
| self.__timeout = timeout | ||
| return self | ||
|
|
||
| def build(self): | ||
| """ | ||
| Builds an AuthenticationTokenGenerator with the supplied values | ||
|
|
||
| :return: the authentication token generator | ||
| :rtype: AuthenticationTokenGenerator | ||
| """ | ||
| if self.__sdk_id is None: | ||
| raise ValueError("sdk_id must be provided") | ||
| if self.__crypto is None: | ||
| raise ValueError("pem_file must be provided") | ||
|
|
||
| auth_api_url = self.__auth_api_url or environ.get( | ||
| "YOTI_AUTH_URL", DEFAULT_AUTH_API_URL | ||
| ) | ||
|
|
||
| return AuthenticationTokenGenerator( | ||
| self.__sdk_id, | ||
| self.__crypto, | ||
| auth_api_url, | ||
| jwt_id_supplier=self.__jwt_id_supplier, | ||
| timeout=self.__timeout, | ||
| ) | ||
59 changes: 59 additions & 0 deletions
59
yoti_python_sdk/auth/create_authentication_token_response.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| # -*- coding: utf-8 -*- | ||
|
|
||
|
|
||
| class CreateAuthenticationTokenResponse(object): | ||
| """ | ||
| The response returned when generating a central auth token | ||
| """ | ||
|
|
||
| def __init__(self, data): | ||
| """ | ||
| :param data: the parsed JSON response body | ||
| :type data: dict | ||
| """ | ||
| self.__access_token = data.get("access_token") | ||
| self.__token_type = data.get("token_type") | ||
| self.__expires_in = data.get("expires_in") | ||
| self.__scope = data.get("scope") | ||
|
|
||
| @property | ||
| def access_token(self): | ||
| """ | ||
| The auth token to be supplied to an SDK client | ||
|
|
||
| :return: the access token | ||
| :rtype: str | ||
| """ | ||
| return self.__access_token | ||
|
|
||
| @property | ||
| def token_type(self): | ||
| """ | ||
| The type of token issued, e.g. "Bearer" | ||
|
|
||
| :return: the token type | ||
| :rtype: str | ||
| """ | ||
| return self.__token_type | ||
|
|
||
| @property | ||
| def expires_in(self): | ||
| """ | ||
| The lifetime of the access token in seconds. The SDK does not | ||
| automatically refresh the token on expiry; it is the caller's | ||
| responsibility to generate a new one before it expires | ||
|
|
||
| :return: the expiry, in seconds | ||
| :rtype: int or None | ||
| """ | ||
| return self.__expires_in | ||
|
|
||
| @property | ||
| def scope(self): | ||
| """ | ||
| The scopes granted to the access token | ||
|
|
||
| :return: the granted scopes | ||
| :rtype: str or None | ||
| """ | ||
| return self.__scope |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| # -*- coding: utf-8 -*- | ||
| import json | ||
|
|
||
|
|
||
| class AuthException(Exception): | ||
| """ | ||
| Exception thrown when an authentication token could not be generated | ||
| """ | ||
|
|
||
| def __init__(self, message, response): | ||
| """ | ||
| :param message: the exception message | ||
| :type message: str | ||
| :param response: the http response | ||
| :type response: requests.Response | ||
| """ | ||
| Exception.__init__(self) | ||
|
|
||
| response_message = self.__get_response_message(response) | ||
|
|
||
| self.__message = message + ( | ||
| " - " + response_message if response_message else "" | ||
| ) | ||
| self.__response = response | ||
|
|
||
| @property | ||
| def message(self): | ||
| """ | ||
| Get the specific exception message | ||
|
|
||
| :return: the exception message | ||
| :rtype: str | ||
| """ | ||
| return self.__message | ||
|
|
||
| @property | ||
| def status_code(self): | ||
| """ | ||
| Get the status code of the HTTP response | ||
|
|
||
| :return: the status code | ||
| :rtype: int or None | ||
| """ | ||
| return self.__response.status_code | ||
|
|
||
| @property | ||
| def text(self): | ||
| """ | ||
| Return the HTTP response body as text | ||
|
|
||
| :return: the body as text | ||
| :rtype: str | ||
| """ | ||
| return self.__response.text | ||
|
|
||
| def __get_response_message(self, response): | ||
| """ | ||
| Return the formatted OAuth2 error response message | ||
|
|
||
| :return: the formatted message | ||
| :rtype: string or None | ||
| """ | ||
| content_type = response.headers.get("Content-Type", "") | ||
| if not content_type.startswith("application/json"): | ||
| return None | ||
|
|
||
| try: | ||
| parsed = json.loads(response.text) | ||
| except ValueError: | ||
| return None | ||
|
|
||
| return self.__format_oauth_error(parsed) | ||
|
|
||
| @staticmethod | ||
| def __format_oauth_error(parsed): | ||
| """ | ||
| Return the formatted OAuth2 "error"/"error_description" message | ||
|
|
||
| :return: the formatted message | ||
| :rtype: string or None | ||
| """ | ||
| error = parsed.get("error") | ||
| if not error: | ||
| return None | ||
|
|
||
| description = parsed.get("error_description") | ||
| if description: | ||
| return error + " - " + description | ||
|
|
||
| return error | ||
|
|
||
| def __str__(self): | ||
| return self.__message |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@mehmet-yoti jti claim is not included in the JWT token generation - example in php
https://github.com/getyoti/yoti-php-sdk/blob/d4cc170c8ff57a4a0c19e3250edb0835af93aa25/src/Auth/AuthenticationTokenGenerator.php#L71
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@mehmet-yoti still needs addressing