Client Reference

This part of the documentation covers the interface of Authlib Client.

Sessions and Client

class authlib.client.OAuth1Session(client_key, client_secret=None, resource_owner_key=None, resource_owner_secret=None, callback_uri=None, rsa_key=None, verifier=None, signature_method='HMAC-SHA1', signature_type='HEADER', force_include_body=False, **kwargs)

Construct a new OAuth 1 client requests session.

Parameters:
  • client_key – Consumer key, which you get from registration.
  • client_secret – Consumer Secret, which you get from registration.
  • resource_owner_key – A resource owner key, also referred to as request token or access token depending on when in the workflow it is used.
  • resource_owner_secret – A resource owner secret obtained with either a request or access token. Often referred to as token secret.
  • callback_uri – The URL the user is redirect back to after authorization.
  • rsa_key – The private RSA key as a string. Can only be used with signature_method=authlib.spec.rfc5849.SIGNATURE_RSA.
  • verifier – A verifier string to prove authorization was granted.
  • signature_method

    Signature methods for OAuth 1, available types:

    • authlib.spec.rfc5849.SIGNATURE_HMAC_SHA1
    • authlib.spec.rfc5849.SIGNATURE_RSA_SHA1
    • authlib.spec.rfc5849.SIGNATURE_PLAINTEXT

    Default is SIGNATURE_HMAC_SHA1. You can extend signature method via rfc5849.Client.

  • signature_type

    Signature type decides where the OAuth parameters are added. Either in the Authorization header (default) or to the URL query parameters or the request body. Defined as:

    • authlib.spec.rfc5849.SIGNATURE_TYPE_HEADER
    • authlib.spec.rfc5849.SIGNATURE_TYPE_BODY
    • authlib.spec.rfc5849.SIGNATURE_TYPE_QUERY
  • force_include_body – Always include the request body in the signature creation.
  • kwargs – Extra parameters to include.
authorization_url(url, request_token=None, **kwargs)

Create an authorization URL by appending request_token and optional kwargs to url.

This is the second step in the OAuth 1 workflow. The user should be redirected to this authorization URL, grant access to you, and then be redirected back to you. The redirection back can either be specified during client registration or by supplying a callback URI per request.

Parameters:
  • url – The authorization endpoint URL.
  • request_token – The previously obtained request token.
  • kwargs – Optional parameters to append to the URL.
Returns:

The authorization URL with new parameters embedded.

fetch_access_token(url, verifier=None, **kwargs)

Method for fetching an access token from the token endpoint.

This is the final step in the OAuth 1 workflow. An access token is obtained using all previously obtained credentials, including the verifier from the authorization step.

Parameters:
  • url – Access Token endpoint.
  • verifier – A verifier string to prove authorization was granted.
  • kwargs – Extra parameters to include for fetching access token.
Returns:

A token dict.

fetch_request_token(url, realm=None, **kwargs)

Method for fetching an access token from the token endpoint.

This is the first step in the OAuth 1 workflow. A request token is obtained by making a signed post request to url. The token is then parsed from the application/x-www-form-urlencoded response and ready to be used to construct an authorization url.

Parameters:
  • url – Request Token endpoint.
  • realm – A string/list/tuple of realm for Authorization header.
  • kwargs – Extra parameters to include for fetching token.
Returns:

A Request Token dict.

Note, realm can also be configured when session created:

session = OAuth1Session(client_key, client_secret, ..., realm='')
parse_authorization_response(url)

Extract parameters from the post authorization redirect response URL.

Parameters:url – The full URL that resulted from the user being redirected back from the OAuth provider to you, the client.
Returns:A dict of parameters extracted from the URL.
rebuild_auth(prepared_request, response)

When being redirected we should always strip Authorization header, since nonce may not be reused as per OAuth spec.

class authlib.client.OAuth2Session(client_id=None, client_secret=None, refresh_token_url=None, refresh_token_params=None, scope=None, redirect_uri=None, token=None, token_placement='headers', state=None, token_updater=None, **kwargs)

Construct a new OAuth 2 client requests session.

Parameters:
  • client_id – Client ID, which you get from client registration.
  • client_secret – Client Secret, which you get from registration.
  • refresh_token_url – Refresh Token endpoint for auto refresh token.
  • refresh_token_params – Extra parameters for refresh token endpoint.
  • scope – Scope that you needed to access user resources.
  • redirect_uri – Redirect URI you registered as callback.
  • token – A dict of token attributes such as access_token, token_type and expires_at.
  • state – State string used to prevent CSRF. This will be given when creating the authorization url and must be supplied when parsing the authorization response.
  • token_updater – A function for you to update token. It accept a OAuth2Token as parameter.
