How to use the oauthlib.common function in oauthlib

To help you get started, we’ve selected a few oauthlib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github oauthlib / oauthlib / tests / oauth2 / rfc6749 / test_grant_types.py View on Github external
def test_create_token_response(self):
        bearer = BearerToken(self.mock_validator, expires_in=1800)
        orig_generate_token = common.generate_token
        self.addCleanup(setattr, common, 'generate_token', orig_generate_token)
        common.generate_token = lambda *args, **kwargs: '1234'
        headers, body, status_code = self.auth.create_token_response(
                self.request, bearer)
        correct_uri = 'https://b.c/p#access_token=1234&token_type=Bearer&expires_in=1800&state=xyz&scope=hello+world'
        self.assertEqual(status_code, 302)
        self.assertIn('Location', headers)
        self.assertURLEqual(headers['Location'], correct_uri, parse_fragment=True)
github oauthlib / oauthlib / tests / oauth2 / rfc6749 / clients / test_base.py View on Github external
def test_add_mac_token(self):
        # Missing access token
        client = Client(self.client_id, token_type="MAC")
        self.assertRaises(ValueError, client.add_token, self.uri)

        # Invalid hash algorithm
        client = Client(self.client_id, token_type="MAC",
                access_token=self.access_token, mac_key=self.mac_key,
                mac_algorithm="hmac-sha-2")
        self.assertRaises(ValueError, client.add_token, self.uri)

        orig_generate_timestamp = common.generate_timestamp
        orig_generate_nonce = common.generate_nonce
        orig_generate_age = utils.generate_age
        self.addCleanup(setattr, common, 'generage_timestamp', orig_generate_timestamp)
        self.addCleanup(setattr, common, 'generage_nonce', orig_generate_nonce)
        self.addCleanup(setattr, utils, 'generate_age', orig_generate_age)
        common.generate_timestamp = lambda: '123456789'
        common.generate_nonce = lambda: 'abc123'
        utils.generate_age = lambda *args: 0

        # Add the Authorization header (draft 00)
        client = Client(self.client_id, token_type="MAC",
                access_token=self.access_token, mac_key=self.mac_key,
                mac_algorithm="hmac-sha-1")
        uri, headers, body = client.add_token(self.uri, body=self.body,
                headers=self.headers, issue_time=datetime.datetime.now())
        self.assertEqual(uri, self.uri)
github pymedusa / Medusa / ext / oauthlib / oauth2 / rfc6749 / grant_types / implicit.py View on Github external
# error and MUST NOT automatically redirect the user-agent to the
        # invalid redirection URI.
        except errors.FatalClientError as e:
            log.debug('Fatal client error during validation of %r. %r.',
                      request, e)
            raise

        # If the resource owner denies the access request or if the request
        # fails for reasons other than a missing or invalid redirection URI,
        # the authorization server informs the client by adding the following
        # parameters to the fragment component of the redirection URI using the
        # "application/x-www-form-urlencoded" format, per Appendix B:
        # https://tools.ietf.org/html/rfc6749#appendix-B
        except errors.OAuth2Error as e:
            log.debug('Client error during validation of %r. %r.', request, e)
            return {'Location': common.add_params_to_uri(request.redirect_uri, e.twotuples,
                                                         fragment=True)}, None, 302

        # In OIDC implicit flow it is possible to have a request_type that does not include the access_token!
        # "id_token token" - return the access token and the id token
        # "id_token" - don't return the access token
        if "token" in request.response_type.split():
            token = token_handler.create_token(request, refresh_token=False, save_token=False)
        else:
            token = {}

        for modifier in self._token_modifiers:
            token = modifier(token, token_handler, request)

        # In OIDC implicit flow it is possible to have a request_type that does
        # not include the access_token! In this case there is no need to save a token.
        if "token" in request.response_type.split():
github oauthlib / oauthlib / oauthlib / oauth2 / rfc6749 / grant_types / implicit.py View on Github external
# error and MUST NOT automatically redirect the user-agent to the
        # invalid redirection URI.
        except errors.FatalClientError as e:
            log.debug('Fatal client error during validation of %r. %r.',
                      request, e)
            raise

        # If the resource owner denies the access request or if the request
        # fails for reasons other than a missing or invalid redirection URI,
        # the authorization server informs the client by adding the following
        # parameters to the fragment component of the redirection URI using the
        # "application/x-www-form-urlencoded" format, per Appendix B:
        # https://tools.ietf.org/html/rfc6749#appendix-B
        except errors.OAuth2Error as e:
            log.debug('Client error during validation of %r. %r.', request, e)
            return {'Location': common.add_params_to_uri(request.redirect_uri, e.twotuples,
                                                         fragment=True)}, None, 302

        # In OIDC implicit flow it is possible to have a request_type that does not include the access_token!
        # "id_token token" - return the access token and the id token
        # "id_token" - don't return the access token
        if "token" in request.response_type.split():
            token = token_handler.create_token(request, refresh_token=False)
        else:
            token = {}

        if request.state is not None:
            token['state'] = request.state

        for modifier in self._token_modifiers:
            token = modifier(token, token_handler, request)
