Python oauthlib.oauth2.WebApplicationClient() Examples

The following are 12 code examples of oauthlib.oauth2.WebApplicationClient(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oauthlib.oauth2 , or try the search function .
Example #1
Source File: nokia.py    From nokia-weight-sync with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, credentials):
        self.credentials = credentials
        self.token = {
            'access_token': credentials.access_token,
            'refresh_token': credentials.refresh_token,
            'token_type': credentials.token_type,
            'expires_in': str(int(credentials.token_expiry) - ts()),
        }
        oauth_client = WebApplicationClient(credentials.client_id,
            token=self.token, default_token_placement='query')
        self.client = OAuth2Session(
            credentials.client_id,
            token=self.token,
            client=oauth_client,
            auto_refresh_url='{}/oauth2/token'.format(NokiaAuth.URL),
            auto_refresh_kwargs={
                'client_id': credentials.client_id,
                'client_secret': credentials.consumer_secret,
            },
            token_updater=self.set_token
        ) 
Example #2
Source File: ads_auth_code.py    From crmint with Apache License 2.0 6 votes vote down vote up
def get_token(client_id, client_secret, ads_code):
  """ Using authentication code retrieved from URL, take code, client_id and
  client_secret to send HTTP request to fetch refresh token taken from parsed
  response """

  oauthlib_client = oauth2.WebApplicationClient(client_id)
  # Prepare the access token request body --> makes a
  # request to the token endpoint by adding the following parameters
  post_body = oauthlib_client.prepare_request_body(
      client_secret=client_secret, code=ads_code, redirect_uri=CALLBACK_URL)
  # URL request
  request = urllib2.Request(GOOGLE_OAUTH2_GEN_ENDPOINT,
                            post_body, OAUTH2_REFRESH_HEADERS)
  if HTTPS_PROXY:
    request.set_proxy(HTTPS_PROXY, 'https')
  # Open the given url, read and decode into raw_response
  raw_response = urllib2.urlopen(request).read().decode()
  # Parse the JSON response body given in raw_response
  oauth2_credentials = oauthlib_client.parse_request_body_response(
      raw_response)
  # Return the refresh token
  token = oauth2_credentials['refresh_token']

  return token 
Example #3
Source File: auth.py    From mendeley-python-sdk with Apache License 2.0 5 votes vote down vote up
def __init__(self, mendeley, state):
        MendeleyLoginAuthenticator.__init__(self, mendeley, WebApplicationClient(mendeley.client_id), state)

        self.token_url = self.mendeley.host + '/oauth/token'
        self.auth = HTTPBasicAuth(self.mendeley.client_id, self.mendeley.client_secret) 
Example #4
Source File: __init__.py    From python_withings_api with MIT License 5 votes vote down vote up
def __init__(
        self,
        credentials: Credentials,
        refresh_cb: Optional[Callable[[Credentials], None]] = None,
    ):
        """Initialize new object."""
        self._credentials = credentials
        self._refresh_cb: Final = refresh_cb
        token: Final = {
            "access_token": credentials.access_token,
            "refresh_token": credentials.refresh_token,
            "token_type": credentials.token_type,
            "expires_in": str(int(credentials.token_expiry) - arrow.utcnow().timestamp),
        }

        self._client: Final = OAuth2Session(
            credentials.client_id,
            token=token,
            client=WebApplicationClient(  # nosec
                credentials.client_id, token=token, default_token_placement="query"
            ),
            auto_refresh_url="%s/%s" % (WithingsAuth.URL, WithingsAuth.PATH_TOKEN),
            auto_refresh_kwargs={
                "client_id": credentials.client_id,
                "client_secret": credentials.consumer_secret,
            },
            token_updater=self._update_token,
        ) 
Example #5
Source File: oauth2_auth.py    From Requester with MIT License 5 votes vote down vote up
def __init__(self, client_id=None, client=None, token=None):
        """Construct a new OAuth 2 authorization object.

        :param client_id: Client id obtained during registration
        :param client: :class:`oauthlib.oauth2.Client` to be used. Default is
                       WebApplicationClient which is useful for any
                       hosted application but not mobile or desktop.
        :param token: Token dictionary, must include access_token
                      and token_type.
        """
        self._client = client or WebApplicationClient(client_id, token=token)
        if token:
            for k, v in token.items():
                setattr(self._client, k, v) 
