本文整理汇总了Python中oauthlib.common.Request类的典型用法代码示例。如果您正苦于以下问题:Python Request类的具体用法?Python Request怎么用?Python Request使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Request类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_authorization_header
def _get_authorization_header(request, client_key, client_secret):
"""
Get proper HTTP Authorization header for a given request
Arguments:
request: Request object to log Authorization header for
Returns:
authorization header
"""
sha1 = hashlib.sha1()
body = request.body or ''
sha1.update(body)
oauth_body_hash = unicode(base64.b64encode(
sha1.digest() # pylint: disable=too-many-function-args
))
client = Client(client_key, client_secret)
params = client.get_oauth_params(request)
params.append((u'oauth_body_hash', oauth_body_hash))
blank_request = Request(urllib.unquote(request.url), http_method=request.method, body='', headers=request.headers, encoding='utf_8')
blank_request.oauth_params = params
blank_request.decoded_body = ''
signature = client.get_oauth_signature(blank_request)
blank_request.oauth_params.append((u'oauth_signature', signature))
headers = client._render( # pylint: disable=protected-access
blank_request
)[1]
return headers['Authorization']
示例2: create_token_response
def create_token_response(self, uri, http_method='GET', body=None,
headers=None, credentials=None, grant_type_for_scope=None,
claims=None):
"""Extract grant_type and route to the designated handler."""
request = Request(
uri, http_method=http_method, body=body, headers=headers)
# 'scope' is an allowed Token Request param in both the "Resource Owner Password Credentials Grant"
# and "Client Credentials Grant" flows
# https://tools.ietf.org/html/rfc6749#section-4.3.2
# https://tools.ietf.org/html/rfc6749#section-4.4.2
request.scopes = utils.scope_to_list(request.scope)
request.extra_credentials = credentials
if grant_type_for_scope:
request.grant_type = grant_type_for_scope
# OpenID Connect claims, if provided. The server using oauthlib might choose
# to implement the claims parameter of the Authorization Request. In this case
# it should retrieve those claims and pass them via the claims argument here,
# as a dict.
if claims:
request.claims = claims
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)
示例3: create_authorization_response
def create_authorization_response(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)
query_params = params_from_uri(request.uri)
body_params = request.decoded_body
# Prioritize response_type defined as query param over those in body.
# Chosen because the two core grant types utilizing the response type
# parameter both supply it in the uri. However it is not specified
# explicitely in RFC 6748.
if 'response_type' in query_params:
request.response_type = query_params.get('response_type')
elif 'response_type' in body_params:
request.response_type = body_params.get('response_type')
else:
raise errors.InvalidRequestError(
description='The response_type parameter is missing.')
if not request.response_type in self.response_types:
raise errors.UnsupportedResponseTypeError(
description='Invalid response type')
return self.response_types.get(
request.response_type).create_authorization_response(
request, self.default_token)
示例4: create_authorization_response
def create_authorization_response(self, uri, http_method='GET', body=None,
headers=None, realms=None, credentials=None):
"""Create an authorization response, with a new request token if valid.
:param uri: The full URI of the token request.
:param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.
:param body: The request body as a string.
:param headers: The request headers as a dict.
:param credentials: A list of credentials to include in the verifier.
:returns: A tuple of 4 elements.
1. The URI to be used to redirect the user back to client.
2. A dict of headers to set on the response.
3. The response body as a string.
4. The response status code as an integer.
An example of a valid request::
>>> from your_validator import your_validator
>>> from oauthlib.oauth1 import RequestTokenEndpoint
>>> endpoint = RequestTokenEndpoint(your_validator)
>>> u, h, b, s = endpoint.create_request_token_response(
... 'https://your.provider/request_token?foo=bar',
... headers={
... 'Authorization': 'OAuth realm=movies user, oauth_....'
... },
... credentials={
... 'extra': 'argument',
... })
>>> u
'https://the.client/callback?oauth_verifier=...&mextra=argument'
>>> h
{}
>>> b
''
>>> s
302
"""
request = Request(uri, http_method=http_method, body=body,
headers=headers)
if not self.request_validator.verify_request_token(
request.oauth_token, request):
raise errors.InvalidClientError()
if not request.oauth_token:
raise NotImplementedError('request.oauth_token must be set after '
'request token verification.')
request.realms = realms
if (request.realms and not self.request_validator.verify_realms(
request.oauth_token, request.realms, request)):
raise errors.InvalidRequestError(
description=('User granted access to realms outside of '
'what the client may request.'))
redirect_uri = self.request_validator.get_redirect_uri(
request.oauth_token, request)
verifier = self.create_verifier(request, credentials or {})
uri = add_params_to_uri(redirect_uri, verifier.items())
return uri, {}, None, 302
示例5: validate_authorization_request
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)
示例6: verify_request
def verify_request(self, uri, http_method='GET', body=None, headers=None):
"""Validate client, code etc, return body + headers"""
request = Request(uri, http_method, body, headers)
request.token_type = self.find_token_type(request)
token_type_handler = self.tokens.get(request.token_type,
self.default_token_type_handler)
return token_type_handler.validate_request(request)
示例7: test_request_invalid_client_id
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)
示例8: create_authorization_response
def create_authorization_response(self, uri, http_method='GET', body=None,
headers=None, scopes=None, credentials=None):
"""Extract response_type and route to the designated handler."""
request = Request(uri, http_method=http_method, body=body, headers=headers)
request.authorized_scopes = scopes
for k, v in (credentials or {}).items():
setattr(request, k, v)
response_type_handler = self.response_types.get(
request.response_type, self.default_response_type_handler)
return response_type_handler.create_authorization_response(
request, self.default_token)
示例9: create_token_response
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.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)
示例10: verify_request
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
示例11: create_authorization_response
def create_authorization_response(
self, uri, http_method="GET", body=None, headers=None, scopes=None, credentials=None
):
"""Extract response_type and route to the designated handler."""
request = Request(uri, http_method=http_method, body=body, headers=headers)
request.scopes = scopes
# TODO: decide whether this should be a required argument
request.user = None # TODO: explain this in docs
for k, v in (credentials or {}).items():
setattr(request, k, v)
response_type_handler = self.response_types.get(request.response_type, self.default_response_type_handler)
log.debug("Dispatching response_type %s request to %r.", request.response_type, response_type_handler)
return response_type_handler.create_authorization_response(request, self.default_token_type)
示例12: verify_request
def verify_request(self, uri, http_method='GET', body=None, headers=None):
"""Validate client, code etc, return body + headers"""
request = Request(uri, http_method, body, headers)
request.token_type = self.find_token_type(request)
# TODO(ib-lundgren): How to return errors is not strictly defined and
# should allow for customization.
if not request.token_type:
raise ValueError('Could not determine the token type.')
if not request.token_type in self.tokens:
raise ValueError('Unsupported token type.')
return self.tokens.get(request.token_type).validate_request(request)
示例13: test_validate_token_request
def test_validate_token_request(self):
mock_validator = mock.MagicMock()
auth = AuthorizationCodeGrant(request_validator=mock_validator)
request = Request('http://a.b/path')
self.assertRaises(UnsupportedGrantTypeError,
auth.validate_token_request, request)
request.grant_type = 'authorization_code'
self.assertRaises(InvalidRequestError,
auth.validate_token_request, request)
mock_validator.validate_client = mock.MagicMock(return_value=False)
request.code = 'waffles'
request.client = 'batman'
self.assertRaises(UnauthorizedClientError,
auth.validate_token_request, request)
mock_validator.validate_client = mock.MagicMock(return_value=True)
mock_validator.validate_code = mock.MagicMock(return_value=False)
self.assertRaises(InvalidGrantError,
auth.validate_token_request, request)
示例14: validate_2legged_oauth
def validate_2legged_oauth(oauth, uri, method, auth_header):
"""
"Two-legged" OAuth authorization isn't standard and so not
supported by current versions of oauthlib. The implementation
here is sufficient for simple developer tools and testing. Real
usage of OAuth will always require directing the user to the
authorization page so that a resource-owner token can be
generated.
"""
req = Request(uri, method, "", auth_header)
typ, params, oauth_params = oauth._get_signature_type_and_params(req)
oauth_params = dict(oauth_params)
req.params = filter(lambda x: x[0] not in ("oauth_signature", "realm"), params)
req.signature = oauth_params.get("oauth_signature")
req.client_key = oauth_params.get("oauth_consumer_key")
req.nonce = oauth_params.get("oauth_nonce")
req.timestamp = oauth_params.get("oauth_timestamp")
if oauth_params.get("oauth_signature_method").lower() != "hmac-sha1":
raise TwoLeggedOAuthError(u"unsupported signature method " + oauth_params.get("oauth_signature_method"))
secret = validator.get_client_secret(req.client_key, req)
valid_signature = signature.verify_hmac_sha1(req, secret, None)
if valid_signature:
return req.client_key
else:
raise TwoLeggedOAuthError(u"Cannot find APIAccess token with that key: %s" % req.client_key)
示例15: sign
def sign(self, uri, http_method=u'GET', body='', headers=None):
"""Sign a request
Signs an HTTP request with the specified parts.
Returns a 3-tuple of the signed request's URI, headers, and body.
Note that http_method is not returned as it is unaffected by the OAuth
signing process.
The body argument may be a dict, a list of 2-tuples, or a formencoded
string. If the body argument is not a formencoded string and/or the
Content-Type header is not 'x-www-form-urlencoded', it will be
returned verbatim as it is unaffected by the OAuth signing process.
Attempting to sign a request with non-formencoded data using the
OAuth body signature type is invalid and will raise an exception.
If the body does contain parameters, it will be returned as a properly-
formatted formencoded string.
All string data MUST be unicode. This includes strings inside body
dicts, for example.
"""
# normalize request data
request = Request(uri, http_method, body, headers)
# sanity check
content_type = request.headers.get('Content-Type', None)
if content_type == 'application/x-www-form-urlencoded' and not request.body_has_params:
raise ValueError("Headers indicate a formencoded body but body was not decodable.")
# generate the basic OAuth parameters
request.oauth_params = self.get_oauth_params()
# generate the signature
request.oauth_params.append((u'oauth_signature', self.get_oauth_signature(request)))
# render the signed request and return it
return self._render(request, formencode=True)