示例#1
0
 def test_create_authorization_grant(self):
     bearer = BearerToken(self.mock_validator)
     self.request.response_mode = 'query'
     h, b, s = self.auth.create_authorization_response(self.request, bearer)
     grant = dict(Request(h['Location']).uri_query_params)
     self.assertIn('code', grant)
     self.assertTrue(self.mock_validator.validate_redirect_uri.called)
     self.assertTrue(self.mock_validator.validate_response_type.called)
     self.assertTrue(self.mock_validator.validate_scopes.called)
示例#2
0
    def setUp(self):
        self.request = Request('http://a.b/path')
        request_validator = mock.MagicMock()
        implicit_grant = OAuth2ImplicitGrant(request_validator)
        openid_connect_implicit = ImplicitGrant(request_validator)

        self.dispatcher = ImplicitTokenGrantDispatcher(
            default_implicit_grant=implicit_grant,
            oidc_implicit_grant=openid_connect_implicit)
示例#3
0
 def validate_authorization_request(self, uri, http_method='GET', body=None,
                                    headers=None):
     """Extract response_type and route to the designated handler."""
     request = Request(
         uri, http_method=http_method, body=body, headers=headers)
     request.scopes = None
     response_type_handler = self.response_types.get(
         request.response_type, self.default_response_type_handler)
     return response_type_handler.validate_authorization_request(request)
示例#4
0
    def test_header_with_multispaces_is_validated(self):
        request_validator = mock.MagicMock()
        request_validator.validate_bearer_token = self._mocked_validate_bearer_token

        request = Request("/", headers=self.valid_header_with_multiple_spaces)
        result = BearerToken(
            request_validator=request_validator).validate_request(request)

        self.assertTrue(result)
示例#5
0
 def test_extract_params_with_urlencoded_json(self):
     wsgi_environ = {
         'QUERY_STRING': 'state=%7B%22t%22%3A%22a%22%2C%22i%22%3A%22l%22%7D'
     }
     with set_flask_request(wsgi_environ):
         uri, http_method, body, headers = extract_params()
         # Request constructor will try to urldecode the querystring, make
         # sure this doesn't fail.
         Request(uri, http_method, body, headers)
示例#6
0
 def setUp(self):
     mock_client = mock.MagicMock()
     mock_client.user.return_value = 'mocked user'
     self.request = Request('http://a.b/path')
     self.request.grant_type = 'urn:ietf:params:oauth:grant-type:saml2-bearer'
     self.request.assertion = 'assertion'
     self.request.client = mock_client
     self.request.scopes = ('mocked', 'scopes')
     self.mock_validator = mock.MagicMock()
     self.auth = SAML2BearerGrant(request_validator=self.mock_validator)
示例#7
0
 def setUp(self):
     mock_client = mock.MagicMock()
     mock_client.user.return_value = 'mocked user'
     self.request = Request('http://a.b/path')
     self.request.assertion = 'mocked assertion'
     self.request.grant_type = JWT_BEARER
     self.request.client = mock_client
     self.request.scope = 'foo'
     self.mock_validator = mock.MagicMock()
     self.auth = JWTBearerGrant(request_validator=self.mock_validator)
示例#8
0
 def setUp(self):
     mock_client = mock.MagicMock()
     mock_client.user.return_value = 'mocked user'
     self.request = Request('http://a.b/path')
     self.request.grant_type = 'refresh_token'
     self.request.refresh_token = 'lsdkfhj230'
     self.request.client = mock_client
     self.request.scope = 'foo'
     self.mock_validator = mock.MagicMock()
     self.auth = RefreshTokenGrant(request_validator=self.mock_validator)
示例#9
0
    def test_fake_bearer_is_not_validated(self):
        request_validator = mock.MagicMock()
        request_validator.validate_bearer_token = self._mocked_validate_bearer_token

        for fake_header in self.fake_bearer_headers:
            request = Request("/", headers=fake_header)
            result = BearerToken(
                request_validator=request_validator).validate_request(request)

            self.assertFalse(result)
示例#10
0
 def test_sanitizing_authorization_header(self):
     r = Request(URI,
                 headers={
                     'Accept': 'application/json',
                     'Authorization': 'Basic Zm9vOmJhcg=='
                 })
     self.assertNotIn('Zm9vOmJhcg==', repr(r))
     self.assertIn('<SANITIZED>', repr(r))
     # Double-check we didn't modify the underlying object:
     self.assertEqual(r.headers['Authorization'], 'Basic Zm9vOmJhcg==')