Example #6
Source File: ads_auth_code.py    From crmint with Apache License 2.0 5 votes vote down vote up
def get_url(client_id):
  """ Create oauth client and use this to generate the URL to get the authorisation
  code using client_id """

  oauthlib_client = oauth2.WebApplicationClient(client_id)
  # This is the URL construction for getting the authorisation code
  authorize_url = oauthlib_client.prepare_request_uri(
      GOOGLE_OAUTH2_AUTH_ENDPOINT, redirect_uri=CALLBACK_URL, scope=SCOPE)

  return authorize_url 
Example #7
Source File: oauth2_auth.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, client_id=None, client=None, token=None):
        """Construct a new OAuth 2 authorization object.

        :param client_id: Client id obtained during registration
        :param client: :class:`oauthlib.oauth2.Client` to be used. Default is
                       WebApplicationClient which is useful for any
                       hosted application but not mobile or desktop.
        :param token: Token dictionary, must include access_token
                      and token_type.
        """
        self._client = client or WebApplicationClient(client_id, token=token)
        if token:
            for k, v in token.items():
                setattr(self._client, k, v) 
Example #8
Source File: oauth2_auth.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, client_id=None, client=None, token=None):
        """Construct a new OAuth 2 authorization object.

        :param client_id: Client id obtained during registration
        :param client: :class:`oauthlib.oauth2.Client` to be used. Default is
                       WebApplicationClient which is useful for any
                       hosted application but not mobile or desktop.
        :param token: Token dictionary, must include access_token
                      and token_type.
        """
        self._client = client or WebApplicationClient(client_id, token=token)
        if token:
            for k, v in token.items():
                setattr(self._client, k, v) 
Example #9
Source File: protocol.py    From exchangelib with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def create_oauth2_session(self):
        if self.auth_type != OAUTH2:
            raise ValueError('Auth type must be %r for credentials type OAuth2Credentials' % OAUTH2)

        has_token = False
        scope = ['https://outlook.office365.com/.default']
        session_params = {}
        token_params = {}

        if isinstance(self.credentials, OAuth2AuthorizationCodeCredentials):
            # Ask for a refresh token
            scope.append('offline_access')

            # We don't know (or need) the Microsoft tenant ID. Use
            # common/ to let Microsoft select the appropriate tenant
            # for the provided authorization code or refresh token.
            #
            # Suppress looks-like-password warning from Bandit.
            token_url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'  # nosec

            client_params = {}
            has_token = self.credentials.access_token is not None
            if has_token:
                session_params['token'] = self.credentials.access_token
            elif self.credentials.authorization_code is not None:
                token_params['code'] = self.credentials.authorization_code
                self.credentials.authorization_code = None

            if self.credentials.client_id is not None and self.credentials.client_secret is not None:
                # If we're given a client ID and secret, we have enough
                # to refresh access tokens ourselves. In other cases the
                # session will raise TokenExpiredError and we'll need to
                # ask the calling application to refresh the token (that
                # covers cases where the caller doesn't have access to
                # the client secret but is working with a service that
                # can provide it refreshed tokens on a limited basis).
                session_params.update({
                    'auto_refresh_kwargs': {
                        'client_id': self.credentials.client_id,
                        'client_secret': self.credentials.client_secret,
                    },
                    'auto_refresh_url': token_url,
                    'token_updater': self.credentials.on_token_auto_refreshed,
                })
            client = WebApplicationClient(self.credentials.client_id, **client_params)
        else:
            token_url = 'https://login.microsoftonline.com/%s/oauth2/v2.0/token' % self.credentials.tenant_id
            client = BackendApplicationClient(client_id=self.credentials.client_id)

        session = self.raw_session(oauth2_client=client, oauth2_session_params=session_params)
        if not has_token:
            # Fetch the token explicitly -- it doesn't occur implicitly
            token = session.fetch_token(token_url=token_url, client_id=self.credentials.client_id,
                                        client_secret=self.credentials.client_secret, scope=scope,
                                        **token_params)
            # Allow the credentials object to update its copy of the new
            # token, and give the application an opportunity to cache it
            self.credentials.on_token_auto_refreshed(token)
        session.auth = get_auth_instance(auth_type=OAUTH2, client=client)

        return session 
