Package: httpx-auth
Authentication for HTTPXVersion 1.0.0 will be released once httpx is considered as stable (release of 1.0.0).However, current state can be considered as stable.Provides authentication classes to be used withhttpxauthentication parameter.Some of the supported authenticationAvailable authenticationOAuth2Authorization Code FlowOktaWakaTimeAuthorization Code Flow with PKCEOktaResource Owner Password Credentials flowClient Credentials FlowOktaImplicit FlowMicrosoft Entra (Access Token)Microsoft Entra (ID token)Okta (Access Token)Okta (ID token)Managing token cacheManaging browserAmazonAPI keyIn headerIn queryBasicMultiple authentication at onceOAuth 2Most ofOAuth2flows are supported.If the one you are looking for is not yet supported, feel free toask for its implementation.Authorization Code flowAuthorization Code Grant is implemented followingrfc6749.Usehttpx_auth.OAuth2AuthorizationCodeto configure this kind of authentication.importhttpxfromhttpx_authimportOAuth2AuthorizationCodewithhttpx.Client()asclient:client.get('https://www.example.com',auth=OAuth2AuthorizationCode('https://www.authorization.url','https://www.token.url'))Note:You can persist tokens thanks tothe token cache.You can tweak web browser interaction thanks tothe display settings.ParametersNameDescriptionMandatoryDefault valueauthorization_urlOAuth 2 authorization URL.Mandatorytoken_urlOAuth 2 token URL.Mandatoryredirect_uri_domainFQDNto use in the redirect_uri when localhost is not allowed.Optionallocalhostredirect_uri_endpointCustom endpoint that will be used as redirect_uri the following way: http://<redirect_uri_domain>:<redirect_uri_port>/<redirect_uri_endpoint>.Optional''redirect_uri_portThe port on which the server listening for the OAuth 2 code will be started.Optional5000timeoutMaximum amount of seconds to wait for a code or a token to be received once requested.Optional60header_nameName of the header field used to send token.OptionalAuthorizationheader_valueFormat used to send the token value. "{token}" must be present as it will be replaced by the actual token.OptionalBearer {token}response_typeValue of the response_type query parameter if not already provided in authorization URL.Optionalcodetoken_field_nameField name containing the token.Optionalaccess_tokenearly_expiryNumber 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.Optional30.0code_field_nameField name containing the code.OptionalcodeusernameUser name in case basic authentication should be used to retrieve token.OptionalpasswordUser password in case basic authentication should be used to retrieve token.Optionalclienthttpx.Clientinstance that will be used to request the token. Use it to provide a custom proxying rule for instance.OptionalAny other parameter will be put as query parameter in the authorization URL and as body parameters in the token URL.Usual extra parameters are:NameDescriptionclient_idCorresponding to your Application ID (in Microsoft Azure app portal)client_secretIf client is not authenticated with the authorization servernonceRefer toOpenID ID Token specificationsfor more detailsCommon providersMost ofOAuth2Authorization Code Grant providers are supported.If the one you are looking for is not yet supported, feel free toask for its implementation.Okta (OAuth2 Authorization Code)Okta Authorization Code Grantproviding access tokens is supported.Usehttpx_auth.OktaAuthorizationCodeto configure this kind of authentication.importhttpxfromhttpx_authimportOktaAuthorizationCodeokta=OktaAuthorizationCode(instance='testserver.okta-emea.com',client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd')withhttpx.Client()asclient:client.get('https://www.example.com',auth=okta)Note:You can persist tokens thanks tothe token cache.You can tweak web browser interaction thanks tothe display settings.ParametersNameDescriptionMandatoryDefault valueinstanceOkta instance (like "testserver.okta-emea.com").Mandatoryclient_idOkta Application Identifier (formatted as an Universal Unique Identifier).Mandatoryresponse_typeValue of the response_type query parameter if not already provided in authorization URL.Optionaltokentoken_field_nameField name containing the token.Optionalaccess_tokenearly_expiryNumber 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.Optional30.0nonceRefer toOpenID ID Token specificationsfor more details.OptionalNewly generated Universal Unique Identifier.scopeScope parameter sent in query. Can also be a list of scopes.Optionalopenidauthorization_serverOkta authorization server.Optional'default'redirect_uri_domainFQDNto use in the redirect_uri when localhost is not allowed.Optionallocalhostredirect_uri_endpointCustom endpoint that will be used as redirect_uri the following way: http://<redirect_uri_domain>:<redirect_uri_port>/<redirect_uri_endpoint>.Optional''redirect_uri_portThe port on which the server listening for the OAuth 2 token will be started.Optional5000timeoutMaximum amount of seconds to wait for a token to be received once requested.Optional60header_nameName of the header field used to send token.OptionalAuthorizationheader_valueFormat used to send the token value. "{token}" must be present as it will be replaced by the actual token.OptionalBearer {token}clienthttpx.Clientinstance that will be used to request the token. Use it to provide a custom proxying rule for instance.OptionalAny other parameter will be put as query parameter in the authorization URL.Usual extra parameters are:NameDescriptionpromptnone to avoid prompting the user if a session is already opened.WakaTime (OAuth2 Authorization Code)WakaTime Authorization Code Grantproviding access tokens is supported.Usehttpx_auth.WakaTimeAuthorizationCodeto configure this kind of authentication.importhttpxfromhttpx_authimportWakaTimeAuthorizationCodewaka_time=WakaTimeAuthorizationCode(client_id="aPJQV0op6Pu3b66MWDi9b1wB",client_secret="waka_sec_0c5MB",scope="email")withhttpx.Client()asclient:client.get('https://wakatime.com/api/v1/users/current',auth=waka_time)Note:You can persist tokens thanks tothe token cache.You can tweak web browser interaction thanks tothe display settings.ParametersNameDescriptionMandatoryDefault valueclient_idWakaTime Application Identifier (formatted as an Universal Unique Identifier).Mandatoryclient_secretWakaTime Application Secret (formatted as waka_sec_ followed by an Universal Unique Identifier).MandatoryscopeScope parameter sent in query. Can also be a list of scopes.Mandatoryresponse_typeValue of the response_type query parameter if not already provided in authorization URL.Optionaltokentoken_field_nameField name containing the token.Optionalaccess_tokenearly_expiryNumber 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.Optional30.0nonceRefer toOpenID ID Token specificationsfor more details.OptionalNewly generated Universal Unique Identifier.redirect_uri_domainFQDNto use in the redirect_uri when localhost is not allowed.Optionallocalhostredirect_uri_endpointCustom endpoint that will be used as redirect_uri the following way: http://<redirect_uri_domain>:<redirect_uri_port>/<redirect_uri_endpoint>.Optional''redirect_uri_portThe port on which the server listening for the OAuth 2 token will be started.Optional5000timeoutMaximum amount of seconds to wait for a token to be received once requested.Optional60header_nameName of the header field used to send token.OptionalAuthorizationheader_valueFormat used to send the token value. "{token}" must be present as it will be replaced by the actual token.OptionalBearer {token}clienthttpx.Clientinstance that will be used to request the token. Use it to provide a custom proxying rule for instance.OptionalAny other parameter will be put as query parameter in the authorization URL.Authorization Code Flow with Proof Key for Code ExchangeProof Key for Code Exchange is implemented followingrfc7636.Usehttpx_auth.OAuth2AuthorizationCodePKCEto configure this kind of authentication.importhttpxfromhttpx_authimportOAuth2AuthorizationCodePKCEwithhttpx.Client()asclient:client.get('https://www.example.com',auth=OAuth2AuthorizationCodePKCE('https://www.authorization.url','https://www.token.url'))Note:You can persist tokens thanks tothe token cache.You can tweak web browser interaction thanks tothe display settings.ParametersNameDescriptionMandatoryDefault valueauthorization_urlOAuth 2 authorization URL.Mandatorytoken_urlOAuth 2 token URL.Mandatoryredirect_uri_domainFQDNto use in the redirect_uri when localhost is not allowed.Optionallocalhostredirect_uri_endpointCustom endpoint that will be used as redirect_uri the following way: http://<redirect_uri_domain>:<redirect_uri_port>/<redirect_uri_endpoint>.Optional''redirect_uri_portThe port on which the server listening for the OAuth 2 code will be started.Optional5000timeoutMaximum amount of seconds to wait for a code or a token to be received once requested.Optional60header_nameName of the header field used to send token.OptionalAuthorizationheader_valueFormat used to send the token value. "{token}" must be present as it will be replaced by the actual token.OptionalBearer {token}response_typeValue of the response_type query parameter if not already provided in authorization URL.Optionalcodetoken_field_nameField name containing the token.Optionalaccess_tokenearly_expiryNumber 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.Optional30.0code_field_nameField name containing the code.Optionalcodeclienthttpx.Clientinstance that will be used to request the token. Use it to provide a custom proxying rule for instance.OptionalAny other parameter will be put as query parameter in the authorization URL and as body parameters in the token URL.Usual extra parameters are:NameDescriptionclient_idCorresponding to your Application ID (in Microsoft Azure app portal)client_secretIf client is not authenticated with the authorization servernonceRefer toOpenID ID Token specificationsfor more detailsCommon providersMost ofOAuth2Proof Key for Code Exchange providers are supported.If the one you are looking for is not yet supported, feel free toask for its implementation.Okta (OAuth2 Proof Key for Code Exchange)Okta Proof Key for Code Exchangeproviding access tokens is supported.Usehttpx_auth.OktaAuthorizationCodePKCEto configure this kind of authentication.importhttpxfromhttpx_authimportOktaAuthorizationCodePKCEokta=OktaAuthorizationCodePKCE(instance='testserver.okta-emea.com',client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd')withhttpx.Client()asclient:client.get('https://www.example.com',auth=okta)Note:You can persist tokens thanks tothe token cache.You can tweak web browser interaction thanks tothe display settings.ParametersNameDescriptionMandatoryDefault valueinstanceOkta instance (like "testserver.okta-emea.com").Mandatoryclient_idOkta Application Identifier (formatted as an Universal Unique Identifier).Mandatoryresponse_typeValue of the response_type query parameter if not already provided in authorization URL.Optionalcodetoken_field_nameField name containing the token.Optionalaccess_tokenearly_expiryNumber 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.Optional30.0code_field_nameField name containing the code.OptionalcodenonceRefer toOpenID ID Token specificationsfor more details.OptionalNewly generated Universal Unique Identifier.scopeScope parameter sent in query. Can also be a list of scopes.Optionalopenidauthorization_serverOkta authorization server.Optional'default'redirect_uri_domainFQDNto use in the redirect_uri when localhost is not allowed.Optionallocalhostredirect_uri_endpointCustom endpoint that will be used as redirect_uri the following way: http://<redirect_uri_domain>:<redirect_uri_port>/<redirect_uri_endpoint>.Optional''redirect_uri_portThe port on which the server listening for the OAuth 2 token will be started.Optional5000timeoutMaximum amount of seconds to wait for a token to be received once requested.Optional60header_nameName of the header field used to send token.OptionalAuthorizationheader_valueFormat used to send the token value. "{token}" must be present as it will be replaced by the actual token.OptionalBearer {token}clienthttpx.Clientinstance that will be used to request the token. Use it to provide a custom proxying rule for instance.OptionalAny other parameter will be put as query parameter in the authorization URL and as body parameters in the token URL.Usual extra parameters are:NameDescriptionclient_secretIf client is not authenticated with the authorization servernonceRefer toOpenID ID Token specificationsfor more detailsResource Owner Password Credentials flowResource Owner Password Credentials Grant is implemented followingrfc6749.Usehttpx_auth.OAuth2ResourceOwnerPasswordCredentialsto configure this kind of authentication.importhttpxfromhttpx_authimportOAuth2ResourceOwnerPasswordCredentialswithhttpx.Client()asclient:client.get('https://www.example.com',auth=OAuth2ResourceOwnerPasswordCredentials('https://www.token.url','user name','user password'))Note:You can persist tokens thanks tothe token cache.ParametersNameDescriptionMandatoryDefault valuetoken_urlOAuth 2 token URL.MandatoryusernameResource owner user name.MandatorypasswordResource owner password.Mandatoryclient_authClient 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.OptionaltimeoutMaximum amount of seconds to wait for a token to be received once requested.Optional60header_nameName of the header field used to send token.OptionalAuthorizationheader_valueFormat used to send the token value. "{token}" must be present as it will be replaced by the actual token.OptionalBearer {token}scopeScope parameter sent to token URL as body. Can also be a list of scopes.Optionaltoken_field_nameField name containing the token.Optionalaccess_tokenearly_expiryNumber 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.Optional30.0clienthttpx.Clientinstance that will be used to request the token. Use it to provide a custom proxying rule for instance.OptionalAny other parameter will be put as body parameter in the token URL.Common providersMost ofOAuth2Resource Owner Password Credentials providers are supported.If the one you are looking for is not yet supported, feel free toask for its implementation.Okta (OAuth2 Resource Owner Password Credentials)Okta Resource Owner Password Credentialsproviding access tokens is supported.Usehttpx_auth.OktaResourceOwnerPasswordCredentialsto configure this kind of authentication.importhttpxfromhttpx_authimportOktaResourceOwnerPasswordCredentialsokta=OktaResourceOwnerPasswordCredentials(instance='testserver.okta-emea.com',username='user name',password='user password',client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd',client_secret="0c5MB")withhttpx.Client()asclient:client.get('https://www.example.com',auth=okta)Note:You can persist tokens thanks tothe token cache.ParametersNameDescriptionMandatoryDefault valueinstanceOkta instance (like "testserver.okta-emea.com").MandatoryusernameResource owner user name.MandatorypasswordResource owner password.Mandatoryclient_idOkta Application Identifier (formatted as an Universal Unique Identifier).Mandatoryclient_secretResource owner password.MandatorytimeoutMaximum amount of seconds to wait for a token to be received once requested.Optional60header_nameName of the header field used to send token.OptionalAuthorizationheader_valueFormat used to send the token value. "{token}" must be present as it will be replaced by the actual token.OptionalBearer {token}scopeScope parameter sent in query. Can also be a list of scopes.Optionalopenidtoken_field_nameField name containing the token.Optionalaccess_tokenearly_expiryNumber 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.Optional30.0clienthttpx.Clientinstance that will be used to request the token. Use it to provide a custom proxying rule for instance.OptionalAny other parameter will be put as body parameters in the token URL.Client Credentials flowClient Credentials Grant is implemented followingrfc6749.Usehttpx_auth.OAuth2ClientCredentialsto configure this kind of authentication.importhttpxfromhttpx_authimportOAuth2ClientCredentialswithhttpx.Client()asclient:client.get('https://www.example.com',auth=OAuth2ClientCredentials('https://www.token.url',client_id='id',client_secret='secret'))Note:You can persist tokens thanks tothe token cache.ParametersNameDescriptionMandatoryDefault valuetoken_urlOAuth 2 token URL.Mandatoryclient_idResource owner user name.Mandatoryclient_secretResource owner password.MandatorytimeoutMaximum amount of seconds to wait for a token to be received once requested.Optional60header_nameName of the header field used to send token.OptionalAuthorizationheader_valueFormat used to send the token value. "{token}" must be present as it will be replaced by the actual token.OptionalBearer {token}scopeScope parameter sent to token URL as body. Can also be a list of scopes.Optionaltoken_field_nameField name containing the token.Optionalaccess_tokenearly_expiryNumber 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.Optional30.0clienthttpx.Clientinstance that will be used to request the token. Use it to provide a custom proxying rule for instance.OptionalAny other parameter will be put as body parameter in the token URL.Common providersMost ofOAuth2Client Credentials Grant providers are supported.If the one you are looking for is not yet supported, feel free toask for its implementation.Okta (OAuth2 Client Credentials)Okta Client Credentials Grantproviding access tokens is supported.Usehttpx_auth.OktaClientCredentialsto configure this kind of authentication.importhttpxfromhttpx_authimportOktaClientCredentialsokta=OktaClientCredentials(instance='testserver.okta-emea.com',client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd',client_secret="secret",scope=["scope1","scope2"])withhttpx.Client()asclient:client.get('https://www.example.com',auth=okta)Note:You can persist tokens thanks tothe token cache.ParametersNameDescriptionMandatoryDefault valueinstanceOkta instance (like "testserver.okta-emea.com").Mandatoryclient_idOkta Application Identifier (formatted as an Universal Unique Identifier).Mandatoryclient_secretResource owner password.MandatoryscopeScope parameter sent in query. Can also be a list of scopes.Mandatoryauthorization_serverOkta authorization server.Optional'default'timeoutMaximum amount of seconds to wait for a token to be received once requested.Optional60header_nameName of the header field used to send token.OptionalAuthorizationheader_valueFormat used to send the token value. "{token}" must be present as it will be replaced by the actual token.OptionalBearer {token}token_field_nameField name containing the token.Optionalaccess_tokenearly_expiryNumber 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.Optional30.0clienthttpx.Clientinstance that will be used to request the token. Use it to provide a custom proxying rule for instance.OptionalAny other parameter will be put as query parameter in the token URL.Implicit flowImplicit Grant is implemented followingrfc6749.Usehttpx_auth.OAuth2Implicitto configure this kind of authentication.importhttpxfromhttpx_authimportOAuth2Implicitwithhttpx.Client()asclient:client.get('https://www.example.com',auth=OAuth2Implicit('https://www.authorization.url'))Note:You can persist tokens thanks tothe token cache.You can tweak web browser interaction thanks tothe display settings.ParametersNameDescriptionMandatoryDefault valueauthorization_urlOAuth 2 authorization URL.Mandatoryresponse_typeValue of the response_type query parameter if not already provided in authorization URL.Optionaltokentoken_field_nameField name containing the token.Optionalid_token if response_type is id_token, otherwise access_tokenearly_expiryNumber 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.Optional30.0redirect_uri_domainFQDNto use in the redirect_uri when localhost is not allowed.Optionallocalhostredirect_uri_endpointCustom endpoint that will be used as redirect_uri the following way: http://<redirect_uri_domain>:<redirect_uri_port>/<redirect_uri_endpoint>.Optional''redirect_uri_portThe port on which the server listening for the OAuth 2 token will be started.Optional5000timeoutMaximum amount of seconds to wait for a token to be received once requested.Optional60header_nameName of the header field used to send token.OptionalAuthorizationheader_valueFormat used to send the token value. "{token}" must be present as it will be replaced by the actual token.OptionalBearer {token}Any other parameter will be put as query parameter in the authorization URL.Usual extra parameters are:NameDescriptionclient_idCorresponding to your Application ID (in Microsoft Azure app portal)nonceRefer toOpenID ID Token specificationsfor more detailspromptnone to avoid prompting the user if a session is already opened.Common providersMost ofOAuth2Implicit Grant providers are supported.If the one you are looking for is not yet supported, feel free toask for its implementation.Microsoft - Azure Active Directory (OAuth2 Access Token)Microsoft identity platform access tokensare supported.Usehttpx_auth.AzureActiveDirectoryImplicitto configure this kind of authentication.importhttpxfromhttpx_authimportAzureActiveDirectoryImplicitaad=AzureActiveDirectoryImplicit(tenant_id='45239d18-c68c-4c47-8bdd-ce71ea1d50cd',client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd')withhttpx.Client()asclient:client.get('https://www.example.com',auth=aad)Note:You can persist tokens thanks tothe token cache.You can tweak web browser interaction thanks tothe display settings.You can retrieve Microsoft Azure Active Directory application information thanks to theapplication list on Azure portal.ParametersNameDescriptionMandatoryDefault valuetenant_idMicrosoft Tenant Identifier (formatted as an Universal Unique Identifier).Mandatoryclient_idMicrosoft Application Identifier (formatted as an Universal Unique Identifier).Mandatoryresponse_typeValue of the response_type query parameter if not already provided in authorization URL.Optionaltokentoken_field_nameField name containing the token.Optionalaccess_tokenearly_expiryNumber 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.Optional30.0nonceRefer toOpenID ID Token specificationsfor more detailsOptionalNewly generated Universal Unique Identifier.redirect_uri_domainFQDNto use in the redirect_uri when localhost is not allowed.Optionallocalhostredirect_uri_endpointCustom endpoint that will be used as redirect_uri the following way: http://<redirect_uri_domain>:<redirect_uri_port>/<redirect_uri_endpoint>.Optional''redirect_uri_portThe port on which the server listening for the OAuth 2 token will be started.Optional5000timeoutMaximum amount of seconds to wait for a token to be received once requested.Optional60header_nameName of the header field used to send token.OptionalAuthorizationheader_valueFormat used to send the token value. "{token}" must be present as it will be replaced by the actual token.OptionalBearer {token}Any other parameter will be put as query parameter in the authorization URL.Usual extra parameters are:NameDescriptionpromptnone to avoid prompting the user if a session is already opened.Microsoft - Azure Active Directory (OpenID Connect ID token)Microsoft identity platform ID tokensare supported.Usehttpx_auth.AzureActiveDirectoryImplicitIdTokento configure this kind of authentication.importhttpxfromhttpx_authimportAzureActiveDirectoryImplicitIdTokenaad=AzureActiveDirectoryImplicitIdToken(tenant_id='45239d18-c68c-4c47-8bdd-ce71ea1d50cd',client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd')withhttpx.Client()asclient:client.get('https://www.example.com',auth=aad)Note:You can persist tokens thanks tothe token cache.You can tweak web browser interaction thanks tothe display settings.You can retrieve Microsoft Azure Active Directory application information thanks to theapplication list on Azure portal.ParametersNameDescriptionMandatoryDefault valuetenant_idMicrosoft Tenant Identifier (formatted as an Universal Unique Identifier).Mandatoryclient_idMicrosoft Application Identifier (formatted as an Universal Unique Identifier).Mandatoryresponse_typeValue of the response_type query parameter if not already provided in authorization URL.Optionalid_tokentoken_field_nameField name containing the token.Optionalid_tokenearly_expiryNumber 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.Optional30.0nonceRefer toOpenID ID Token specificationsfor more detailsOptionalNewly generated Universal Unique Identifier.redirect_uri_domainFQDNto use in the redirect_uri when localhost is not allowed.Optionallocalhostredirect_uri_endpointCustom endpoint that will be used as redirect_uri the following way: http://<redirect_uri_domain>:<redirect_uri_port>/<redirect_uri_endpoint>.Optional''redirect_uri_portThe port on which the server listening for the OAuth 2 token will be started.Optional5000timeoutMaximum amount of seconds to wait for a token to be received once requested.Optional60header_nameName of the header field used to send token.OptionalAuthorizationheader_valueFormat used to send the token value. "{token}" must be present as it will be replaced by the actual token.OptionalBearer {token}Any other parameter will be put as query parameter in the authorization URL.Usual extra parameters are:NameDescriptionpromptnone to avoid prompting the user if a session is already opened.Okta (OAuth2 Implicit Access Token)Okta Implicit Grantproviding access tokens is supported.Usehttpx_auth.OktaImplicitto configure this kind of authentication.importhttpxfromhttpx_authimportOktaImplicitokta=OktaImplicit(instance='testserver.okta-emea.com',client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd')withhttpx.Client()asclient:client.get('https://www.example.com',auth=okta)Note:You can persist tokens thanks tothe token cache.You can tweak web browser interaction thanks tothe display settings.ParametersNameDescriptionMandatoryDefault valueinstanceOkta instance (like "testserver.okta-emea.com").Mandatoryclient_idOkta Application Identifier (formatted as an Universal Unique Identifier).Mandatoryresponse_typeValue of the response_type query parameter if not already provided in authorization URL.Optionaltokentoken_field_nameField name containing the token.Optionalaccess_tokenearly_expiryNumber 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.Optional30.0nonceRefer toOpenID ID Token specificationsfor more details.OptionalNewly generated Universal Unique Identifier.scopeScope parameter sent in query. Can also be a list of scopes.Optional['openid', 'profile', 'email']authorization_serverOkta authorization server.Optional'default'redirect_uri_domainFQDNto use in the redirect_uri when localhost is not allowed.Optionallocalhostredirect_uri_endpointCustom endpoint that will be used as redirect_uri the following way: http://<redirect_uri_domain>:<redirect_uri_port>/<redirect_uri_endpoint>.Optional''redirect_uri_portThe port on which the server listening for the OAuth 2 token will be started.Optional5000timeoutMaximum amount of seconds to wait for a token to be received once requested.Optional60header_nameName of the header field used to send token.OptionalAuthorizationheader_valueFormat used to send the token value. "{token}" must be present as it will be replaced by the actual token.OptionalBearer {token}Any other parameter will be put as query parameter in the authorization URL.Usual extra parameters are:NameDescriptionpromptnone to avoid prompting the user if a session is already opened.Okta (OpenID Connect Implicit ID token)Okta Implicit Grantproviding ID tokens is supported.Usehttpx_auth.OktaImplicitIdTokento configure this kind of authentication.importhttpxfromhttpx_authimportOktaImplicitIdTokenokta=OktaImplicitIdToken(instance='testserver.okta-emea.com',client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd')withhttpx.Client()asclient:client.get('https://www.example.com',auth=okta)Note:You can persist tokens thanks tothe token cache.You can tweak web browser interaction thanks tothe display settings.ParametersNameDescriptionMandatoryDefault valueinstanceOkta instance (like "testserver.okta-emea.com").Mandatoryclient_idOkta Application Identifier (formatted as an Universal Unique Identifier).Mandatoryresponse_typeValue of the response_type query parameter if not already provided in authorization URL.Optionalid_tokentoken_field_nameField name containing the token.Optionalid_tokenearly_expiryNumber 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.Optional30.0nonceRefer toOpenID ID Token specificationsfor more details.OptionalNewly generated Universal Unique Identifier.scopeScope parameter sent in query. Can also be a list of scopes.Optional['openid', 'profile', 'email']authorization_serverOkta authorization server.Optional'default'redirect_uri_domainFQDNto use in the redirect_uri when localhost is not allowed.Optionallocalhostredirect_uri_endpointCustom endpoint that will be used as redirect_uri the following way: http://<redirect_uri_domain>:<redirect_uri_port>/<redirect_uri_endpoint>.Optional''redirect_uri_portThe port on which the server listening for the OAuth 2 token will be started.Optional5000timeoutMaximum amount of seconds to wait for a token to be received once requested.Optional60header_nameName of the header field used to send token.OptionalAuthorizationheader_valueFormat used to send the token value. "{token}" must be present as it will be replaced by the actual token.OptionalBearer {token}Any other parameter will be put as query parameter in the authorization URL.Usual extra parameters are:NameDescriptionpromptnone to avoid prompting the user if a session is already opened.Managing token cacheTo 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 (strorpathlib.Path).If the file already exists it will be used, if the file do not exist it will be created.fromhttpx_authimportOAuth2,JsonTokenFileCacheOAuth2.token_cache=JsonTokenFileCache('path/to/my_token_cache.json')Managing the web browserYou can configure the browser display settings thanks tohttpx_auth.OAuth2.displayas in the following:fromhttpx_authimportOAuth2,DisplaySettingsOAuth2.display=DisplaySettings()The following parameters can be provided toDisplaySettings:NameDescriptionDefault valuesuccess_display_timeIn case a code or token is successfully received, this is the maximum amount of milliseconds the success page will be displayed in your browser.1success_htmlIn 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_timeIn 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_000failure_htmlIn 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.AWS Signature v4Amazon Web Service Signature version 4 is implemented followingAmazon S3 documentationandrequest-aws4auth 1.2.3(with some changes, see below).Usehttpx_auth.AWS4Authto configure this kind of authentication.importhttpxfromhttpx_authimportAWS4Authaws=AWS4Auth(access_id="my-access-id",secret_key="my-secret-key",region="eu-west-1",service="s3")withhttpx.Client()asclient:client.get('http://s3-eu-west-1.amazonaws.com',auth=aws)Note that the following changes were made compared torequests-aws4auth:Each request now has its own signing key andx-amz-date. Meaningyou can use the same auth instance for more than one request.session_tokenwas renamed intosecurity_tokenfor consistency with the underlying name at Amazon.include_hdrsparameter was renamed intoinclude_headers. When using this parameter:Provided values will not be stripped,WYSIWYG.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 forrequests-aws4auth.amz_dateattribute has been removed.It is not possible to provide adate. It will default to now.It is not possible to provide anAWSSigningKeyinstance, use explicit parameters instead.It is not possible to provideraise_invalid_dateparameter anymore as the date will always be valid.hostis 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.ParametersNameDescriptionMandatoryDefault valueaccess_idAWS access ID.Mandatorysecret_keyAWS secret access key.MandatoryregionThe region you are connecting to, as perthis list. For services which do not require a region (e.g. IAM), use us-east-1.MandatoryserviceThe name of the service you are connecting to, as perthis list. e.g. elasticbeanstalk.Mandatorysecurity_tokenUsed for thex-amz-security-tokenheader, for use with STS temporary credentials.Optionalinclude_headersSet of headers to include in the canonical and signed headers (in addition to the default). Note thatx-amz-client-contextis not included by default and*will include all headers.Optional{"host", "content-type", "x-amz-*"} and ifsecurity_tokenis provided,x-amz-security-token.Dynamically retrieving credentials using boto3Whilehttpx-authdoes not want to include support forbotocore, the following authentication class should allow you to automatically retrieve up-to-date credentials.importhttpxfrombotocore.sessionimportSessionfromhttpx_authimportAWS4AuthclassAWS4BotoAuth(AWS4Auth):def__init__(self,region:str,service:str="s3",**kwargs):self.refreshable_credentials=Session().get_credentials()AWS4Auth.__init__(self,access_id=kwargs.pop("access_id","_"),secret_key=kwargs.pop("secret_key","_"),region=region,service=service,**kwargs)defauth_flow(self,request):self.refresh_credentials()yieldsuper().auth_flow(request)defrefresh_credentials(self):credentials=self.refreshable_credentials.get_frozen_credentials()self.access_id=credentials.access_keyself.secret_key=credentials.secret_keyself.security_token=credentials.tokenaws=AWS4BotoAuth(region="eu-west-1")withhttpx.Client()asclient:client.get('http://s3-eu-west-1.amazonaws.com',auth=aws)API key in headerYou can send an API key inside the header of your request usinghttpx_auth.HeaderApiKey.importhttpxfromhttpx_authimportHeaderApiKeywithhttpx.Client()asclient:client.get('https://www.example.com',auth=HeaderApiKey('my_api_key'))ParametersNameDescriptionMandatoryDefault valueapi_keyThe API key that will be sent.Mandatoryheader_nameName of the header field.Optional"X-API-Key"API key in queryYou can send an API key inside the query parameters of your request usinghttpx_auth.QueryApiKey.importhttpxfromhttpx_authimportQueryApiKeywithhttpx.Client()asclient:client.get('https://www.example.com',auth=QueryApiKey('my_api_key'))ParametersNameDescriptionMandatoryDefault valueapi_keyThe API key that will be sent.Mandatoryquery_parameter_nameName of the query parameter.Optional"api_key"BasicYou can use basic authentication usinghttpx_auth.Basic.The only advantage of using this class instead ofhttpxnative support of basic authentication, is to be able to use it inmultiple authentication.importhttpxfromhttpx_authimportBasicwithhttpx.Client()asclient:client.get('https://www.example.com',auth=Basic('username','password'))ParametersNameDescriptionMandatoryDefault valueusernameUser name.MandatorypasswordUser password.MandatoryMultiple authentication at onceYou can also use a combination of authentication using+or&as in the following sample:importhttpxfromhttpx_authimportHeaderApiKey,OAuth2Implicitapi_key=HeaderApiKey('my_api_key')oauth2=OAuth2Implicit('https://www.example.com')withhttpx.Client()asclient:client.get('https://www.example.com',auth=api_key+oauth2)This is supported on every authentication class exposed byhttpx_auth, but you can also enable it on your own authentication classes by usinghttpx_auth.SupportMultiAuthas in the following sample:fromhttpx_authimportSupportMultiAuth# TODO Import your own auth herefrommy_packageimportMyAuthclassMyMultiAuth(MyAuth,SupportMultiAuth):passAvailable pytest fixturesTesting the code usinghttpx_authauthentication classes can be achieved using providedpytestfixtures.token_cache_mockfromhttpx_auth.testingimporttoken_cache_mock,token_mockdeftest_something(token_cache_mock):# perform code using authenticationpassUse this fixture to mock authentication success for any of the following classes:OAuth2AuthorizationCodePKCEOktaAuthorizationCodePKCEOAuth2ImplicitOktaImplicitOktaImplicitIdTokenAzureActiveDirectoryImplicitAzureActiveDirectoryImplicitIdTokenOAuth2AuthorizationCodeOktaAuthorizationCodeWakaTimeAuthorizationCodeOAuth2ClientCredentialsOktaClientCredentialsOAuth2ResourceOwnerPasswordCredentialsOktaResourceOwnerPasswordCredentialsBy default, an access token with value2YotnFZFEjr1zCsicMWpAAis generated.You can however return your custom token by providing your owntoken_mockfixture as in the following sample:importpytestfromhttpx_auth.testingimporttoken_cache_mock@pytest.fixturedeftoken_mock()->str:return"MyCustomTokenValue"deftest_something(token_cache_mock):# perform code using authenticationpassYou can even return a more complex token by using thecreate_tokenfunction.Note thatpyjwtis a required dependency in this case as it is used to generate the token returned by the authentication.importpytestfromhttpx_auth.testingimporttoken_cache_mock,create_token@pytest.fixturedeftoken_mock()->str:expiry=None# TODO Compute your expiryreturncreate_token(expiry)deftest_something(token_cache_mock):# perform code using authenticationpassAdvanced testingtoken_cacheThispytestfixture will return the token cache and ensure it is reset at the end of the test case.fromhttpx_auth.testingimporttoken_cachedeftest_something(token_cache):# perform code using authenticationpassbrowser_mockThispytestfixture will allow to mock the behavior of a web browser.With thispytestfixture you will be allowed to fine tune your authentication related failures handling.pyjwtis a required dependency if you usecreate_tokenhelper function.importdatetimefromhttpx_auth.testingimportbrowser_mock,BrowserMock,create_tokendeftest_something(browser_mock:BrowserMock):token_expiry=datetime.datetime.now(datetime.timezone.utc)+datetime.timedelta(hours=1)token=create_token(token_expiry)tab=browser_mock.add_response(opened_url="http://url_opened_by_browser?state=1234",reply_url=f"http://localhost:5000#access_token={token}&state=1234",)# perform code using authenticationtab.assert_success()