Python requests auth windows

This document discusses using various kinds of authentication with Requests.

Many web services require authentication, and there are many different types.
Below, we outline various forms of authentication available in Requests, from
the simple to the complex.

Basic Authentication¶

Many web services that require authentication accept HTTP Basic Auth. This is
the simplest kind, and Requests supports it straight out of the box.

Making requests with HTTP Basic Auth is very simple:

>>> from requests.auth import HTTPBasicAuth
>>> basic = HTTPBasicAuth('user', 'pass')
>>> requests.get('https://httpbin.org/basic-auth/user/pass', auth=basic)
<Response [200]>

In fact, HTTP Basic Auth is so common that Requests provides a handy shorthand
for using it:

>>> requests.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass'))
<Response [200]>

Providing the credentials in a tuple like this is exactly the same as the
HTTPBasicAuth example above.

netrc Authentication¶

If no authentication method is given with the auth argument, Requests will
attempt to get the authentication credentials for the URL’s hostname from the
user’s netrc file. The netrc file overrides raw HTTP authentication headers
set with headers=.

If credentials for the hostname are found, the request is sent with HTTP Basic
Auth.

Digest Authentication¶

Another very popular form of HTTP Authentication is Digest Authentication,
and Requests supports this out of the box as well:

>>> from requests.auth import HTTPDigestAuth
>>> url = 'https://httpbin.org/digest-auth/auth/user/pass'
>>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))
<Response [200]>

OAuth 1 Authentication¶

A common form of authentication for several web APIs is OAuth. The requests-oauthlib
library allows Requests users to easily make OAuth 1 authenticated requests:

>>> import requests
>>> from requests_oauthlib import OAuth1

>>> url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
>>> auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET',
...               'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET')

>>> requests.get(url, auth=auth)
<Response [200]>

For more information on how to OAuth flow works, please see the official OAuth website.
For examples and documentation on requests-oauthlib, please see the requests_oauthlib
repository on GitHub

OAuth 2 and OpenID Connect Authentication¶

The requests-oauthlib library also handles OAuth 2, the authentication mechanism
underpinning OpenID Connect. See the requests-oauthlib OAuth2 documentation for
details of the various OAuth 2 credential management flows:

  • Web Application Flow

  • Mobile Application Flow

  • Legacy Application Flow

  • Backend Application Flow

Other Authentication¶

Requests is designed to allow other forms of authentication to be easily and
quickly plugged in. Members of the open-source community frequently write
authentication handlers for more complicated or less commonly-used forms of
authentication. Some of the best have been brought together under the
Requests organization, including:

  • Kerberos

  • NTLM

If you want to use any of these forms of authentication, go straight to their
GitHub page and follow the instructions.

New Forms of Authentication¶

If you can’t find a good implementation of the form of authentication you
want, you can implement it yourself. Requests makes it easy to add your own
forms of authentication.

To do so, subclass AuthBase and implement the
__call__() method:

>>> import requests
>>> class MyAuth(requests.auth.AuthBase):
...     def __call__(self, r):
...         # Implement my authentication
...         return r
...
>>> url = 'https://httpbin.org/get'
>>> requests.get(url, auth=MyAuth())
<Response [200]>

When an authentication handler is attached to a request,
it is called during request setup. The __call__ method must therefore do
whatever is required to make the authentication work. Some forms of
authentication will additionally add hooks to provide further functionality.

Further examples can be found under the Requests organization and in the
auth.py file.

Authentication for Requests

Provides authentication classes to be used with requests authentication parameter.

Okta

Some of the supported authentication

Available authentication

  • OAuth2
    • Authorization Code Flow
      • Okta
    • Authorization Code Flow with PKCE
      • Okta
    • Resource Owner Password Credentials flow
    • Client Credentials Flow
      • Okta
    • Implicit Flow
      • Microsoft Entra (Access Token)
      • Microsoft Entra (ID token)
      • Okta (Access Token)
      • Okta (ID token)
    • Managing token cache
    • Managing browser
  • API key
    • In header
    • In query
  • Basic
  • NTLM (Windows)
  • Multiple authentication at once
  • Endorsements

OAuth 2

Most of OAuth2 flows are supported.

If the one you are looking for is not yet supported, feel free to ask for its implementation.

Authorization Code Grant is implemented following rfc6749.

Use requests_auth.OAuth2AuthorizationCode to configure this kind of authentication.

