Authorization Code Grant is implemented following rfc6749.
Use httpx_auth.OAuth2AuthorizationCode to configure this kind of authentication.
import httpx
from httpx_auth import OAuth2AuthorizationCode
with httpx.Client() as client:
client.get('https://www.example.com', auth=OAuth2AuthorizationCode('https://www.authorization.url', 'https://www.token.url'))
FQDN to use in the redirect_uri when localhost is not allowed.
Optional
localhost
redirect_uri_endpoint
Custom endpoint that will be used as redirect_uri the following way: http://<redirect_uri_domain>:<redirect_uri_port>/<redirect_uri_endpoint>.
Optional
''
redirect_uri_port
The port on which the server listening for the OAuth 2 code will be started.
Optional
5000
timeout
Maximum amount of seconds to wait for a code or a token to be received once requested.
Optional
60
header_name
Name of the header field used to send token.
Optional
Authorization
header_value
Format used to send the token value. "{token}" must be present as it will be replaced by the actual token.
Optional
Bearer {token}
response_type
Value of the response_type query parameter if not already provided in authorization URL.
Optional
code
token_field_name
Field name containing the token.
Optional
access_token
early_expiry
Number of seconds before actual token expiry where token will be considered as expired. Used to ensure token will not expire between the time of retrieval and the time the request reaches the actual server. Set it to 0 to deactivate this feature and use the same token until actual expiry.
Optional
30.0
code_field_name
Field name containing the code.
Optional
code
username
User name in case basic authentication should be used to retrieve token.
Optional
password
User password in case basic authentication should be used to retrieve token.
Optional
client
httpx.Client instance that will be used to request the token. Use it to provide a custom proxying rule for instance.
Optional
Any other parameter will be put as query parameter in the authorization URL and as body parameters in the token URL.
Usual extra parameters are:
Name
Description
client_id
Corresponding to your Application ID (in Microsoft Azure app portal)
client_secret
If client is not authenticated with the authorization server
Okta Application Identifier (formatted as an Universal Unique Identifier).
Mandatory
response_type
Value of the response_type query parameter if not already provided in authorization URL.
Optional
token
token_field_name
Field name containing the token.
Optional
access_token
early_expiry
Number of seconds before actual token expiry where token will be considered as expired. Used to ensure token will not expire between the time of retrieval and the time the request reaches the actual server. Set it to 0 to deactivate this feature and use the same token until actual expiry.
WakaTime Application Identifier (formatted as an Universal Unique Identifier).
Mandatory
client_secret
WakaTime Application Secret (formatted as waka_sec_ followed by an Universal Unique Identifier).
Mandatory
scope
Scope parameter sent in query. Can also be a list of scopes.
Mandatory
response_type
Value of the response_type query parameter if not already provided in authorization URL.
Optional
token
token_field_name
Field name containing the token.
Optional
access_token
early_expiry
Number of seconds before actual token expiry where token will be considered as expired. Used to ensure token will not expire between the time of retrieval and the time the request reaches the actual server. Set it to 0 to deactivate this feature and use the same token until actual expiry.
FQDN to use in the redirect_uri when localhost is not allowed.
Optional
localhost
redirect_uri_endpoint
Custom endpoint that will be used as redirect_uri the following way: http://<redirect_uri_domain>:<redirect_uri_port>/<redirect_uri_endpoint>.
Optional
''
redirect_uri_port
The port on which the server listening for the OAuth 2 token will be started.
Optional
5000
timeout
Maximum amount of seconds to wait for a token to be received once requested.
Optional
60
header_name
Name of the header field used to send token.
Optional
Authorization
header_value
Format used to send the token value. "{token}" must be present as it will be replaced by the actual token.
Optional
Bearer {token}
client
httpx.Client instance that will be used to request the token. Use it to provide a custom proxying rule for instance.
Optional
Any other parameter will be put as query parameter in the authorization URL.
Authorization Code Flow with Proof Key for Code Exchange
Proof Key for Code Exchange is implemented following rfc7636.
Use httpx_auth.OAuth2AuthorizationCodePKCE to configure this kind of authentication.
import httpx
from httpx_auth import OAuth2AuthorizationCodePKCE
with httpx.Client() as client:
client.get('https://www.example.com', auth=OAuth2AuthorizationCodePKCE('https://www.authorization.url', 'https://www.token.url'))
FQDN to use in the redirect_uri when localhost is not allowed.
Optional
localhost
redirect_uri_endpoint
Custom endpoint that will be used as redirect_uri the following way: http://<redirect_uri_domain>:<redirect_uri_port>/<redirect_uri_endpoint>.
Optional
''
redirect_uri_port
The port on which the server listening for the OAuth 2 code will be started.
Optional
5000
timeout
Maximum amount of seconds to wait for a code or a token to be received once requested.
Optional
60
header_name
Name of the header field used to send token.
Optional
Authorization
header_value
Format used to send the token value. "{token}" must be present as it will be replaced by the actual token.
Optional
Bearer {token}
response_type
Value of the response_type query parameter if not already provided in authorization URL.
Optional
code
token_field_name
Field name containing the token.
Optional
access_token
early_expiry
Number of seconds before actual token expiry where token will be considered as expired. Used to ensure token will not expire between the time of retrieval and the time the request reaches the actual server. Set it to 0 to deactivate this feature and use the same token until actual expiry.
Optional
30.0
code_field_name
Field name containing the code.
Optional
code
client
httpx.Client instance that will be used to request the token. Use it to provide a custom proxying rule for instance.
Optional
Any other parameter will be put as query parameter in the authorization URL and as body parameters in the token URL.
Usual extra parameters are:
Name
Description
client_id
Corresponding to your Application ID (in Microsoft Azure app portal)
client_secret
If client is not authenticated with the authorization server
Okta Application Identifier (formatted as an Universal Unique Identifier).
Mandatory
response_type
Value of the response_type query parameter if not already provided in authorization URL.
Optional
code
token_field_name
Field name containing the token.
Optional
access_token
early_expiry
Number of seconds before actual token expiry where token will be considered as expired. Used to ensure token will not expire between the time of retrieval and the time the request reaches the actual server. Set it to 0 to deactivate this feature and use the same token until actual expiry.
Client authentication if the client type is confidential or the client was issued client credentials (or assigned other authentication requirements). Can be a tuple or any httpx authentication class instance.
Optional
timeout
Maximum amount of seconds to wait for a token to be received once requested.
Optional
60
header_name
Name of the header field used to send token.
Optional
Authorization
header_value
Format used to send the token value. "{token}" must be present as it will be replaced by the actual token.
Optional
Bearer {token}
scope
Scope parameter sent to token URL as body. Can also be a list of scopes.
Optional
token_field_name
Field name containing the token.
Optional
access_token
early_expiry
Number of seconds before actual token expiry where token will be considered as expired. Used to ensure token will not expire between the time of retrieval and the time the request reaches the actual server. Set it to 0 to deactivate this feature and use the same token until actual expiry.
Optional
30.0
client
httpx.Client instance that will be used to request the token. Use it to provide a custom proxying rule for instance.
Optional
Any other parameter will be put as body parameter in the token URL.
Common providers
Most of OAuth2 Resource Owner Password Credentials providers are supported.
Okta Application Identifier (formatted as an Universal Unique Identifier).
Mandatory
client_secret
Resource owner password.
Mandatory
timeout
Maximum amount of seconds to wait for a token to be received once requested.
Optional
60
header_name
Name of the header field used to send token.
Optional
Authorization
header_value
Format used to send the token value. "{token}" must be present as it will be replaced by the actual token.
Optional
Bearer {token}
scope
Scope parameter sent in query. Can also be a list of scopes.
Optional
openid
token_field_name
Field name containing the token.
Optional
access_token
early_expiry
Number of seconds before actual token expiry where token will be considered as expired. Used to ensure token will not expire between the time of retrieval and the time the request reaches the actual server. Set it to 0 to deactivate this feature and use the same token until actual expiry.
Optional
30.0
client
httpx.Client instance that will be used to request the token. Use it to provide a custom proxying rule for instance.
Optional
Any other parameter will be put as body parameters in the token URL.
Client Credentials flow
Client Credentials Grant is implemented following rfc6749.
Use httpx_auth.OAuth2ClientCredentials to configure this kind of authentication.
import httpx
from httpx_auth import OAuth2ClientCredentials
with httpx.Client() as client:
client.get('https://www.example.com', auth=OAuth2ClientCredentials('https://www.token.url', client_id='id', client_secret='secret'))
Maximum amount of seconds to wait for a token to be received once requested.
Optional
60
header_name
Name of the header field used to send token.
Optional
Authorization
header_value
Format used to send the token value. "{token}" must be present as it will be replaced by the actual token.
Optional
Bearer {token}
scope
Scope parameter sent to token URL as body. Can also be a list of scopes.
Optional
token_field_name
Field name containing the token.
Optional
access_token
early_expiry
Number of seconds before actual token expiry where token will be considered as expired. Used to ensure token will not expire between the time of retrieval and the time the request reaches the actual server. Set it to 0 to deactivate this feature and use the same token until actual expiry.
Optional
30.0
client
httpx.Client instance that will be used to request the token. Use it to provide a custom proxying rule for instance.
Optional
Any other parameter will be put as body parameter in the token URL.
Common providers
Most of OAuth2 Client Credentials Grant providers are supported.
Okta Application Identifier (formatted as an Universal Unique Identifier).
Mandatory
client_secret
Resource owner password.
Mandatory
scope
Scope parameter sent in query. Can also be a list of scopes.
Mandatory
authorization_server
Okta authorization server.
Optional
'default'
timeout
Maximum amount of seconds to wait for a token to be received once requested.
Optional
60
header_name
Name of the header field used to send token.
Optional
Authorization
header_value
Format used to send the token value. "{token}" must be present as it will be replaced by the actual token.
Optional
Bearer {token}
token_field_name
Field name containing the token.
Optional
access_token
early_expiry
Number of seconds before actual token expiry where token will be considered as expired. Used to ensure token will not expire between the time of retrieval and the time the request reaches the actual server. Set it to 0 to deactivate this feature and use the same token until actual expiry.
Optional
30.0
client
httpx.Client instance that will be used to request the token. Use it to provide a custom proxying rule for instance.
Optional
Any other parameter will be put as query parameter in the token URL.
Use httpx_auth.OAuth2Implicit to configure this kind of authentication.
import httpx
from httpx_auth import OAuth2Implicit
with httpx.Client() as client:
client.get('https://www.example.com', auth=OAuth2Implicit('https://www.authorization.url'))
Value of the response_type query parameter if not already provided in authorization URL.
Optional
token
token_field_name
Field name containing the token.
Optional
id_token if response_type is id_token, otherwise access_token
early_expiry
Number of seconds before actual token expiry where token will be considered as expired. Used to ensure token will not expire between the time of retrieval and the time the request reaches the actual server. Set it to 0 to deactivate this feature and use the same token until actual expiry.
Optional
30.0
redirect_uri_domain
FQDN to use in the redirect_uri when localhost is not allowed.
Optional
localhost
redirect_uri_endpoint
Custom endpoint that will be used as redirect_uri the following way: http://<redirect_uri_domain>:<redirect_uri_port>/<redirect_uri_endpoint>.
Optional
''
redirect_uri_port
The port on which the server listening for the OAuth 2 token will be started.
Optional
5000
timeout
Maximum amount of seconds to wait for a token to be received once requested.
Optional
60
header_name
Name of the header field used to send token.
Optional
Authorization
header_value
Format used to send the token value. "{token}" must be present as it will be replaced by the actual token.
Optional
Bearer {token}
Any other parameter will be put as query parameter in the authorization URL.
Usual extra parameters are:
Name
Description
client_id
Corresponding to your Application ID (in Microsoft Azure app portal)
Microsoft Tenant Identifier (formatted as an Universal Unique Identifier).
Mandatory
client_id
Microsoft Application Identifier (formatted as an Universal Unique Identifier).
Mandatory
response_type
Value of the response_type query parameter if not already provided in authorization URL.
Optional
token
token_field_name
Field name containing the token.
Optional
access_token
early_expiry
Number of seconds before actual token expiry where token will be considered as expired. Used to ensure token will not expire between the time of retrieval and the time the request reaches the actual server. Set it to 0 to deactivate this feature and use the same token until actual expiry.
Microsoft Tenant Identifier (formatted as an Universal Unique Identifier).
Mandatory
client_id
Microsoft Application Identifier (formatted as an Universal Unique Identifier).
Mandatory
response_type
Value of the response_type query parameter if not already provided in authorization URL.
Optional
id_token
token_field_name
Field name containing the token.
Optional
id_token
early_expiry
Number of seconds before actual token expiry where token will be considered as expired. Used to ensure token will not expire between the time of retrieval and the time the request reaches the actual server. Set it to 0 to deactivate this feature and use the same token until actual expiry.
Okta Application Identifier (formatted as an Universal Unique Identifier).
Mandatory
response_type
Value of the response_type query parameter if not already provided in authorization URL.
Optional
token
token_field_name
Field name containing the token.
Optional
access_token
early_expiry
Number of seconds before actual token expiry where token will be considered as expired. Used to ensure token will not expire between the time of retrieval and the time the request reaches the actual server. Set it to 0 to deactivate this feature and use the same token until actual expiry.
Okta Application Identifier (formatted as an Universal Unique Identifier).
Mandatory
response_type
Value of the response_type query parameter if not already provided in authorization URL.
Optional
id_token
token_field_name
Field name containing the token.
Optional
id_token
early_expiry
Number of seconds before actual token expiry where token will be considered as expired. Used to ensure token will not expire between the time of retrieval and the time the request reaches the actual server. Set it to 0 to deactivate this feature and use the same token until actual expiry.
Scope parameter sent in query. Can also be a list of scopes.
Optional
['openid', 'profile', 'email']
authorization_server
Okta authorization server.
Optional
'default'
redirect_uri_domain
FQDN to use in the redirect_uri when localhost is not allowed.
Optional
localhost
redirect_uri_endpoint
Custom endpoint that will be used as redirect_uri the following way: http://<redirect_uri_domain>:<redirect_uri_port>/<redirect_uri_endpoint>.
Optional
''
redirect_uri_port
The port on which the server listening for the OAuth 2 token will be started.
Optional
5000
timeout
Maximum amount of seconds to wait for a token to be received once requested.
Optional
60
header_name
Name of the header field used to send token.
Optional
Authorization
header_value
Format used to send the token value. "{token}" must be present as it will be replaced by the actual token.
Optional
Bearer {token}
Any other parameter will be put as query parameter in the authorization URL.
Usual extra parameters are:
Name
Description
prompt
none to avoid prompting the user if a session is already opened.
Managing token cache
To avoid asking for a new token every new request, a token cache is used.
Default cache is in memory, but it is also possible to use a physical cache.
You need to provide the location of your token cache file. It can be a full or relative path (str or pathlib.Path).
If the file already exists it will be used, if the file do not exist it will be created.
from httpx_auth import OAuth2, JsonTokenFileCache
OAuth2.token_cache = JsonTokenFileCache('path/to/my_token_cache.json')
Managing the web browser
Authentication response pages
You can configure the browser display settings thanks to httpx_auth.OAuth2.display as in the following:
from httpx_auth import OAuth2, DisplaySettings
OAuth2.display = DisplaySettings()
The following parameters can be provided to DisplaySettings:
Name
Description
Default value
success_display_time
In case a code or token is successfully received, this is the maximum amount of milliseconds the success page will be displayed in your browser.
1
success_html
In case a code or token is successfully received, this is the success page that will be displayed in your browser. {display_time} is expected in this content.
failure_display_time
In case received code or token is not valid, this is the maximum amount of milliseconds the failure page will be displayed in your browser.
10_000
failure_html
In case received code or token is not valid, this is the failure page that will be displayed in your browser. {information} and {display_time} are expected in this content.
Text-mode web browser
This project uses webbrowser.open() to open a web browser to support authentication flows like OAuth's Authorization Code grant. When running graphically, webbrowser.open() does not block. But when run in text mode, webbrowser.open() blocks until the opened browser is closed, which leads to a deadlock when httpx-auth cannot serve the auth response pages to the webbrowser. To work around this, you can specify a BROWSER environment variable that contains a %s and ends with a &, and the webbrowser module will open the text-mode browser in a subprocess and allow httpx-auth to serve the auth response pages to the browser without deadlocking.
BROWSER="/usr/bin/links %s &"
For more information, please see the implementation of webbrowser.get().
If multiple values are provided for a same header, the computation will be based on the value order you provided and value separated by , . Instead of ordered values separated by comma for requests-aws4auth.
amz_date attribute has been removed.
It is not possible to provide a date. It will default to now.
It is not possible to provide an AWSSigningKey instance, use explicit parameters instead.
It is not possible to provide raise_invalid_date parameter anymore as the date will always be valid.
host is not considered as a specific Amazon service anymore (no test specific code).
Canonical query string computation is entirely based on AWS documentation (and consider undocumented fragment (# and following characters) as part of the query string).
Canonical uri computation is entirely based on AWS documentation.
Canonical headers computation is entirely based on AWS documentation.
Parameters
Name
Description
Mandatory
Default value
access_id
AWS access ID.
Mandatory
secret_key
AWS secret access key.
Mandatory
region
The region you are connecting to, as per this list. For services which do not require a region (e.g. IAM), use us-east-1.
Mandatory
service
The name of the service you are connecting to, as per this list. e.g. elasticbeanstalk.
Mandatory
security_token
Used for the x-amz-security-token header, for use with STS temporary credentials.
Optional
include_headers
Set of headers to include in the canonical and signed headers (in addition to the default). Note that x-amz-client-context is not included by default and * will include all headers.
Optional
{"host", "content-type", "x-amz-*"} and if security_token is provided, x-amz-security-token.
Dynamically retrieving credentials using boto3
While httpx-auth does not want to include support for botocore, the following authentication class should allow you to automatically retrieve up-to-date credentials.
You can send an API key inside the header of your request using httpx_auth.HeaderApiKey.
import httpx
from httpx_auth import HeaderApiKey
with httpx.Client() as client:
client.get('https://www.example.com', auth=HeaderApiKey('my_api_key'))
Parameters
Name
Description
Mandatory
Default value
api_key
The API key that will be sent.
Mandatory
header_name
Name of the header field.
Optional
"X-API-Key"
API key in query
You can send an API key inside the query parameters of your request using httpx_auth.QueryApiKey.
import httpx
from httpx_auth import QueryApiKey
with httpx.Client() as client:
client.get('https://www.example.com', auth=QueryApiKey('my_api_key'))
Parameters
Name
Description
Mandatory
Default value
api_key
The API key that will be sent.
Mandatory
query_parameter_name
Name of the query parameter.
Optional
"api_key"
Basic
You can use basic authentication using httpx_auth.Basic.
The only advantage of using this class instead of httpx native support of basic authentication, is to be able to use it in multiple authentication.
import httpx
from httpx_auth import Basic
with httpx.Client() as client:
client.get('https://www.example.com', auth=Basic('username', 'password'))
Parameters
Name
Description
Mandatory
Default value
username
User name.
Mandatory
password
User password.
Mandatory
Multiple authentication at once
You can also use a combination of authentication using +or & as in the following sample:
import httpx
from httpx_auth import HeaderApiKey, OAuth2Implicit
api_key = HeaderApiKey('my_api_key')
oauth2 = OAuth2Implicit('https://www.example.com')
with httpx.Client() as client:
client.get('https://www.example.com', auth=api_key + oauth2)
This is supported on every authentication class exposed by httpx_auth, but you can also enable it on your own authentication classes by using httpx_auth.SupportMultiAuth as in the following sample:
from httpx_auth import SupportMultiAuth
# TODO Import your own auth here
from my_package import MyAuth
class MyMultiAuth(MyAuth, SupportMultiAuth):
pass
Available pytest fixtures
Testing the code using httpx_auth authentication classes can be achieved using provided pytest fixtures.
token_cache_mock
from httpx_auth.testing import token_cache_mock, token_mock
def test_something(token_cache_mock):
# perform code using authentication
pass
Use this fixture to mock authentication success for any of the following classes:
OAuth2AuthorizationCodePKCE
OktaAuthorizationCodePKCE
OAuth2Implicit
OktaImplicit
OktaImplicitIdToken
AzureActiveDirectoryImplicit
AzureActiveDirectoryImplicitIdToken
OAuth2AuthorizationCode
OktaAuthorizationCode
WakaTimeAuthorizationCode
OAuth2ClientCredentials
OktaClientCredentials
OAuth2ResourceOwnerPasswordCredentials
OktaResourceOwnerPasswordCredentials
By default, an access token with value 2YotnFZFEjr1zCsicMWpAA is generated.
You can however return your custom token by providing your own token_mock fixture as in the following sample: