Developer Interface — Async-OAuthlib 0.0.4 documentation

# Developer Interface

## OAuth 1.0

class `async_oauthlib.` `OAuth1`(login: str, password: str = '', encoding: str = 'latin1')

  Signs the request using OAuth 1 (RFC5849)

  `client_class`

    alias of `oauthlib.oauth1.rfc5849.Client`

## OAuth 1.0 Session

class `async_oauthlib.` `OAuth1Session`(client_key, client_secret=None, resource_owner_key=None, resource_owner_secret=None, callback_uri=None, signature_method='HMAC-SHA1', signature_type='AUTH_HEADER', rsa_key=None, verifier=None, client_class=None, force_include_body=False, **kwargs)

  Request signing and convenience methods for the oauth dance.

  What is the difference between OAuth1Session and OAuth1?

  OAuth1Session actually uses OAuth1 internally and its purpose is to assist in the OAuth workflow through convenience methods to prepare authorization URLs and parse the various token and redirection responses. It also provide rudimentary validation of responses.

  An example of the OAuth workflow using a basic CLI app and Twitter.

      >>> # Credentials obtained during the registration.
      >>> client_key = 'client key'
      >>> client_secret = 'secret'
      >>> callback_uri = 'https://127.0.0.1/callback'
      >>>
      >>> # Endpoints found in the OAuth provider API documentation
      >>> request_token_url = 'https://api.twitter.com/oauth/request_token'
      >>> authorization_url = 'https://api.twitter.com/oauth/authorize'
      >>> access_token_url = 'https://api.twitter.com/oauth/access_token'
      >>>
      >>> oauth_session = OAuth1Session(client_key,client_secret=client_secret, callback_uri=callback_uri)
      >>>
      >>> # First step, fetch the request token.
      >>> await oauth_session.fetch_request_token(request_token_url)
      {
          'oauth_token': 'kjerht2309u',
          'oauth_token_secret': 'lsdajfh923874',
      }
      >>>
      >>> # Second step. Follow this link and authorize
      >>> oauth_session.authorization_url(authorization_url)
      'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback'
      >>>
      >>> # Third step. Fetch the access token
      >>> redirect_response = input('Paste the full redirect URL here.')
      >>> oauth_session.parse_authorization_response(redirect_response)
      {
          'oauth_token: 'kjerht2309u',
          'oauth_token_secret: 'lsdajfh923874',
          'oauth_verifier: 'w34o8967345',
      }
      >>> await oauth_session.fetch_access_token(access_token_url)
      {
          'oauth_token': 'sdf0o9823sjdfsdf',
          'oauth_token_secret': '2kjshdfp92i34asdasd',
      }
      >>> # Done. You can now make OAuth requests.
      >>> status_url = 'http://api.twitter.com/1/statuses/update.json'
      >>> new_status = {'status':  'hello world!'}
      >>> await oauth_session.post(status_url, data=new_status)
      <Response [200]>

  `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.

    An example using a registered default callback URI.

        >>> request_token_url = 'https://api.twitter.com/oauth/request_token'
        >>> authorization_url = 'https://api.twitter.com/oauth/authorize'
        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')
        >>> await oauth_session.fetch_request_token(request_token_url)
        {
            'oauth_token': 'sdf0o9823sjdfsdf',
            'oauth_token_secret': '2kjshdfp92i34asdasd',
        }
        >>> oauth_session.authorization_url(authorization_url)
        'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf'
        >>> oauth_session.authorization_url(authorization_url, foo='bar')
        'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&foo=bar'

    An example using an explicit callback URI.

        >>> request_token_url = 'https://api.twitter.com/oauth/request_token'
        >>> authorization_url = 'https://api.twitter.com/oauth/authorize'
        >>> oauth_session = OAuth1Session('client-key', client_secret='secret', callback_uri='https://127.0.0.1/callback')
        >>> await oauth_session.fetch_request_token(request_token_url)
        {
            'oauth_token': 'sdf0o9823sjdfsdf',
            'oauth_token_secret': '2kjshdfp92i34asdasd',
        }
        >>> oauth_session.authorization_url(authorization_url)
        'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback'

  property `authorized`

    Boolean that indicates whether this session has an OAuth token or not. If self.authorized is True, you can reasonably expect OAuth-protected requests to the resource to succeed. If self.authorized is False, you need the user to go through the OAuth authentication dance before OAuth-protected requests to the resource will succeed.

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

    Fetch an access token.

    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.

    Note that a previously set verifier will be reset for your convenience, or else signature creation will be incorrect on consecutive requests.

        >>> access_token_url = 'https://api.twitter.com/oauth/access_token'
        >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'
        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')
        >>> oauth_session.parse_authorization_response(redirect_response)
        {
            'oauth_token: 'kjerht2309u',
            'oauth_token_secret: 'lsdajfh923874',
            'oauth_verifier: 'w34o8967345',
        }
        >>> await oauth_session.fetch_access_token(access_token_url)
        {
            'oauth_token': 'sdf0o9823sjdfsdf',
            'oauth_token_secret': '2kjshdfp92i34asdasd',
        }

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

    Fetch a request token.

    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 – The request token endpoint URL.

      - realm – A list of realms to request access to.

      - kwargs – Optional arguments passed to ‘’post’’ function in ‘’aiohttp.ClientSession’’

    Returns

      The response in dict format.

    Note that a previously set callback_uri will be reset for your convenience, or else signature creation will be incorrect on consecutive requests.

        >>> request_token_url = 'https://api.twitter.com/oauth/request_token'
        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')
        >>> await oauth_session.fetch_request_token(request_token_url)
        {
            'oauth_token': 'sdf0o9823sjdfsdf',
            'oauth_token_secret': '2kjshdfp92i34asdasd',
        }

  `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.

        >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'
        >>> oauth_session = OAuth1Session('client-key', client_secret='secret')
        >>> oauth_session.parse_authorization_response(redirect_response)
        {
            'oauth_token: 'kjerht2309u',
            'oauth_token_secret: 'lsdajfh923874',
            'oauth_verifier: 'w34o8967345',
        }

  `rebuild_auth`(prepared_request, response)

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