import requests
from requests_auth import OAuth2AuthorizationCode

requests.get('https://www.example.com', auth=OAuth2AuthorizationCode('https://www.authorization.url', 'https://www.token.url'))

Note:

  • You can persist tokens thanks to the token cache.
  • You can tweak web browser interaction thanks to the display settings.

Parameters

Name Description Mandatory Default value
authorization_url OAuth 2 authorization URL. Mandatory  
token_url OAuth 2 token URL. Mandatory  
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://:/. 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  
session requests.Session 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
nonce Refer to OpenID ID Token specifications for more details

Common providers

Most of OAuth2 Authorization Code Grant providers are supported.

If the one you are looking for is not yet supported, feel free to ask for its implementation.

Okta (OAuth2 Authorization Code)

Okta Authorization Code Grant providing access tokens is supported.

Use requests_auth.OktaAuthorizationCode to configure this kind of authentication.

import requests
from requests_auth import OktaAuthorizationCode


okta = OktaAuthorizationCode(instance='testserver.okta-emea.com', client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd')
requests.get('https://www.example.com', auth=okta)

Note:

  • You can persist tokens thanks to the token cache.
  • You can tweak web browser interaction thanks to the display settings.
Parameters
Name Description Mandatory Default value
instance Okta instance (like “testserver.okta-emea.com”). Mandatory  
client_id 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. Optional 30.0
nonce Refer to OpenID ID Token specifications for more details. Optional Newly generated Universal Unique Identifier.
scope Scope parameter sent in query. Can also be a list of scopes. Optional openid
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://:/. 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}
session requests.Session 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.

Usual extra parameters are:

Name Description
prompt none to avoid prompting the user if a session is already opened.
WakaTime (OAuth2 Authorization Code)

WakaTime Authorization Code Grant providing access tokens is supported.

Use requests_auth.WakaTimeAuthorizationCode to configure this kind of authentication.

import requests
from requests_auth import WakaTimeAuthorizationCode


waka_time = WakaTimeAuthorizationCode(client_id="aPJQV0op6Pu3b66MWDi9b1wB", client_secret="waka_sec_0c5MB", scope="email")
requests.get('https://wakatime.com/api/v1/users/current', auth=waka_time)

Note:

  • You can persist tokens thanks to the token cache.
  • You can tweak web browser interaction thanks to the display settings.
Parameters
Name Description Mandatory Default value
client_id 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. Optional 30.0
nonce Refer to OpenID ID Token specifications for more details. Optional Newly generated Universal Unique Identifier.
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://:/. 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}
session requests.Session 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 requests_auth.OAuth2AuthorizationCodePKCE to configure this kind of authentication.

import requests
from requests_auth import OAuth2AuthorizationCodePKCE

requests.get('https://www.example.com', auth=OAuth2AuthorizationCodePKCE('https://www.authorization.url', 'https://www.token.url'))

Note:

  • You can persist tokens thanks to the token cache.
  • You can tweak web browser interaction thanks to the display settings.

Parameters

Name Description Mandatory Default value
authorization_url OAuth 2 authorization URL. Mandatory  
token_url OAuth 2 token URL. Mandatory  
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://:/. 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
session requests.Session 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
nonce Refer to OpenID ID Token specifications for more details

Common providers

Most of OAuth2 Proof Key for Code Exchange providers are supported.

If the one you are looking for is not yet supported, feel free to ask for its implementation.

Okta (OAuth2 Proof Key for Code Exchange)

Okta Proof Key for Code Exchange providing access tokens is supported.

Use requests_auth.OktaAuthorizationCodePKCE to configure this kind of authentication.

import requests
from requests_auth import OktaAuthorizationCodePKCE


okta = OktaAuthorizationCodePKCE(instance='testserver.okta-emea.com', client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd')
requests.get('https://www.example.com', auth=okta)

Note:

  • You can persist tokens thanks to the token cache.
  • You can tweak web browser interaction thanks to the display settings.
Parameters
Name Description Mandatory Default value
instance Okta instance (like “testserver.okta-emea.com”). Mandatory  
client_id 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. Optional 30.0
code_field_name Field name containing the code. Optional code
nonce Refer to OpenID ID Token specifications for more details. Optional Newly generated Universal Unique Identifier.
scope Scope parameter sent in query. Can also be a list of scopes. Optional openid
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://:/. 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}
session requests.Session 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_secret If client is not authenticated with the authorization server
nonce Refer to OpenID ID Token specifications for more details

Resource Owner Password Credentials flow

Resource Owner Password Credentials Grant is implemented following rfc6749.

Use requests_auth.OAuth2ResourceOwnerPasswordCredentials to configure this kind of authentication.

import requests
from requests_auth import OAuth2ResourceOwnerPasswordCredentials

requests.get('https://www.example.com', auth=OAuth2ResourceOwnerPasswordCredentials('https://www.token.url', 'user name', 'user password'))

Note:

  • You can persist tokens thanks to the token cache.

Parameters

Name Description Mandatory Default value
token_url OAuth 2 token URL. Mandatory  
username Resource owner user name. Mandatory  
password Resource owner password. Mandatory  
session_auth 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 requests 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
session requests.Session 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.

If the one you are looking for is not yet supported, feel free to ask for its implementation.

Okta (OAuth2 Resource Owner Password Credentials)

Okta Resource Owner Password Credentials providing access tokens is supported.

Use requests_auth.OktaResourceOwnerPasswordCredentials to configure this kind of authentication.

import requests
from requests_auth import OktaResourceOwnerPasswordCredentials


okta = OktaResourceOwnerPasswordCredentials(instance='testserver.okta-emea.com', username='user name', password='user password', client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd', client_secret="0c5MB")
requests.get('https://www.example.com', auth=okta)

Note:

  • You can persist tokens thanks to the token cache.
Parameters
Name Description Mandatory Default value
instance Okta instance (like “testserver.okta-emea.com”). Mandatory  
username Resource owner user name. Mandatory  
password Resource owner password. Mandatory  
client_id 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
session requests.Session 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 requests_auth.OAuth2ClientCredentials to configure this kind of authentication.

import requests
from requests_auth import OAuth2ClientCredentials

requests.get('https://www.example.com', auth=OAuth2ClientCredentials('https://www.token.url', client_id='id', client_secret='secret'))

Note:

  • You can persist tokens thanks to the token cache.

Parameters

Name Description Mandatory Default value
token_url OAuth 2 token URL. Mandatory  
client_id Resource owner user name. 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 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
session requests.Session 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.

If the one you are looking for is not yet supported, feel free to ask for its implementation.

Okta (OAuth2 Client Credentials)

Okta Client Credentials Grant providing access tokens is supported.

Use requests_auth.OktaClientCredentials to configure this kind of authentication.

import requests
from requests_auth import OktaClientCredentials


okta = OktaClientCredentials(instance='testserver.okta-emea.com', client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd', client_secret="secret", scope=["scope1", "scope2"])
requests.get('https://www.example.com', auth=okta)

Note:

  • You can persist tokens thanks to the token cache.
Parameters
Name Description Mandatory Default value
instance Okta instance (like “testserver.okta-emea.com”). Mandatory  
client_id 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
session requests.Session 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.

Implicit flow

Implicit Grant is implemented following rfc6749.

Use requests_auth.OAuth2Implicit to configure this kind of authentication.

import requests
from requests_auth import OAuth2Implicit

requests.get('https://www.example.com', auth=OAuth2Implicit('https://www.authorization.url'))

Note:

  • You can persist tokens thanks to the token cache.
  • You can tweak web browser interaction thanks to the display settings.

Parameters

Name Description Mandatory Default value
authorization_url OAuth 2 authorization URL. 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 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://:/. 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)
nonce Refer to OpenID ID Token specifications for more details
prompt none to avoid prompting the user if a session is already opened.

Common providers

Most of OAuth2 Implicit Grant providers are supported.

If the one you are looking for is not yet supported, feel free to ask for its implementation.

Microsoft — Azure Active Directory (OAuth2 Access Token)

Microsoft identity platform access tokens are supported.

Use requests_auth.AzureActiveDirectoryImplicit to configure this kind of authentication.

import requests
from requests_auth import AzureActiveDirectoryImplicit


aad = AzureActiveDirectoryImplicit(tenant_id='45239d18-c68c-4c47-8bdd-ce71ea1d50cd', client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd')
requests.get('https://www.example.com', auth=aad)

Note:

  • You can persist tokens thanks to the token cache.
  • You can tweak web browser interaction thanks to the display settings.

You can retrieve Microsoft Azure Active Directory application information thanks to the application list on Azure portal.

Parameters
Name Description Mandatory Default value
tenant_id 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. Optional 30.0
nonce Refer to OpenID ID Token specifications for more details Optional Newly generated Universal Unique Identifier.
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://:/. 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.
Microsoft — Azure Active Directory (OpenID Connect ID token)

Microsoft identity platform ID tokens are supported.

Use requests_auth.AzureActiveDirectoryImplicitIdToken to configure this kind of authentication.

import requests
from requests_auth import AzureActiveDirectoryImplicitIdToken


aad = AzureActiveDirectoryImplicitIdToken(tenant_id='45239d18-c68c-4c47-8bdd-ce71ea1d50cd', client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd')
requests.get('https://www.example.com', auth=aad)

Note:

  • You can persist tokens thanks to the token cache.
  • You can tweak web browser interaction thanks to the display settings.

You can retrieve Microsoft Azure Active Directory application information thanks to the application list on Azure portal.

Parameters
Name Description Mandatory Default value
tenant_id 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. Optional 30.0
nonce Refer to OpenID ID Token specifications for more details Optional Newly generated Universal Unique Identifier.
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://:/. 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.
Okta (OAuth2 Implicit Access Token)

Okta Implicit Grant providing access tokens is supported.

Use requests_auth.OktaImplicit to configure this kind of authentication.

import requests
from requests_auth import OktaImplicit


okta = OktaImplicit(instance='testserver.okta-emea.com', client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd')
requests.get('https://www.example.com', auth=okta)

Note:

  • You can persist tokens thanks to the token cache.
  • You can tweak web browser interaction thanks to the display settings.
Parameters
Name Description Mandatory Default value
instance Okta instance (like “testserver.okta-emea.com”). Mandatory  
client_id 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. Optional 30.0
nonce Refer to OpenID ID Token specifications for more details. Optional Newly generated Universal Unique Identifier.
scope 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://:/. 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.
Okta (OpenID Connect Implicit ID token)

Okta Implicit Grant providing ID tokens is supported.

Use requests_auth.OktaImplicitIdToken to configure this kind of authentication.

import requests
from requests_auth import OktaImplicitIdToken


okta = OktaImplicitIdToken(instance='testserver.okta-emea.com', client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd')
requests.get('https://www.example.com', auth=okta)

Note:

  • You can persist tokens thanks to the token cache.
  • You can tweak web browser interaction thanks to the display settings.
Parameters
Name Description Mandatory Default value
instance Okta instance (like “testserver.okta-emea.com”). Mandatory  
client_id 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. Optional 30.0
nonce Refer to OpenID ID Token specifications for more details. Optional Newly generated Universal Unique Identifier.
scope 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://:/. 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 requests_auth import OAuth2, JsonTokenFileCache

OAuth2.token_cache = JsonTokenFileCache('path/to/my_token_cache.json')

Managing the web browser

You can configure the browser display settings thanks to requests_auth.OAuth2.display as in the following:

from requests_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.  

You can send an API key inside the header of your request using requests_auth.HeaderApiKey.

import requests
from requests_auth import HeaderApiKey

requests.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 requests_auth.QueryApiKey.

import requests
from requests_auth import QueryApiKey

requests.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 requests_auth.Basic.

The only advantage of using this class instead of requests native support of basic authentication, is to be able to use it in multiple authentication.

import requests
from requests_auth import Basic

requests.get('https://www.example.com', auth=Basic('username', 'password'))

Parameters

Name Description Mandatory Default value
username User name. Mandatory  
password User password. Mandatory  

NTLM

Requires requests-negotiate-sspi module or requests_ntlm module depending on provided parameters.

You can use Windows authentication using requests_auth.NTLM.

import requests
from requests_auth import NTLM

requests.get('https://www.example.com', auth=NTLM())

Parameters

Name Description Mandatory Default value
username User name. Mandatory if requests_negotiate_sspi module is not installed. In such a case requests_ntlm module is mandatory.  
password User password. Mandatory if requests_negotiate_sspi module is not installed. In such a case requests_ntlm module is mandatory.  

Multiple authentication at once

You can also use a combination of authentication using + or & as in the following sample:

import requests
from requests_auth import HeaderApiKey, OAuth2Implicit

api_key = HeaderApiKey('my_api_key')
oauth2 = OAuth2Implicit('https://www.example.com')
requests.get('https://www.example.com', auth=api_key + oauth2)

This is supported on every authentication class exposed by requests_auth, but you can also enable it on your own authentication classes by using requests_auth.SupportMultiAuth as in the following sample:

from requests_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 requests_auth authentication classes can be achieved using provided pytest fixtures.

token_cache_mock

from requests_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
  • OAuth2ClientCredentials
  • OktaClientCredentials
  • OAuth2ResourceOwnerPasswordCredentials,

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:

import pytest

from requests_auth.testing import token_cache_mock


@pytest.fixture
def token_mock() -> str:
    return "MyCustomTokenValue"


def test_something(token_cache_mock):
    # perform code using authentication
    pass

You can even return a more complex token by using the create_token function.

Note that pyjwt is a required dependency in this case as it is used to generate the token returned by the authentication.

import pytest

from requests_auth.testing import token_cache_mock, create_token


@pytest.fixture
def token_mock() -> str:
    expiry = None  # TODO Compute your expiry
    return create_token(expiry)


def test_something(token_cache_mock):
    # perform code using authentication
    pass

Advanced testing

token_cache

This pytest fixture will return the token cache and ensure it is reset at the end of the test case.

from requests_auth.testing import token_cache

def test_something(token_cache):
    # perform code using authentication
    pass

browser_mock

This pytest fixture will allow to mock the behavior of a web browser.

With this pytest fixture you will be allowed to fine tune your authentication related failures handling.

pyjwt is a required dependency if you use create_token helper function.

import datetime

from requests_auth.testing import browser_mock, BrowserMock, create_token

def test_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 authentication

    tab.assert_success()

Endorsements

I love requests_auth. As a ~15 year pythonista, this library makes working with OAuth services a breeze. <333

Randall Degges, Head of Evangelism, Okta

Last Updated :
05 Mar, 2020

Authentication refers to giving a user permissions to access a particular resource. Since, everyone can’t be allowed to access data from every URL, one would require authentication primarily. To achieve this authentication, typically one provides authentication data through Authorization header or a custom header defined by server.

Example –

import requests

from requests.auth import HTTPBasicAuth

            auth = HTTPBasicAuth('user', 'pass'))

print(response)

Replace “user” and “pass” with your username and password. It will authenticate the request and return a response 200 or else it will return error 403.

authenticate-python-requests

If you an invalid username or password, it will return an error as –

autentication-python-requests

Types of Authentication

Digest Authentication
Another very popular form of HTTP Authentication is Digest Authentication, and Requests supports this out of the box as well:

>>> from requests.auth import HTTPDigestAuth
>>> url = 'https://httpbin.org/digest-auth/auth/user/pass'
>>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))

OAuth 1 Authentication
A common form of authentication for several web APIs is OAuth. The requests-oauthlib library allows Requests users to easily make OAuth 1 authenticated requests:

>>> import requests
>>> from requests_oauthlib import OAuth1

>>> url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
>>> auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET',
...               'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET')

>>> requests.get(url, auth=auth)

For more information on how to OAuth flow works, please see the official OAuth website. For examples and documentation on requests-oauthlib, please see the requests_oauthlib repository on GitHub

OAuth 2 and OpenID Connect Authentication
The requests-oauthlib library also handles OAuth 2, the authentication mechanism underpinning OpenID Connect. See the requests-oauthlib OAuth2 documentation for details of the various OAuth 2 credential management flows:

  • Web Application Flow
  • Mobile Application Flow
  • Legacy Application Flow
  • Backend Application Flow

Other Authentication
Requests is designed to allow other forms of authentication to be easily and quickly plugged in. Members of the open-source community frequently write authentication handlers for more complicated or less commonly-used forms of authentication. Some of the best have been brought together under the Requests organization, including:

  • Kerberos
  • NTLM.

If you want to use any of these forms of authentication, go straight to their GitHub page and follow the instructions.

If you are working with a Microsoft Windows-based web server, you may encounter NTLM authentication when making requests to the API. NTLM is a Microsoft proprietary protocol used for authentication between clients and servers. In order to make requests with NTLM authentication in Python, you need to use the Requests library.

Here is an example of how to perform NTLM authentication with Requests:


import requests
from requests_ntlm import HttpNtlmAuth

url = 'https://example.com/api'
username = 'your_username'
password = 'your_password'
response = requests.get(url, auth=HttpNtlmAuth(username, password))
print(response.text)
    

In this example, we first import the Requests library and the HttpNtlmAuth class from requests_ntlm. We then define the URL of the API we want to access, as well as the username and password for the NTLM authentication.

We make a GET request to the API using the requests.get() function and pass in the URL and the HttpNtlmAuth object with our username and password. The response is stored in the response variable and we print the text content of the response using response.text.

If you are using a proxy server, you can also pass the HttpNtlmAuth object as the auth parameter to the proxies argument:


import requests
from requests_ntlm import HttpNtlmAuth

url = 'https://example.com/api'
username = 'your_username'
password = 'your_password'
proxies = {'https': 'http://your_proxy_server:port'}
response = requests.get(url, auth=HttpNtlmAuth(username, password), proxies=proxies)
print(response.text)
    

Here, we define the proxies dictionary with the URL of our proxy server and pass it as the proxies parameter to the requests.get() function.

Another way to perform NTLM authentication is by using the requests_negotiate_sspi library:


import requests
from requests_negotiate_sspi import HttpNegotiateAuth

url = 'https://example.com/api'
response = requests.get(url, auth=HttpNegotiateAuth())
print(response.text)
    

In this case, we import the HttpNegotiateAuth class from requests_negotiate_sspi and pass it as the auth parameter to the requests.get() function. This will perform NTLM authentication using the SSPI security package on Windows.

These are some ways to perform NTLM authentication in Python using the Requests library. Make sure you have the necessary libraries installed before running the code.

Recently I was working on a unit project to realize python automation, but in the first step, I was turned away. I checked the information and asked the big guys and asked our developers. It was done from Monday to Friday.

Next to share with you

Project background: Our system is implemented based on the Windows platform, and the login method is Windows identity authentication

1. Web login mode, selenium module implementation

1. I originally wanted to use selenium to achieve it. Can I use WinSpy to locate it on the web and use pywin32 to achieve it. I tried it and found that the tool WinSpy could not locate my login window at all. The entire black positioning frame could not locate the login pop-up window. The Autoit method mentioned is probably similar to this one. It is all operating Windows windows. I don’t know how to do it. I didn’t study it to understand, as shown in the figure:

2. In the middle, I also thought about using the requests library to request and obtain the cookie (the second method below). The requests library initiates the request, returns the Set-Cookie in the request header, uses the sessionid in the Set-Cookie and other When the webdriver in selenium initiates a request, it will bring a series of parameters such as sessionid, and use this method to achieve Windows authentication, but it still doesn’t work. It will report an error directly, saying it is an invalid cookie domain. , The specific error message is as follows:

3. The web method is even more exotic. It took me a week and a half. After consulting our little Jane and Benben, it still hasn’t been settled. It’s not my mentality. Self-confidence is completely destroyed. I browsed through search sites such as Baidu and Bing. During the period, my classmate L was always with me to help me solve the problem, including the implementation steps, screenshots, and videos. Finally, I finally got it done. Let me tell you that some students will encounter Windows identity authentication in the future, and they can use this method for login authentication.

In fact, the principle is very simple, and I have seen a post to talk about this method, which is to write the user name and password into the url, but I was unsuccessful at the time. The key lies in the special characters.

The syntax is:http://username:password@url

The implementation code is as follows, for example:

from selenium import webdriver


driver = webdriver.Chrome()
url = r"http://d%5cyuaxxx:[email protected]/"  # The user name contains special symbols, which is the escaped user name
driver.get(url)

Be careful here, if your username and password contain special characters, such as:! @#¥%……&*Wait,Must be converted to UrlEncode format, Otherwise the login must be unsuccessful, a history of blood and tears

Special thanks to my sister L. I can’t solve this problem without her.

Provide a transcoded URL:https://tool.chinaz.com/tools/urlencode.aspx

For example: «admin@1234» this string, after transcoding:

Second, use the requests library in python to implement Windows authentication login

First install the requests library, requests_ntlm library

pip install requests
pip install requests_ntlm

Log in as Windows

import requests
from requests_ntlm import HttpNtlmAuth

requests.get("http://xxx.com",auth=HttpNtlmAuth('domain\\username','pwd'))

for example:

Login is successful, and you can get some information such as header request header, sessionid, etc.

Reference article:https://www.cnblogs.com/xbzhu/p/7743584.html

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как распечатать картинку на нескольких листах а4 на принтере windows 10
  • Как добавить иконку bluetooth в панель задач windows 10
  • Майнкрафт windows 10 текстур пак
  • How to delete onedrive from windows 10
  • Как самому подписать драйвер windows 10