示例#11
0
 def test_authenticate_client(self):
     request = Request('http://localhost/authenticate_client', 'GET', None,
                       {
                           'client_id': '10',
                           'client_secret': 'secret'
                       })
     self.assertTrue(self.validator.authenticate_client(request))
     request = Request('http://localhost/authenticate_client', 'GET', None,
                       {
                           'client_id': '10',
                           'client_secret': 'secre'
                       })
     self.assertFalse(self.validator.authenticate_client(request))
     request = Request('http://localhost/authenticate_client', 'GET', None,
                       {
                           'client_id': '1',
                           'client_secret': 'secret'
                       })
     self.assertFalse(self.validator.authenticate_client(request))
示例#12
0
 def setUp(self):
     self.request = Request('http://a.b/path')
     self.request.grant_type = 'password'
     self.request.username = '******'
     self.request.password = '******'
     self.request.client = 'mock authenticated'
     self.request.scopes = ('mocked', 'scopes')
     self.mock_validator = mock.MagicMock()
     self.auth = ResourceOwnerPasswordCredentialsGrant(
         request_validator=self.mock_validator)
示例#13
0
 def setUp(self):
     mock_client = mock.MagicMock()
     mock_client.user.return_value = 'mocked user'
     self.request = Request('http://a.b/path')
     self.request.grant_type = 'client_credentials'
     self.request.client = mock_client
     self.request.scopes = ('mocked', 'scopes')
     self.mock_validator = mock.MagicMock()
     self.auth = ClientCredentialsGrant(
             request_validator=self.mock_validator)
示例#14
0
    def setUp(self):
        self.request = Request('http://a.b/path')
        self.request.decoded_body = (
            ("client_id", "me"),
            ("code", "code"),
            ("redirect_url", "https://a.b/cb"),
        )

        self.request_validator = mock.MagicMock()
        self.auth_grant = OAuth2AuthorizationCodeGrant(self.request_validator)
        self.openid_connect_auth = AuthorizationCodeGrant(self.request_validator)
    def test_request_invalid_client_id(self):
        request = Request('https://a.b./path')
        request.scope = 'openid profile'
        request.response_type = 'code'
        with pytest.raises(errors.MissingClientIdError):
            self.auth.validate_authorization_request(request)

        request.client_id = 'invalid_client'
        self.validator.validate_client_id.return_value = False
        with pytest.raises(errors.InvalidClientIdError):
            self.auth.validate_authorization_request(request)
示例#16
0
 def test_validate_lti_old_timestamp(self):
     request = Request(uri='https://example.com/lti',
                       http_method='POST',
                       body=self.read_data_file('lti_old_timestamp.txt'))
     parameters = LTIAuthBackend._get_validated_lti_params_from_values(  # pylint: disable=protected-access
         request=request,
         current_time=1436900000,
         lti_consumer_valid=True,
         lti_consumer_secret='secret',
         lti_max_timestamp_age=10)
     self.assertFalse(parameters)
示例#17
0
    def setUp(self):
        self.request = Request('http://a.b/path')
        self.request.scopes = ('hello', 'world')
        self.request.client = 'batman'
        self.request.client_id = 'abcdef'
        self.request.response_type = 'token'
        self.request.state = 'xyz'
        self.request.redirect_uri = 'https://b.c/p'

        self.mock_validator = mock.MagicMock()
        self.auth = ImplicitGrant(request_validator=self.mock_validator)
示例#18
0
 def verify_request(self, uri, http_method='GET', body=None, headers=None,
                    scopes=None):
     """Validate client, code etc, return body + headers"""
     request = Request(uri, http_method, body, headers)
     request.token_type = self.find_token_type(request)
     request.scopes = scopes
     token_type_handler = self.tokens.get(request.token_type,
                                          self.default_token_type_handler)
     log.debug('Dispatching token_type %s request to %r.',
               request.token_type, token_type_handler)
     return token_type_handler.validate_request(request), request
示例#19
0
 def oauth_error(self, request, error, **kwargs):
     # UGLY HACK
     from oauthlib.common import Request
     core = self.get_oauthlib_core()
     uri, http_method, body, headers = core._extract_params(request)
     orequest = Request(uri,
                        http_method=http_method,
                        body=body,
                        headers=headers)
     raise OAuthToolkitError(
         error=error(request=orequest, state=orequest.state, **kwargs))