## OAuth 2.0

class `async_oauthlib.` `OAuth2`(login: str, password: str = '', encoding: str = 'latin1')

  Adds proof of authorization (OAuth2 token) to the request.

class `async_oauthlib.` `TokenUpdated`(token)

## OAuth 2.0 Session

class `async_oauthlib.` `OAuth2Session`(client_id=None, client=None, auto_refresh_url=None, auto_refresh_kwargs=None, scope=None, redirect_uri=None, token=None, state=None, token_updater=None, **kwargs)

  Versatile OAuth 2 extension to `requests.Session`.

  Supports any grant type adhering to `oauthlib.oauth2.Client` spec including the four core OAuth 2 grants.

  Can be used to create authorization urls, fetch tokens and access protected resources using the `requests.Session` interface you are used to.

  - `oauthlib.oauth2.WebApplicationClient` (default): Authorization Code Grant

  - `oauthlib.oauth2.MobileApplicationClient`: Implicit Grant

  - `oauthlib.oauth2.LegacyApplicationClient`: Password Credentials Grant

  - `oauthlib.oauth2.BackendApplicationClient`: Client Credentials Grant

  Note that the only time you will be using Implicit Grant from python is if you are driving a user agent able to obtain URL fragments.

  `authorization_url`(url, state=None, **kwargs)

    Form 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

  property `authorized`

    Boolean that indicates whether this session has an OAuth token or not. If self.authorized is True, you can reasonably expect OAuth-protected requests to the resource to succeed. If self.authorized is False, you need the user to go through the OAuth authentication dance before OAuth-protected requests to the resource will succeed.

  async `fetch_token`(token_url, code=None, authorization_response=None, body='', auth=None, username=None, password=None, method='POST', force_querystring=False, timeout=None, headers=None, verify_ssl=True, proxy=None, include_client_id=None, client_secret=None, ssl_context=None, **kwargs)

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

    If you are using the MobileApplicationClient you will want to use token_from_fragment instead of fetch_token.

    The current implementation enforces the RFC guidelines.

    Parameters

      - token_url – Token endpoint URL, must use HTTPS.

      - code – Authorization code (used by WebApplicationClients).

      - authorization_response – Authorization response URL, the callback URL of the request back to you. Used by WebApplicationClients instead of code.

      - 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 required by LegacyApplicationClients to appear in the request body.

      - password – Password required by LegacyApplicationClients to appear in the request body.

      - method – The HTTP method used to make the request. Defaults to POST, but may also be GET. Other methods should be added as needed.

      - force_querystring – If True, force the request body to be sent in the querystring instead.

      - timeout – Timeout of the request in seconds.

      - headers – Dict to default request headers with.

      - verify_ssl – Verify SSL certificate.

      - proxy – The proxy argument is passed onto aiohttp.

      - include_client_id – Should the request body include the client_id parameter. Default is None, which will attempt to autodetect. This can be forced to always include (True) or never include (False).

      - client_secret – The client_secret paired to the client_id. This is generally required unless provided in the auth tuple. If the value is None, it will be omitted from the request, however if the value is an empty string, an empty string will be sent.

      - ssl_context – The ssl context being passed to aiohttp ssl_context.

      - kwargs – Extra parameters to include in the token request.

    Returns

      A token dict

  `new_state`()

    Generates a state string to be used in authorizations.

  async `refresh_token`(token_url, refresh_token=None, body='', auth=None, timeout=None, headers=None, verify_ssl=True, proxy=None, **kwargs)

    Fetch a new access token using a refresh token.

    Parameters

      - token_url – The 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.

      - timeout – Timeout of the request in seconds.

      - headers – A dict of headers to be used by requests.

      - verify_ssl – Verify SSL certificate.

      - proxy – The proxy argument will be passed to requests.

      - kwargs – Extra parameters to include in the token request.

    Returns

      A token dict

  `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.

    If you find a new hook is needed please send a GitHub PR request or open an issue.

  async `request`(method, url, data=None, headers=None, withhold_token=False, client_id=None, client_secret=None, **kwargs)

    Intercept all requests and add the OAuth 2 token if present.

  `token_from_fragment`(authorization_response)

    Parse token from the URI fragment, used by MobileApplicationClients.

    Parameters

      authorization_response – The full URL of the redirect back to you

    Returns

      A token dict