OAuth 2 Workflow
Introduction
The following sections provide some example code that demonstrates some of thepossible OAuth2 flows you can use with requests-oauthlib. We provide fourexamples: one for each of the grant types defined by the OAuth2 RFC. Thesegrant types (or workflows) are the Authorization Code Grant (or Web ApplicationFlow), the Implicit Grant (or Mobile Application Flow), the Resource OwnerPassword Credentials Grant (or, more succinctly, the Legacy Application Flow),and the Client Credentials Grant (or Backend Application Flow).
Available Workflows
There are four core work flows:
Authorization Code Grant (Web ApplicationFlow).
Implicit Grant (Mobile Application flow).
Resource Owner Password Credentials Grant(Legacy Application flow).
Client Credentials Grant (BackendApplication flow).
Web Application Flow
The steps below outline how to use the default Authorization Grant Type flow toobtain an access token and fetch a protected resource. In this examplethe provider is Google and the protected resource is the user’s profile.
Obtain credentials from your OAuth provider manually. At minimum you willneed a
client_id
but likely also aclient_secret
. During thisprocess you might also be required to register a default redirect URI to beused by your application. Save these things in your Python script:
>>>client_id=r'your_client_id'>>>client_secret=r'your_client_secret'>>>redirect_uri='https://your.callback/uri'
User authorization through redirection. First we will create anauthorization url from the base URL given by the provider andthe credentials previously obtained. In addition most providers willrequest that you ask for access to a certain scope. In this examplewe will ask Google for access to the email address of the user and theusers profile.
# Note that these are Google specific scopes>>>scope=['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile']>>>oauth=OAuth2Session(client_id,redirect_uri=redirect_uri, scope=scope)>>>authorization_url,state=oauth.authorization_url( 'https://accounts.google.com/o/oauth2/auth', # access_type and prompt are Google specific extra # parameters. access_type="offline", prompt="select_account")>>>print(f'Please go to{authorization_url} and authorize access.')>>>authorization_response=input('Enter the full callback URL')
Fetch an access token from the provider using the authorization codeobtained during user authorization.
>>>token=oauth.fetch_token( 'https://accounts.google.com/o/oauth2/token', authorization_response=authorization_response, # Google specific extra parameter used for client # authentication client_secret=client_secret)
Access protected resources using the access token you just obtained.For example, get the users profile info.
>>>r=oauth.get('https://www.googleapis.com/oauth2/v1/userinfo')>>># Enjoy =)
Mobile Application Flow
The steps below outline how to use the Implicit Code Grant Type flow to obtain an access token.
You will need the following settings.
>>>client_id='your_client_id'>>>scopes=['scope_1','scope_2']>>>auth_url='https://your.oauth2/auth'
Get the authorization_url
>>>fromoauthlib.oauth2importMobileApplicationClient>>>fromrequests_oauthlibimportOAuth2Session>>>oauth=OAuth2Session(client=MobileApplicationClient(client_id=client_id),scope=scopes)>>>authorization_url,state=oauth.authorization_url(auth_url)
Fetch an access token from the provider.
>>>response=oauth.get(authorization_url)>>>oauth.token_from_fragment(response.url)
Legacy Application Flow
The steps below outline how to use the Resource Owner Password Credentials Grant Type flow to obtain an access token.
You will need the following settings.
client_secret
is optional depending on the provider.
>>>client_id='your_client_id'>>>client_secret='your_client_secret'>>>username='your_username'>>>password='your_password'
Fetch an access token from the provider.
>>>fromoauthlib.oauth2importLegacyApplicationClient>>>fromrequests_oauthlibimportOAuth2Session>>>oauth=OAuth2Session(client=LegacyApplicationClient(client_id=client_id))>>>token=oauth.fetch_token(token_url='https://somesite.com/oauth2/token', username=username, password=password, client_id=client_id, client_secret=client_secret)
Backend Application Flow
The steps below outline how to use the Resource Owner Client Credentials Grant Type flow to obtain an access token.
Obtain credentials from your OAuth provider. At minimum you willneed a
client_id
andclient_secret
.>>>client_id='your_client_id'>>>client_secret='your_client_secret'
Fetch an access token from the provider.
>>>fromoauthlib.oauth2importBackendApplicationClient>>>fromrequests_oauthlibimportOAuth2Session>>>client=BackendApplicationClient(client_id=client_id)>>>oauth=OAuth2Session(client=client)>>>token=oauth.fetch_token(token_url='https://provider.com/oauth2/token',client_id=client_id, client_secret=client_secret)
If your provider requires that you pass auth credentials in a Basic Auth header, you can do this instead:
>>>fromoauthlib.oauth2importBackendApplicationClient>>>fromrequests_oauthlibimportOAuth2Session>>>fromrequests.authimportHTTPBasicAuth>>>auth=HTTPBasicAuth(client_id,client_secret)>>>client=BackendApplicationClient(client_id=client_id)>>>oauth=OAuth2Session(client=client)>>>token=oauth.fetch_token(token_url='https://provider.com/oauth2/token',auth=auth)
Refreshing tokens
Certain providers will give you arefresh_token
along with theaccess_token
. These can be used to directly fetch new access tokens withoutgoing through the normal OAuth workflow.requests-oauthlib
provides threemethods of obtaining refresh tokens. All of these are dependent on youspecifying an accurateexpires_in
in the token.
expires_in
is a credential given with the access and refresh tokenindicating in how many seconds from now the access token expires. Commonly,access tokens expire after an hour and theexpires_in
would be3600
.Without this it is impossible forrequests-oauthlib
to know when a tokenis expired as the status code of a request failing due to token expiration isnot defined.
If you are not interested in token refreshing, always pass in a positive valueforexpires_in
or omit it entirely.
(ALL) Define the token, token saver and needed credentials
>>>token={...'access_token':'eswfld123kjhn1v5423',...'refresh_token':'asdfkljh23490sdf',...'token_type':'Bearer',...'expires_in':'-30',# initially 3600, need to be updated by you...}>>>client_id=r'foo'>>>refresh_url='https://provider.com/token'>>>protected_url='https://provider.com/secret'>>># most providers will ask you for extra credentials to be passed along>>># when refreshing tokens, usually for authentication purposes.>>>extra={...'client_id':client_id,...'client_secret':r'potato',...}>>># After updating the token you will most likely want to save it.>>>deftoken_saver(token):...# save token in database / session
(First) Define Try-Catch TokenExpiredError on each request
This is the most basic version in which an error is raised when refreshis necessary but refreshing is done manually.
>>>fromrequests_oauthlibimportOAuth2Session>>>fromoauthlib.oauth2importTokenExpiredError>>>try:...oauth=OAuth2Session(client_id,token=token)...r=oauth.get(protected_url)>>>exceptTokenExpiredErrorase:...token=oauth.refresh_token(refresh_url,**extra)...token_saver(token)>>>oauth=OAuth2Session(client_id,token=token)>>>r=oauth.get(protected_url)
(Second) Define automatic token refresh automatic but update manually
This is the, arguably awkward, middle between the basic and convenient refreshmethods in which a token is automatically refreshed, but saving the new tokenis done manually.
>>>fromrequests_oauthlibimportOAuth2Session,TokenUpdated>>>try:...oauth=OAuth2Session(client_id,token=token,...auto_refresh_kwargs=extra,auto_refresh_url=refresh_url)...r=oauth.get(protected_url)>>>exceptTokenUpdatedase:...token_saver(e.token)
(Third, Recommended) Define automatic token refresh and update
The third and recommended method will automatically fetch refresh tokens andsave them. It requires no exception catching and results in clean code. Rememberhowever that you still need to updateexpires_in
to trigger the refresh.
>>>fromrequests_oauthlibimportOAuth2Session>>>oauth=OAuth2Session(client_id,token=token,auto_refresh_url=refresh_url,...auto_refresh_kwargs=extra,token_updater=token_saver)>>>r=oauth.get(protected_url)
TLS Client Authentication
To use TLS Client Authentication (draft-ietf-oauth-mtls) via aself-signed or CA-issued certificate, pass the certificate in thetoken request and ensure that the client id is sent in the request:
>>>oauth.fetch_token(token_url='https://somesite.com/oauth2/token',...include_client_id=True,cert=('test-client.pem','test-client-key.pem'))