Example #10
Source File: oauth2_session.py    From Requester with MIT License 4 votes vote down vote up
def __init__(self, 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):
        """Construct a new OAuth 2 client session.

        :param client_id: Client id obtained during registration
        :param client: :class:`oauthlib.oauth2.Client` to be used. Default is
                       WebApplicationClient which is useful for any
                       hosted application but not mobile or desktop.
        :param scope: List of scopes you wish to request access to
        :param redirect_uri: Redirect URI you registered as callback
        :param token: Token dictionary, must include access_token
                      and token_type.
        :param 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.
                      Can be either a string or a no argument callable.
        :auto_refresh_url: Refresh token endpoint URL, must be HTTPS. Supply
                           this if you wish the client to automatically refresh
                           your access tokens.
        :auto_refresh_kwargs: Extra arguments to pass to the refresh token
                              endpoint.
        :token_updater: Method with one argument, token, to be used to update
                        your token database on automatic token refresh. If not
                        set a TokenUpdated warning will be raised when a token
                        has been refreshed. This warning will carry the token
                        in its token argument.
        :param kwargs: Arguments to pass to the Session constructor.
        """
        super(OAuth2Session, self).__init__(**kwargs)
        self._client = client or WebApplicationClient(client_id, token=token)
        self.token = token or {}
        self.scope = scope
        self.redirect_uri = redirect_uri
        self.state = state or generate_token
        self._state = state
        self.auto_refresh_url = auto_refresh_url
        self.auto_refresh_kwargs = auto_refresh_kwargs or {}
        self.token_updater = token_updater

        # Allow customizations for non compliant providers through various
        # hooks to adjust requests and responses.
        self.compliance_hook = {
            'access_token_response': set(),
            'refresh_token_response': set(),
            'protected_request': set(),
        } 
Example #11
Source File: oauth2_session.py    From bazarr with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, 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):
        """Construct a new OAuth 2 client session.

        :param client_id: Client id obtained during registration
        :param client: :class:`oauthlib.oauth2.Client` to be used. Default is
                       WebApplicationClient which is useful for any
                       hosted application but not mobile or desktop.
        :param scope: List of scopes you wish to request access to
        :param redirect_uri: Redirect URI you registered as callback
        :param token: Token dictionary, must include access_token
                      and token_type.
        :param 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.
                      Can be either a string or a no argument callable.
        :auto_refresh_url: Refresh token endpoint URL, must be HTTPS. Supply
                           this if you wish the client to automatically refresh
                           your access tokens.
        :auto_refresh_kwargs: Extra arguments to pass to the refresh token
                              endpoint.
        :token_updater: Method with one argument, token, to be used to update
                        your token database on automatic token refresh. If not
                        set a TokenUpdated warning will be raised when a token
                        has been refreshed. This warning will carry the token
                        in its token argument.
        :param kwargs: Arguments to pass to the Session constructor.
        """
        super(OAuth2Session, self).__init__(**kwargs)
        self._client = client or WebApplicationClient(client_id, token=token)
        self.token = token or {}
        self.scope = scope
        self.redirect_uri = redirect_uri
        self.state = state or generate_token
        self._state = state
        self.auto_refresh_url = auto_refresh_url
        self.auto_refresh_kwargs = auto_refresh_kwargs or {}
        self.token_updater = token_updater

        # Allow customizations for non compliant providers through various
        # hooks to adjust requests and responses.
        self.compliance_hook = {
            'access_token_response': set(),
            'refresh_token_response': set(),
            'protected_request': set(),
        } 
Example #12
Source File: oauth2_session.py    From Tautulli with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, 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):
        """Construct a new OAuth 2 client session.

        :param client_id: Client id obtained during registration
        :param client: :class:`oauthlib.oauth2.Client` to be used. Default is
                       WebApplicationClient which is useful for any
                       hosted application but not mobile or desktop.
        :param scope: List of scopes you wish to request access to
        :param redirect_uri: Redirect URI you registered as callback
        :param token: Token dictionary, must include access_token
                      and token_type.
        :param 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.
                      Can be either a string or a no argument callable.
        :auto_refresh_url: Refresh token endpoint URL, must be HTTPS. Supply
                           this if you wish the client to automatically refresh
                           your access tokens.
        :auto_refresh_kwargs: Extra arguments to pass to the refresh token
                              endpoint.
        :token_updater: Method with one argument, token, to be used to update
                        your token databse on automatic token refresh. If not
                        set a TokenUpdated warning will be raised when a token
                        has been refreshed. This warning will carry the token
                        in its token argument.
        :param kwargs: Arguments to pass to the Session constructor.
        """
        super(OAuth2Session, self).__init__(**kwargs)
        self._client = client or WebApplicationClient(client_id, token=token)
        self.token = token or {}
        self.scope = scope
        self.redirect_uri = redirect_uri
        self.state = state or generate_token
        self._state = state
        self.auto_refresh_url = auto_refresh_url
        self.auto_refresh_kwargs = auto_refresh_kwargs or {}
        self.token_updater = token_updater

        # Allow customizations for non compliant providers through various
        # hooks to adjust requests and responses.
        self.compliance_hook = {
            'access_token_response': set([]),
            'refresh_token_response': set([]),
            'protected_request': set([]),
        }