示例#20
0
 def test_non_unicode_params(self):
     r = Request(
         bytes_type('http://a.b/path?query', 'utf-8'),
         http_method=bytes_type('GET', 'utf-8'),
         body=bytes_type('you=shall+pass', 'utf-8'),
         headers={bytes_type('a', 'utf-8'): bytes_type('b', 'utf-8')})
     self.assertEqual(r.uri, 'http://a.b/path?query')
     self.assertEqual(r.http_method, 'GET')
     self.assertEqual(r.body, 'you=shall+pass')
     self.assertEqual(r.decoded_body, [('you', 'shall pass')])
     self.assertEqual(r.headers, {'a': 'b'})
示例#21
0
    def test_extract_params_with_json(self):
        data = {'test': 'foo', 'foo': 'bar'}
        json_payload = json.dumps(data).encode('utf-8')

        wsgi_environ = {
            'CONTENT_TYPE': 'application/json',
            'CONTENT_LENGHT': str(len(data))
        }
        with set_flask_request(wsgi_environ, data):
            uri, http_method, body, headers = extract_params()
            Request(uri, http_method, body, headers)
            self.assertEqual(body, {'test': 'foo', 'foo': 'bar'})
 def test_validate_lti_cannot_add_get_params(self):
     request = Request(
         uri='https://example.com/lti?custom_another=parameter',
         http_method='POST',
         body=self.read_data_file('lti_cannot_add_get_params.txt')
     )
     parameters = LTIAuthBackend._get_validated_lti_params_from_values(  # pylint: disable=protected-access
         request=request, current_time=1436823554,
         lti_consumer_valid=True, lti_consumer_secret='secret',
         lti_max_timestamp_age=10
     )
     assert not parameters
示例#23
0
 def test_non_unicode_params(self):
     r = Request(b'http://a.b/path?query',
                 http_method=b'GET',
                 body=b'you=shall+pass',
                 headers={
                     b'a': b'b',
                 })
     self.assertEqual(r.uri, 'http://a.b/path?query')
     self.assertEqual(r.http_method, 'GET')
     self.assertEqual(r.body, 'you=shall+pass')
     self.assertEqual(r.decoded_body, [('you', 'shall pass')])
     self.assertEqual(r.headers, {'a': 'b'})
示例#24
0
文件: token.py 项目: GoogleJump/ninja
 def create_token_response(self, uri, http_method='GET', body=None,
         headers=None, credentials=None):
     """Extract grant_type and route to the designated handler."""
     request = Request(uri, http_method=http_method, body=body, headers=headers)
     request.scopes = None
     request.extra_credentials = credentials
     grant_type_handler = self.grant_types.get(request.grant_type,
             self.default_grant_type_handler)
     log.debug('Dispatching grant_type %s request to %r.',
               request.grant_type, grant_type_handler)
     return grant_type_handler.create_token_response(
             request, self.default_token_type)
示例#25
0
    def _create_request(self, uri, http_method, body, headers):
        # Only include body data from x-www-form-urlencoded requests
        headers = CaseInsensitiveDict(headers or {})
        if (
            "Content-Type" in headers
            and CONTENT_TYPE_FORM_URLENCODED in headers["Content-Type"]
        ):
            request = Request(uri, http_method, body, headers)
        else:
            request = Request(uri, http_method, "", headers)

        signature_type, params, oauth_params = self._get_signature_type_and_params(
            request
        )

        # The server SHOULD return a 400 (Bad Request) status code when
        # receiving a request with duplicated protocol parameters.
        if len(dict(oauth_params)) != len(oauth_params):
            raise errors.InvalidRequestError(description="Duplicate OAuth1 entries.")

        oauth_params = dict(oauth_params)
        request.signature = oauth_params.get("oauth_signature")
        request.client_key = oauth_params.get("oauth_consumer_key")
        request.resource_owner_key = oauth_params.get("oauth_token")
        request.nonce = oauth_params.get("oauth_nonce")
        request.timestamp = oauth_params.get("oauth_timestamp")
        request.redirect_uri = oauth_params.get("oauth_callback")
        request.verifier = oauth_params.get("oauth_verifier")
        request.signature_method = oauth_params.get("oauth_signature_method")
        request.realm = dict(params).get("realm")
        request.oauth_params = oauth_params

        # Parameters to Client depend on signature method which may vary
        # for each request. Note that HMAC-SHA1 and PLAINTEXT share parameters
        request.params = [(k, v) for k, v in params if k != "oauth_signature"]

        if "realm" in request.headers.get("Authorization", ""):
            request.params = [(k, v) for k, v in request.params if k != "realm"]

        return request
