Python requests access token

OAuth for Requests¶

Requests is a very popular HTTP library for Python. Authlib enables OAuth 1.0 and OAuth 2.0 for Requests with its OAuth1Session , OAuth2Session and AssertionSession .

Requests OAuth 1.0¶

There are three steps in OAuth 1 Session to obtain an access token:

  1. fetch a temporary credential
  2. visit the authorization page
  3. exchange access token with the temporary credential

It shares a common API design with OAuth for HTTPX .

OAuth1Session¶

The requests integration follows our common guide of OAuth 1 Session . Follow the documentation in OAuth 1 Session instead.

OAuth1Auth¶

It is also possible to use OAuth1Auth directly with in requests. After we obtained access token from an OAuth 1.0 provider, we can construct an auth instance for requests:

auth = OAuth1Auth( client_id='YOUR-CLIENT-ID', client_secret='YOUR-CLIENT-SECRET', token='oauth_token', token_secret='oauth_token_secret', ) requests.get(url, auth=auth) 

Requests OAuth 2.0¶

In OAuth 2 Session , there are many grant types, including:

  1. Authorization Code Flow
  2. Implicit Flow
  3. Password Flow
  4. Client Credentials Flow

And also, Authlib supports non Standard OAuth 2.0 providers via Compliance Fix.

Follow the common guide of OAuth 2 Session to find out how to use requests integration of OAuth 2.0 flow.

Using client_secret_jwt in Requests¶

There are three default client authentication methods defined for OAuth2Session . But what if you want to use client_secret_jwt instead? client_secret_jwt is defined in RFC7523, use it for Requests:

from authlib.integrations.requests_client import OAuth2Session from authlib.oauth2.rfc7523 import ClientSecretJWT token_endpoint = 'https://example.com/oauth/token' session = OAuth2Session( 'your-client-id', 'your-client-secret', token_endpoint_auth_method=ClientSecretJWT(token_endpoint), ) session.fetch_token(token_endpoint) 

Using private_key_jwt in Requests¶

What if you want to use private_key_jwt client authentication method, here is the way with PrivateKeyJWT for Requests:

from authlib.integrations.requests_client import OAuth2Session from authlib.oauth2.rfc7523 import PrivateKeyJWT with open('your-private-key.pem', 'rb') as f: private_key = f.read() token_endpoint = 'https://example.com/oauth/token' session = OAuth2Session( 'your-client-id', private_key, token_endpoint_auth_method=PrivateKeyJWT(token_endpoint), ) session.fetch_token(token_endpoint) 

OAuth2Auth¶

Already obtained access token? We can use OAuth2Auth directly in requests. But this OAuth2Auth can not refresh token automatically for you. Here is how to use it in requests:

token = 'token_type': 'bearer', 'access_token': '. ', . > auth = OAuth2Auth(token) requests.get(url, auth=auth) 

Requests OpenID Connect¶

OpenID Connect is built on OAuth 2.0. It is pretty simple to communicate with an OpenID Connect provider via Authlib. With Authlib built-in OAuth 2.0 system and JsonWebToken (JWT), parsing OpenID Connect id_token could be very easy.

Understand how it works with OAuth 2 OpenID Connect .

Requests Service Account¶

The Assertion Framework of OAuth 2.0 Authorization Grants is also known as service account. With the implementation of AssertionSession , we can easily integrate with a “assertion” service.

Checking out an example of Google Service Account with AssertionSession .

Close Session Hint¶

Developers SHOULD close a Requests Session when the jobs are done. You can call .close() manually, or use a with context to automatically close the session:

session = OAuth2Session(client_id, client_secret) session.get(url) session.close() with OAuth2Session(client_id, client_secret) as session: session.get(url) 

Self-Signed Certificate¶

Self-signed certificate mutual-TLS method internet standard is defined in RFC8705 Section 2.2 .

For specifics development purposes only, you may need to disable SSL verification.

You can force all requests to disable SSL verification by setting your environment variable CURL_CA_BUNDLE=»» .

This solutions works because Python requests (and most of the packages) overwrites the default value for ssl verifications from environment variables CURL_CA_BUNDLE and REQUESTS_CA_BUNDLE .

This hack will only work with CURL_CA_BUNDLE , as you can see in requests/sessions.py

verify = (os.environ.get('REQUESTS_CA_BUNDLE') or os.environ.get('CURL_CA_BUNDLE')) 

Please remember to set the env variable only in you development environment.

Источник

Authentication¶

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)

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’))

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’))

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:

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:

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())

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.

Requests is an elegant and simple HTTP library for Python, built for human beings. You are currently looking at the documentation of the development release.

Table of Contents

Источник

Читайте также:  Python change value in data frame
Оцените статью