authorization_url(url, state=None, **kwargs)

Generate an authorization URL.

Parameters:
  • url – Authorization endpoint url, must be HTTPS.
  • state – An optional state string for CSRF protection. If not given it will be generated for you.
  • kwargs – Extra parameters to include.
Returns:

authorization_url, state

fetch_access_token(url=None, code=None, authorization_response=None, body='', auth=None, username=None, password=None, method='POST', headers=None, timeout=None, verify=True, proxies=None, **kwargs)

Generic method for fetching an access token from the token endpoint.

Parameters:
  • url – Access Token endpoint URL, if not configured, authorization_response is used to extract token from its fragment (implicit way).
  • code – Authorization code (if any)
  • authorization_response – Authorization response URL, the callback URL of the request back to you. We can extract authorization code from it.
  • body – Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body.
  • auth – An auth tuple or method as accepted by requests.
  • username – Username used by legacy clients.
  • password – Password used by legacy clients.
  • method – The HTTP method used to make the request. Defaults to POST, but may also be GET. Other methods should be added as needed.
  • headers – Dict to default request headers with.
  • timeout – Timeout of the request in seconds.
  • verify – Verify SSL certificate.
  • proxies – Proxies to use with requests.
  • kwargs – Extra parameters to include in the token request.
Returns:

A OAuth2Token object (a dict too).

fetch_token(url, **kwargs)

Alias for fetch_access_token. Compatible with requests-oauthlib.

refresh_token(url, refresh_token=None, body='', auth=None, headers=None, timeout=None, verify=True, proxies=None, **kwargs)

Fetch a new access token using a refresh token.

Parameters:
  • url – Refresh Token endpoint, must be HTTPS.
  • refresh_token – The refresh_token to use.
  • body – Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body.
  • auth – An auth tuple or method as accepted by requests.
  • headers – Dict to default request headers with.
  • timeout – Timeout of the request in seconds.
  • verify – Verify SSL certificate.
  • proxies – Proxies to use with requests.
  • kwargs – Extra parameters to include in the token request.
Returns:

A OAuth2Token object (a dict too).

register_compliance_hook(hook_type, hook)

Register a hook for request/response tweaking.

Available hooks are:

  • access_token_response: invoked before token parsing.
  • refresh_token_response: invoked before refresh token parsing.
  • protected_request: invoked before making a request.
  • revoke_token_request: invoked before revoking a token.
revoke_token(url, token, token_type_hint=None, body=None, auth=None, headers=None, timeout=None, verify=True, proxies=None, **kwargs)

Revoke token method defined via RFC7009.

Parameters:
  • url – Revoke Token endpoint, must be HTTPS.
  • token – The token to be revoked.
  • token_type_hint – The type of the token that to be revoked. It can be “access_token” or “refresh_token”.
  • body – Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body.
  • auth – An auth tuple or method as accepted by requests.
  • headers – Dict to default request headers with.
  • timeout – Timeout of the request in seconds.
  • verify – Verify SSL certificate.
  • proxies – Proxies to use with requests.
  • kwargs – Extra parameters to include in the token request.
Returns:

A OAuth2Token object (a dict too).

class authlib.client.OAuthClient(client_key=None, client_secret=None, request_token_url=None, request_token_params=None, access_token_url=None, access_token_params=None, refresh_token_url=None, refresh_token_params=None, authorize_url=None, api_base_url=None, client_kwargs=None, compliance_fix=None, **kwargs)

A mixed OAuth client for OAuth 1 and OAuth 2.

Parameters:
  • client_key – Consumer key of OAuth 1, or Client ID of OAuth 2
  • client_secret – Consumer secret of OAuth 2, or Client Secret of OAuth 2
  • request_token_url – Request Token endpoint for OAuth 1
  • request_token_params – Extra parameters for Request Token endpoint
  • access_token_url – Access Token endpoint for OAuth 1 and OAuth 2
  • access_token_params – Extra parameters for Access Token endpoint
  • refresh_token_url – Refresh Token endpoint for OAuth 2 (if any)
  • refresh_token_params – Extra paramters for Refresh Token endpoint
  • authorize_url – Endpoint for user authorization of OAuth 1 ro OAuth 2
  • api_base_url – A base URL endpoint to make requests simple
  • client_kwargs – Extra keyword arguments for session
  • kwargs – Extra keyword arguments