示例#26
0
    async def create_revocation_response(self,
                                         uri,
                                         http_method='POST',
                                         body=None,
                                         headers=None):
        """Revoke supplied access or refresh token.


        The authorization server responds with HTTP status code 200 if the
        token has been revoked sucessfully or if the client submitted an
        invalid token.

        Note: invalid tokens do not cause an error response since the client
        cannot handle such an error in a reasonable way.  Moreover, the purpose
        of the revocation request, invalidating the particular token, is
        already achieved.

        The content of the response body is ignored by the client as all
        necessary information is conveyed in the response code.

        An invalid token type hint value is ignored by the authorization server
        and does not influence the revocation response.
        """
        resp_headers = {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-store',
            'Pragma': 'no-cache',
        }
        request = Request(uri,
                          http_method=http_method,
                          body=body,
                          headers=headers)
        try:
            await self.validate_revocation_request(request)
            log.debug('Token revocation valid for %r.', request)
        except OAuth2Error as e:
            log.debug('Client error during validation of %r. %r.', request, e)
            response_body = e.json
            if self.enable_jsonp and request.callback:
                response_body = '{}({});'.format(request.callback,
                                                 response_body)
            resp_headers.update(e.headers)
            return resp_headers, response_body, e.status_code

        await self.request_validator.revoke_token(request.token,
                                                  request.token_type_hint,
                                                  request)

        response_body = ''
        if self.enable_jsonp and request.callback:
            response_body = request.callback + '();'
        return {}, response_body, 200
示例#27
0
    def _create_request(self, uri, http_method, body, headers):
        # Only include body data from x-www-form-urlencoded requests
        headers = headers or {}
        if ('Content-Type' in headers
                and CONTENT_TYPE_FORM_URLENCODED in headers['Content-Type']):
            request = Request(uri, http_method, body, headers)
        else:
            request = Request(uri, http_method, '', headers)

        signature_type, params, oauth_params = (
            self._get_signature_type_and_params(request))

        # The server SHOULD return a 400 (Bad Request) status code when
        # receiving a request with duplicated protocol parameters.
        if len(dict(oauth_params)) != len(oauth_params):
            raise errors.InvalidRequestError(
                description='Duplicate OAuth1 entries.')

        oauth_params = dict(oauth_params)
        request.signature = oauth_params.get('oauth_signature')
        request.client_key = oauth_params.get('oauth_consumer_key')
        request.resource_owner_key = oauth_params.get('oauth_token')
        request.nonce = oauth_params.get('oauth_nonce')
        request.timestamp = oauth_params.get('oauth_timestamp')
        request.redirect_uri = oauth_params.get('oauth_callback')
        request.verifier = oauth_params.get('oauth_verifier')
        request.signature_method = oauth_params.get('oauth_signature_method')
        request.realm = dict(params).get('realm')
        request.oauth_params = oauth_params

        # Parameters to Client depend on signature method which may vary
        # for each request. Note that HMAC-SHA1 and PLAINTEXT share parameters
        request.params = [(k, v) for k, v in params if k != 'oauth_signature']

        if 'realm' in request.headers.get('Authorization', ''):
            request.params = [(k, v) for k, v in request.params
                              if k != 'realm']

        return request
示例#28
0
 def setUp(self):
     """Set up tests."""
     self.token = 'f34mfSADsf45sada31mF'
     self.scopes = []
     self.headers = {
         'Authorization': 'Bearer %s' % self.token,
         'UWUM': True,
     }
     self.request = Request(
         'https://geokey.org.uk/api/projects/',
         http_method='GET',
         body=None,
         headers=self.headers)
    def __create_django_request(
        self, uri, http_method='GET', body=None, headers=None, credentials=None
    ):
        """
        Assembles a request and assigns django_request to Request object.
        """
        request = Request(uri, http_method=http_method, body=body, headers=headers)
        request.scopes = ['read', 'write']
        request.extra_credentials = credentials
        # Make sure we consume the django request object
        request.django_request = self.pop_request_object()

        return request
示例#30
0
 def test_create_authorization_grant_state(self):
     self.request.state = 'abc'
     self.request.redirect_uri = None
     self.mock_validator.get_default_redirect_uri.return_value = 'https://a.b/cb'
     bearer = BearerToken(self.mock_validator)
     h, b, s = self.auth.create_authorization_response(self.request, bearer)
     grant = dict(Request(h['Location']).uri_query_params)
     self.assertIn('code', grant)
     self.assertIn('state', grant)
     self.assertFalse(self.mock_validator.validate_redirect_uri.called)
     self.assertTrue(self.mock_validator.get_default_redirect_uri.called)
     self.assertTrue(self.mock_validator.validate_response_type.called)
     self.assertTrue(self.mock_validator.validate_scopes.called)