github pymedusa / Medusa / ext / oauthlib / oauth2 / rfc6749 / tokens.py View on Github external
def random_token_generator(request, refresh_token=False):
    """
    :param request: OAuthlib request.
    :type request: oauthlib.common.Request
    :param refresh_token:
    """
    return common.generate_token()
github piterpy-meetup / postpost / postpost / api / serializers / user_registration.py View on Github external
)
        expires = timezone.now() + timedelta(seconds=oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS)

        access_token = AccessToken(
            user=user,
            scope='',
            expires=expires,
            token=common.generate_token(),
            application=application,
        )
        access_token.save()
        self._access_token = access_token.token

        refresh_token = RefreshToken(
            user=user,
            token=common.generate_token(),
            application=application,
            access_token=access_token,
        )
        refresh_token.save()
        self._refresh_token = refresh_token.token

        return user
github h3llrais3r / Auto-Subliminal / lib / oauthlib / oauth2 / rfc6749 / tokens.py View on Github external
def signed_token_generator(request):
        request.claims = kwargs
        return common.generate_signed_token(private_pem, request)
github h3llrais3r / Auto-Subliminal / lib / oauthlib / oauth2 / rfc6749 / grant_types / authorization_code.py View on Github external
def create_authorization_code(self, request):
        """
        Generates an authorization grant represented as a dictionary.

        :param request: OAuthlib request.
        :type request: oauthlib.common.Request
        """
        grant = {'code': common.generate_token()}
        if hasattr(request, 'state') and request.state:
            grant['state'] = request.state
        log.debug('Created authorization code grant %r for request %r.',
                  grant, request)
        return grant
github filiph / progress_bar / gae / oauthlib / oauth2 / rfc6749 / tokens.py View on Github external
http_method = http_method.upper()
    host, port = utils.host_from_uri(uri)

    if hash_algorithm.lower() == 'hmac-sha-1':
        h = hashlib.sha1
    elif hash_algorithm.lower() == 'hmac-sha-256':
        h = hashlib.sha256
    else:
        raise ValueError('unknown hash algorithm')

    if draft == 0:
        nonce = nonce or '{0}:{1}'.format(utils.generate_age(issue_time),
                                          common.generate_nonce())
    else:
        ts = common.generate_timestamp()
        nonce = common.generate_nonce()

    sch, net, path, par, query, fra = urlparse(uri)

    if query:
        request_uri = path + '?' + query
    else:
        request_uri = path

    # Hash the body/payload
    if body is not None and draft == 0:
        body = body.encode('utf-8')
        bodyhash = b2a_base64(h(body).digest())[:-1].decode('utf-8')
    else:
        bodyhash = ''

    # Create the normalized base string
github pymedusa / Medusa / ext / oauthlib / oauth2 / rfc6749 / grant_types / authorization_code.py View on Github external
# invalid redirection URI.
        except errors.FatalClientError as e:
            log.debug('Fatal client error during validation of %r. %r.',
                      request, e)
            raise

        # If the resource owner denies the access request or if the request
        # fails for reasons other than a missing or invalid redirection URI,
        # the authorization server informs the client by adding the following
        # parameters to the query component of the redirection URI using the
        # "application/x-www-form-urlencoded" format, per Appendix B:
        # https://tools.ietf.org/html/rfc6749#appendix-B
        except errors.OAuth2Error as e:
            log.debug('Client error during validation of %r. %r.', request, e)
            request.redirect_uri = request.redirect_uri or self.error_uri
            redirect_uri = common.add_params_to_uri(
                request.redirect_uri, e.twotuples,
                fragment=request.response_mode == "fragment")
            return {'Location': redirect_uri}, None, 302

        grant = self.create_authorization_code(request)
        for modifier in self._code_modifiers:
            grant = modifier(grant, token_handler, request)
        log.debug('Saving grant %r for %r.', grant, request)
        self.request_validator.save_authorization_code(
            request.client_id, grant, request)
        return self.prepare_authorization_response(
            request, grant, {}, None, 302)