Create an instance of OAuthClient. If request_token_url is configured, it would be an OAuth 1 instance, otherwise it is OAuth 2 instance:

oauth1_client = OAuthClient(
    client_key='Twitter Consumer Key',
    client_secret='Twitter Consumer Secret',
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authenticate',
    api_base_url='https://api.twitter.com/1.1/',
)

oauth2_client = OAuthClient(
    client_key='GitHub Client ID',
    client_secret='GitHub Client Secret',
    api_base_url='https://api.github.com/',
    access_token_url='https://github.com/login/oauth/access_token',
    authorize_url='https://github.com/login/oauth/authorize',
    client_kwargs={'scope': 'user:email'},
)
delete(url, **kwargs)

Invoke DELETE http request.

If api_base_url configured, shortcut is available:

client.delete('posts/123')
fetch_access_token(callback_uri=None, request_token=None, **params)

Fetch access token in one step.

Parameters:
  • callback_uri – Callback or Redirect URI that is used in previous authorize_redirect().
  • request_token – A previous request token for OAuth 1.
  • params – Extra parameters to fetch access token.
Returns:

A token dict.

generate_authorize_redirect(callback_uri=None, save_request_token=None, **kwargs)

Generate the authorize redirect.

Parameters:
  • callback_uri – Callback or redirect URI for authorization.
  • save_request_token – A function to save request token.
  • kwargs – Extra parameters to include.
Returns:

(url, state)

get(url, **kwargs)

Invoke GET http request.

If api_base_url configured, shortcut is available:

client.get('users/lepture')
post(url, **kwargs)

Invoke POST http request.

If api_base_url configured, shortcut is available:

client.post('timeline', json={'text': 'Hi'})
put(url, **kwargs)

Invoke PUT http request.

If api_base_url configured, shortcut is available:

client.put('profile', json={'name': 'Hsiaoming Yang'})
session

OAuth 1/2 Session for requests. Initialized lazily.

If request_token_url is configured, it is a OAuth1Session, otherwise it is a OAuth2Session.

Flask Registry and RemoteApp

class authlib.flask.client.OAuth(app=None, fetch_token=None, update_token=None)

Registry for oauth clients.

Parameters:app – the app instance of Flask

Create an instance with Flask:

oauth = OAuth(app)
init_app(app, fetch_token=None, update_token=None)

Init app with Flask instance.

You can also pass the instance of Flask later:

oauth = OAuth()
oauth.init_app(app)
register(name, **kwargs)

Registers a new remote application.

Parameters:
  • name – Name of the remote application.
  • kwargs – Parameters for RemoteApp.

Find parameters from OAuthClient. When a remote app is registered, it can be accessed with named attribute:

oauth.register('twitter', client_key='', ...)
oauth.twitter.get('timeline')
class authlib.flask.client.RemoteApp(name, cache=None, fetch_token=None, update_token=None, *args, **kwargs)

Flask integrated RemoteApp of OAuthClient. It has built-in hooks for OAuthClient. The only required configuration is token model.

authorize_access_token(**kwargs)

Authorize access token.

authorize_redirect(callback_uri=None, **kwargs)

Create a HTTP Redirect for Authorization Endpoint.

Parameters:
  • callback_uri – Callback or redirect URI for authorization.
  • kwargs – Extra parameters to include.
Returns:

A HTTP redirect response.

Django Registry and RemoteApp

class authlib.django.client.OAuth

Registry for oauth clients.

Create an instance for registry:

oauth = OAuth()
register(name, **kwargs)

Registers a new remote application.

Parameters:
  • name – Name of the remote application.
  • kwargs – Parameters for RemoteApp.

Find parameters from OAuthClient. When a remote app is registered, it can be accessed with named attribute:

oauth.register('twitter', client_key='', ...)
oauth.twitter.get('timeline')
class authlib.django.client.RemoteApp(name, token=None, *args, **kwargs)

Django integrated RemoteApp of OAuthClient. It has built-in hooks for OAuthClient.

authorize_access_token(request, **kwargs)

Fetch access token in one step.

Parameters:request – HTTP request instance from Django view.
Returns:A token dict.
authorize_redirect(request, callback_uri=None, **kwargs)

Create a HTTP Redirect for Authorization Endpoint.

Parameters:
  • request – HTTP request instance from Django view.
  • callback_uri – Callback or redirect URI for authorization.
  • kwargs – Extra parameters to include.
Returns:

A HTTP redirect response.