summaryrefslogtreecommitdiff
path: root/oauthlib
diff options
context:
space:
mode:
authorJonathan Huot <JonathanHuot@users.noreply.github.com>2019-07-19 09:22:21 +0200
committerGitHub <noreply@github.com>2019-07-19 09:22:21 +0200
commitfe9ec057f3cba2f8428ad666ad557d2f77188268 (patch)
treea4b4f4b8567e59f8b0558f2de8786af820cd0c54 /oauthlib
parent9e824cfb0eb36b4d23ab73171b821b1a74ec659c (diff)
parentd7b90fc841694f126ec63500ea8f74330c4672eb (diff)
downloadoauthlib-fe9ec057f3cba2f8428ad666ad557d2f77188268.tar.gz
Merge branch 'master' into release-3.0.2release-3.0.2
Diffstat (limited to 'oauthlib')
-rw-r--r--oauthlib/__init__.py17
-rw-r--r--oauthlib/common.py5
-rw-r--r--oauthlib/oauth1/rfc5849/__init__.py5
-rw-r--r--oauthlib/oauth1/rfc5849/endpoints/base.py4
-rw-r--r--oauthlib/oauth1/rfc5849/signature.py57
-rw-r--r--oauthlib/oauth2/rfc6749/clients/backend_application.py17
-rw-r--r--oauthlib/oauth2/rfc6749/clients/base.py35
-rw-r--r--oauthlib/oauth2/rfc6749/clients/legacy_application.py14
-rw-r--r--oauthlib/oauth2/rfc6749/clients/service_application.py36
-rw-r--r--oauthlib/oauth2/rfc6749/endpoints/base.py31
-rw-r--r--oauthlib/oauth2/rfc6749/endpoints/introspect.py3
-rw-r--r--oauthlib/oauth2/rfc6749/endpoints/revocation.py3
-rw-r--r--oauthlib/oauth2/rfc6749/endpoints/token.py10
-rw-r--r--oauthlib/oauth2/rfc6749/grant_types/authorization_code.py3
-rw-r--r--oauthlib/oauth2/rfc6749/parameters.py18
-rw-r--r--oauthlib/oauth2/rfc6749/request_validator.py193
-rw-r--r--oauthlib/oauth2/rfc6749/tokens.py4
-rw-r--r--oauthlib/openid/__init__.py1
-rw-r--r--oauthlib/openid/connect/core/grant_types/authorization_code.py20
-rw-r--r--oauthlib/openid/connect/core/grant_types/base.py97
-rw-r--r--oauthlib/openid/connect/core/grant_types/implicit.py4
-rw-r--r--oauthlib/openid/connect/core/request_validator.py76
22 files changed, 375 insertions, 278 deletions
diff --git a/oauthlib/__init__.py b/oauthlib/__init__.py
index 089977c..f1457a9 100644
--- a/oauthlib/__init__.py
+++ b/oauthlib/__init__.py
@@ -15,3 +15,20 @@ __author__ = 'The OAuthlib Community'
__version__ = '3.0.2'
logging.getLogger('oauthlib').addHandler(NullHandler())
+
+_DEBUG = False
+
+def set_debug(debug_val):
+ """Set value of debug flag
+
+ :param debug_val: Value to set. Must be a bool value.
+ """
+ global _DEBUG
+ _DEBUG = debug_val
+
+def get_debug():
+ """Get debug mode value.
+
+ :return: `True` if debug mode is on, `False` otherwise
+ """
+ return _DEBUG
diff --git a/oauthlib/common.py b/oauthlib/common.py
index 970d7a5..5aeb015 100644
--- a/oauthlib/common.py
+++ b/oauthlib/common.py
@@ -14,6 +14,7 @@ import logging
import re
import sys
import time
+from . import get_debug
try:
from secrets import randbits
@@ -172,7 +173,7 @@ def extract_params(raw):
empty list of parameters. Any other input will result in a return
value of None.
"""
- if isinstance(raw, bytes) or isinstance(raw, unicode_type):
+ if isinstance(raw, (bytes, unicode_type)):
try:
params = urldecode(raw)
except ValueError:
@@ -435,6 +436,8 @@ class Request(object):
raise AttributeError(name)
def __repr__(self):
+ if not get_debug():
+ return "<oauthlib.Request SANITIZED>"
body = self.body
headers = self.headers.copy()
if body:
diff --git a/oauthlib/oauth1/rfc5849/__init__.py b/oauthlib/oauth1/rfc5849/__init__.py
index 7313286..4f462bb 100644
--- a/oauthlib/oauth1/rfc5849/__init__.py
+++ b/oauthlib/oauth1/rfc5849/__init__.py
@@ -133,12 +133,11 @@ class Client(object):
log.debug("Collected params: {0}".format(collected_params))
normalized_params = signature.normalize_parameters(collected_params)
- normalized_uri = signature.normalize_base_string_uri(uri,
- headers.get('Host', None))
+ normalized_uri = signature.base_string_uri(uri, headers.get('Host', None))
log.debug("Normalized params: {0}".format(normalized_params))
log.debug("Normalized URI: {0}".format(normalized_uri))
- base_string = signature.construct_base_string(request.http_method,
+ base_string = signature.signature_base_string(request.http_method,
normalized_uri, normalized_params)
log.debug("Signing: signature base string: {0}".format(base_string))
diff --git a/oauthlib/oauth1/rfc5849/endpoints/base.py b/oauthlib/oauth1/rfc5849/endpoints/base.py
index 9702939..ecf8a50 100644
--- a/oauthlib/oauth1/rfc5849/endpoints/base.py
+++ b/oauthlib/oauth1/rfc5849/endpoints/base.py
@@ -10,7 +10,7 @@ from __future__ import absolute_import, unicode_literals
import time
-from oauthlib.common import Request, generate_token
+from oauthlib.common import CaseInsensitiveDict, Request, generate_token
from .. import (CONTENT_TYPE_FORM_URLENCODED, SIGNATURE_HMAC, SIGNATURE_RSA,
SIGNATURE_TYPE_AUTH_HEADER, SIGNATURE_TYPE_BODY,
@@ -67,7 +67,7 @@ class BaseEndpoint(object):
def _create_request(self, uri, http_method, body, headers):
# Only include body data from x-www-form-urlencoded requests
- headers = headers or {}
+ 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)
diff --git a/oauthlib/oauth1/rfc5849/signature.py b/oauthlib/oauth1/rfc5849/signature.py
index e90d6f3..f899aca 100644
--- a/oauthlib/oauth1/rfc5849/signature.py
+++ b/oauthlib/oauth1/rfc5849/signature.py
@@ -40,9 +40,10 @@ except ImportError:
log = logging.getLogger(__name__)
-def construct_base_string(http_method, base_string_uri,
+
+def signature_base_string(http_method, base_str_uri,
normalized_encoded_request_parameters):
- """**String Construction**
+ """**Construct the signature base string.**
Per `section 3.4.1.1`_ of the spec.
For example, the HTTP request::
@@ -90,7 +91,7 @@ def construct_base_string(http_method, base_string_uri,
#
# .. _`Section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2
# .. _`Section 3.4.6`: https://tools.ietf.org/html/rfc5849#section-3.4.6
- base_string += utils.escape(base_string_uri)
+ base_string += utils.escape(base_str_uri)
# 4. An "&" character (ASCII code 38).
base_string += '&'
@@ -105,9 +106,9 @@ def construct_base_string(http_method, base_string_uri,
return base_string
-def normalize_base_string_uri(uri, host=None):
+def base_string_uri(uri, host=None):
"""**Base String URI**
- Per `section 3.4.1.2`_ of the spec.
+ Per `section 3.4.1.2`_ of RFC 5849.
For example, the HTTP request::
@@ -177,7 +178,31 @@ def normalize_base_string_uri(uri, host=None):
if (scheme, port) in default_ports:
netloc = host
- return urlparse.urlunparse((scheme, netloc, path, params, '', ''))
+ v = urlparse.urlunparse((scheme, netloc, path, params, '', ''))
+
+ # RFC 5849 does not specify which characters are encoded in the
+ # "base string URI", nor how they are encoded - which is very bad, since
+ # the signatures won't match if there are any differences. Fortunately,
+ # most URIs only use characters that are clearly not encoded (e.g. digits
+ # and A-Z, a-z), so have avoided any differences between implementations.
+ #
+ # The example from its section 3.4.1.2 illustrates that spaces in
+ # the path are percent encoded. But it provides no guidance as to what other
+ # characters (if any) must be encoded (nor how); nor if characters in the
+ # other components are to be encoded or not.
+ #
+ # This implementation **assumes** that **only** the space is percent-encoded
+ # and it is done to the entire value (not just to spaces in the path).
+ #
+ # This code may need to be changed if it is discovered that other characters
+ # are expected to be encoded.
+ #
+ # Note: the "base string URI" returned by this function will be encoded
+ # again before being concatenated into the "signature base string". So any
+ # spaces in the URI will actually appear in the "signature base string"
+ # as "%2520" (the "%20" further encoded according to section 3.6).
+
+ return v.replace(' ', '%20')
# ** Request Parameters **
@@ -624,13 +649,15 @@ def verify_hmac_sha1(request, client_secret=None,
"""
norm_params = normalize_parameters(request.params)
- uri = normalize_base_string_uri(request.uri)
- base_string = construct_base_string(request.http_method, uri, norm_params)
- signature = sign_hmac_sha1(base_string, client_secret,
+ bs_uri = base_string_uri(request.uri)
+ sig_base_str = signature_base_string(request.http_method, bs_uri,
+ norm_params)
+ signature = sign_hmac_sha1(sig_base_str, client_secret,
resource_owner_secret)
match = safe_string_equals(signature, request.signature)
if not match:
- log.debug('Verify HMAC-SHA1 failed: sig base string: %s', base_string)
+ log.debug('Verify HMAC-SHA1 failed: signature base string: %s',
+ sig_base_str)
return match
@@ -657,16 +684,18 @@ def verify_rsa_sha1(request, rsa_public_key):
.. _`RFC2616 section 5.2`: https://tools.ietf.org/html/rfc2616#section-5.2
"""
norm_params = normalize_parameters(request.params)
- uri = normalize_base_string_uri(request.uri)
- message = construct_base_string(request.http_method, uri, norm_params).encode('utf-8')
+ bs_uri = base_string_uri(request.uri)
+ sig_base_str = signature_base_string(request.http_method, bs_uri,
+ norm_params).encode('utf-8')
sig = binascii.a2b_base64(request.signature.encode('utf-8'))
alg = _jwt_rs1_signing_algorithm()
key = _prepare_key_plus(alg, rsa_public_key)
- verify_ok = alg.verify(message, key, sig)
+ verify_ok = alg.verify(sig_base_str, key, sig)
if not verify_ok:
- log.debug('Verify RSA-SHA1 failed: sig base string: %s', message)
+ log.debug('Verify RSA-SHA1 failed: signature base string: %s',
+ sig_base_str)
return verify_ok
diff --git a/oauthlib/oauth2/rfc6749/clients/backend_application.py b/oauthlib/oauth2/rfc6749/clients/backend_application.py
index a000ecf..5737814 100644
--- a/oauthlib/oauth2/rfc6749/clients/backend_application.py
+++ b/oauthlib/oauth2/rfc6749/clients/backend_application.py
@@ -29,11 +29,11 @@ class BackendApplicationClient(Client):
Since the client authentication is used as the authorization grant,
no additional authorization request is needed.
"""
-
+
grant_type = 'client_credentials'
-
+
def prepare_request_body(self, body='', scope=None,
- include_client_id=None, **kwargs):
+ include_client_id=False, **kwargs):
"""Add the client credentials to the request body.
The client makes a request to the token endpoint by adding the
@@ -45,11 +45,11 @@ class BackendApplicationClient(Client):
:param scope: The scope of the access request as described by
`Section 3.3`_.
- :param include_client_id: `True` to send the `client_id` in the body of
- the upstream request. Default `None`. This is
- required if the client is not authenticating
- with the authorization server as described
- in `Section 3.2.1`_.
+ :param include_client_id: `True` to send the `client_id` in the
+ body of the upstream request. This is required
+ if the client is not authenticating with the
+ authorization server as described in
+ `Section 3.2.1`_. False otherwise (default).
:type include_client_id: Boolean
:param kwargs: Extra credentials to include in the token request.
@@ -71,5 +71,6 @@ class BackendApplicationClient(Client):
"""
kwargs['client_id'] = self.client_id
kwargs['include_client_id'] = include_client_id
+ scope = self.scope if scope is None else scope
return prepare_token_request(self.grant_type, body=body,
scope=scope, **kwargs)
diff --git a/oauthlib/oauth2/rfc6749/clients/base.py b/oauthlib/oauth2/rfc6749/clients/base.py
index 1a50644..9b05ad5 100644
--- a/oauthlib/oauth2/rfc6749/clients/base.py
+++ b/oauthlib/oauth2/rfc6749/clients/base.py
@@ -28,8 +28,8 @@ FORM_ENC_HEADERS = {
'Content-Type': 'application/x-www-form-urlencoded'
}
-class Client(object):
+class Client(object):
"""Base OAuth2 client responsible for access token management.
This class also acts as a generic interface providing methods common to all
@@ -201,7 +201,7 @@ class Client(object):
headers, token_placement, **kwargs)
def prepare_authorization_request(self, authorization_url, state=None,
- redirect_url=None, scope=None, **kwargs):
+ redirect_url=None, scope=None, **kwargs):
"""Prepare the authorization request.
This is the first step in many OAuth flows in which the user is
@@ -222,6 +222,8 @@ class Client(object):
the provider. If provided then it must also be provided in the
token request.
+ :param scope:
+
:param kwargs: Additional parameters to included in the request.
:returns: The prepared request tuple with (url, headers, body).
@@ -233,12 +235,12 @@ class Client(object):
self.redirect_url = redirect_url or self.redirect_url
self.scope = scope or self.scope
auth_url = self.prepare_request_uri(
- authorization_url, redirect_uri=self.redirect_url,
- scope=self.scope, state=self.state, **kwargs)
+ authorization_url, redirect_uri=self.redirect_url,
+ scope=self.scope, state=self.state, **kwargs)
return auth_url, FORM_ENC_HEADERS, ''
def prepare_token_request(self, token_url, authorization_response=None,
- redirect_url=None, state=None, body='', **kwargs):
+ redirect_url=None, state=None, body='', **kwargs):
"""Prepare a token creation request.
Note that these requests usually require client authentication, either
@@ -255,6 +257,8 @@ class Client(object):
:param redirect_url: The redirect_url supplied with the authorization
request (if there was one).
+ :param state:
+
:param body: Existing request body (URL encoded string) to embed parameters
into. This may contain extra paramters. Default ''.
@@ -268,15 +272,15 @@ class Client(object):
state = state or self.state
if authorization_response:
self.parse_request_uri_response(
- authorization_response, state=state)
+ authorization_response, state=state)
self.redirect_url = redirect_url or self.redirect_url
body = self.prepare_request_body(body=body,
- redirect_uri=self.redirect_url, **kwargs)
+ redirect_uri=self.redirect_url, **kwargs)
return token_url, FORM_ENC_HEADERS, body
def prepare_refresh_token_request(self, token_url, refresh_token=None,
- body='', scope=None, **kwargs):
+ body='', scope=None, **kwargs):
"""Prepare an access token refresh request.
Expired access tokens can be replaced by new access tokens without
@@ -304,11 +308,11 @@ class Client(object):
self.scope = scope or self.scope
body = self.prepare_refresh_body(body=body,
- refresh_token=refresh_token, scope=self.scope, **kwargs)
+ refresh_token=refresh_token, scope=self.scope, **kwargs)
return token_url, FORM_ENC_HEADERS, body
def prepare_token_revocation_request(self, revocation_url, token,
- token_type_hint="access_token", body='', callback=None, **kwargs):
+ token_type_hint="access_token", body='', callback=None, **kwargs):
"""Prepare a token revocation request.
:param revocation_url: Provider token revocation endpoint URL.
@@ -319,6 +323,8 @@ class Client(object):
``"refresh_token"``. This is optional and if you wish to not pass it you
must provide ``token_type_hint=None``.
+ :param body:
+
:param callback: A jsonp callback such as ``package.callback`` to be invoked
upon receiving the response. Not that it should not include a () suffix.
@@ -363,8 +369,8 @@ class Client(object):
raise InsecureTransportError()
return prepare_token_revocation_request(revocation_url, token,
- token_type_hint=token_type_hint, body=body, callback=callback,
- **kwargs)
+ token_type_hint=token_type_hint, body=body, callback=callback,
+ **kwargs)
def parse_request_body_response(self, body, scope=None, **kwargs):
"""Parse the JSON response body.
@@ -404,7 +410,7 @@ class Client(object):
If omitted, the authorization server SHOULD provide the
expiration time via other means or document the default value.
- **scope**
+ **scope**
Providers may supply this in all responses but are required to only
if it has changed since the authorization request.
@@ -461,6 +467,9 @@ class Client(object):
Warning: MAC token support is experimental as the spec is not yet stable.
"""
+ if token_placement != AUTH_HEADER:
+ raise ValueError("Invalid token placement.")
+
headers = tokens.prepare_mac_header(self.access_token, uri,
self.mac_key, http_method, headers=headers, body=body, ext=ext,
hash_algorithm=self.mac_algorithm, **kwargs)
diff --git a/oauthlib/oauth2/rfc6749/clients/legacy_application.py b/oauthlib/oauth2/rfc6749/clients/legacy_application.py
index 2449363..ca218e4 100644
--- a/oauthlib/oauth2/rfc6749/clients/legacy_application.py
+++ b/oauthlib/oauth2/rfc6749/clients/legacy_application.py
@@ -34,14 +34,14 @@ class LegacyApplicationClient(Client):
credentials is beyond the scope of this specification. The client
MUST discard the credentials once an access token has been obtained.
"""
-
+
grant_type = 'password'
def __init__(self, client_id, **kwargs):
super(LegacyApplicationClient, self).__init__(client_id, **kwargs)
def prepare_request_body(self, username, password, body='', scope=None,
- include_client_id=None, **kwargs):
+ include_client_id=False, **kwargs):
"""Add the resource owner password and username to the request body.
The client makes a request to the token endpoint by adding the
@@ -54,11 +54,11 @@ class LegacyApplicationClient(Client):
into. This may contain extra paramters. Default ''.
:param scope: The scope of the access request as described by
`Section 3.3`_.
- :param include_client_id: `True` to send the `client_id` in the body of
- the upstream request. Default `None`. This is
- required if the client is not authenticating
- with the authorization server as described
- in `Section 3.2.1`_.
+ :param include_client_id: `True` to send the `client_id` in the
+ body of the upstream request. This is required
+ if the client is not authenticating with the
+ authorization server as described in
+ `Section 3.2.1`_. False otherwise (default).
:type include_client_id: Boolean
:param kwargs: Extra credentials to include in the token request.
diff --git a/oauthlib/oauth2/rfc6749/clients/service_application.py b/oauthlib/oauth2/rfc6749/clients/service_application.py
index 35333d8..ea946ce 100644
--- a/oauthlib/oauth2/rfc6749/clients/service_application.py
+++ b/oauthlib/oauth2/rfc6749/clients/service_application.py
@@ -41,20 +41,20 @@ class ServiceApplicationClient(Client):
:param private_key: Private key used for signing and encrypting.
Must be given as a string.
- :param subject: The principal that is the subject of the JWT, i.e.
+ :param subject: The principal that is the subject of the JWT, i.e.
which user is the token requested on behalf of.
For example, ``foo@example.com.
:param issuer: The JWT MUST contain an "iss" (issuer) claim that
contains a unique identifier for the entity that issued
- the JWT. For example, ``your-client@provider.com``.
+ the JWT. For example, ``your-client@provider.com``.
:param audience: A value identifying the authorization server as an
intended audience, e.g.
``https://provider.com/oauth2/token``.
:param kwargs: Additional arguments to pass to base client, such as
- state and token. See ``Client.__init__.__doc__`` for
+ state and token. See ``Client.__init__.__doc__`` for
details.
"""
super(ServiceApplicationClient, self).__init__(client_id, **kwargs)
@@ -63,17 +63,17 @@ class ServiceApplicationClient(Client):
self.issuer = issuer
self.audience = audience
- def prepare_request_body(self,
+ def prepare_request_body(self,
private_key=None,
- subject=None,
- issuer=None,
- audience=None,
- expires_at=None,
+ subject=None,
+ issuer=None,
+ audience=None,
+ expires_at=None,
issued_at=None,
extra_claims=None,
- body='',
+ body='',
scope=None,
- include_client_id=None,
+ include_client_id=False,
**kwargs):
"""Create and add a JWT assertion to the request body.
@@ -86,7 +86,7 @@ class ServiceApplicationClient(Client):
:param issuer: (iss) The JWT MUST contain an "iss" (issuer) claim that
contains a unique identifier for the entity that issued
- the JWT. For example, ``your-client@provider.com``.
+ the JWT. For example, ``your-client@provider.com``.
:param audience: (aud) A value identifying the authorization server as an
intended audience, e.g.
@@ -105,11 +105,11 @@ class ServiceApplicationClient(Client):
:param scope: The scope of the access request.
- :param include_client_id: `True` to send the `client_id` in the body of
- the upstream request. Default `None`. This is
- required if the client is not authenticating
- with the authorization server as described
- in `Section 3.2.1`_.
+ :param include_client_id: `True` to send the `client_id` in the
+ body of the upstream request. This is required
+ if the client is not authenticating with the
+ authorization server as described in
+ `Section 3.2.1`_. False otherwise (default).
:type include_client_id: Boolean
:param not_before: A unix timestamp after which the JWT may be used.
@@ -129,7 +129,7 @@ class ServiceApplicationClient(Client):
[I-D.ietf-oauth-assertions] specification, to indicate the requested
scope.
- Authentication of the client is optional, as described in
+ Authentication of the client is optional, as described in
`Section 3.2.1`_ of OAuth 2.0 [RFC6749] and consequently, the
"client_id" is only needed when a form of client authentication that
relies on the parameter is used.
@@ -186,5 +186,5 @@ class ServiceApplicationClient(Client):
return prepare_token_request(self.grant_type,
body=body,
assertion=assertion,
- scope=scope,
+ scope=scope,
**kwargs)
diff --git a/oauthlib/oauth2/rfc6749/endpoints/base.py b/oauthlib/oauth2/rfc6749/endpoints/base.py
index c0fc726..e39232f 100644
--- a/oauthlib/oauth2/rfc6749/endpoints/base.py
+++ b/oauthlib/oauth2/rfc6749/endpoints/base.py
@@ -15,6 +15,8 @@ from ..errors import (FatalClientError, OAuth2Error, ServerError,
TemporarilyUnavailableError, InvalidRequestError,
InvalidClientError, UnsupportedTokenTypeError)
+from oauthlib.common import CaseInsensitiveDict, urldecode
+
log = logging.getLogger(__name__)
@@ -23,6 +25,18 @@ class BaseEndpoint(object):
def __init__(self):
self._available = True
self._catch_errors = False
+ self._valid_request_methods = None
+
+ @property
+ def valid_request_methods(self):
+ return self._valid_request_methods
+
+ @valid_request_methods.setter
+ def valid_request_methods(self, valid_request_methods):
+ if valid_request_methods is not None:
+ valid_request_methods = [x.upper() for x in valid_request_methods]
+ self._valid_request_methods = valid_request_methods
+
@property
def available(self):
@@ -30,7 +44,7 @@ class BaseEndpoint(object):
@available.setter
def available(self, available):
- self._available = available
+ self._available = available
@property
def catch_errors(self):
@@ -62,6 +76,21 @@ class BaseEndpoint(object):
request.token_type_hint not in self.supported_token_types):
raise UnsupportedTokenTypeError(request=request)
+ def _raise_on_bad_method(self, request):
+ if self.valid_request_methods is None:
+ raise ValueError('Configure "valid_request_methods" property first')
+ if request.http_method.upper() not in self.valid_request_methods:
+ raise InvalidRequestError(request=request,
+ description=('Unsupported request method %s' % request.http_method.upper()))
+
+ def _raise_on_bad_post_request(self, request):
+ """Raise if invalid POST request received
+ """
+ if request.http_method.upper() == 'POST':
+ query_params = request.uri_query or ""
+ if query_params:
+ raise InvalidRequestError(request=request,
+ description=('URL query parameters are not allowed'))
def catch_errors_and_unavailability(f):
@functools.wraps(f)
diff --git a/oauthlib/oauth2/rfc6749/endpoints/introspect.py b/oauthlib/oauth2/rfc6749/endpoints/introspect.py
index 47022fd..4accbdc 100644
--- a/oauthlib/oauth2/rfc6749/endpoints/introspect.py
+++ b/oauthlib/oauth2/rfc6749/endpoints/introspect.py
@@ -39,6 +39,7 @@ class IntrospectEndpoint(BaseEndpoint):
"""
valid_token_types = ('access_token', 'refresh_token')
+ valid_request_methods = ('POST',)
def __init__(self, request_validator, supported_token_types=None):
BaseEndpoint.__init__(self)
@@ -117,6 +118,8 @@ class IntrospectEndpoint(BaseEndpoint):
.. _`section 1.5`: http://tools.ietf.org/html/rfc6749#section-1.5
.. _`RFC6749`: http://tools.ietf.org/html/rfc6749
"""
+ self._raise_on_bad_method(request)
+ self._raise_on_bad_post_request(request)
self._raise_on_missing_token(request)
self._raise_on_invalid_client(request)
self._raise_on_unsupported_token(request)
diff --git a/oauthlib/oauth2/rfc6749/endpoints/revocation.py b/oauthlib/oauth2/rfc6749/endpoints/revocation.py
index fda3f30..1fabd03 100644
--- a/oauthlib/oauth2/rfc6749/endpoints/revocation.py
+++ b/oauthlib/oauth2/rfc6749/endpoints/revocation.py
@@ -28,6 +28,7 @@ class RevocationEndpoint(BaseEndpoint):
"""
valid_token_types = ('access_token', 'refresh_token')
+ valid_request_methods = ('POST',)
def __init__(self, request_validator, supported_token_types=None,
enable_jsonp=False):
@@ -121,6 +122,8 @@ class RevocationEndpoint(BaseEndpoint):
.. _`Section 4.1.2`: https://tools.ietf.org/html/draft-ietf-oauth-revocation-11#section-4.1.2
.. _`RFC6749`: https://tools.ietf.org/html/rfc6749
"""
+ self._raise_on_bad_method(request)
+ self._raise_on_bad_post_request(request)
self._raise_on_missing_token(request)
self._raise_on_invalid_client(request)
self._raise_on_unsupported_token(request)
diff --git a/oauthlib/oauth2/rfc6749/endpoints/token.py b/oauthlib/oauth2/rfc6749/endpoints/token.py
index 90fb16f..bc87e9b 100644
--- a/oauthlib/oauth2/rfc6749/endpoints/token.py
+++ b/oauthlib/oauth2/rfc6749/endpoints/token.py
@@ -62,6 +62,8 @@ class TokenEndpoint(BaseEndpoint):
.. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B
"""
+ valid_request_methods = ('POST',)
+
def __init__(self, default_grant_type, default_token_type, grant_types):
BaseEndpoint.__init__(self)
self._grant_types = grant_types
@@ -85,13 +87,13 @@ class TokenEndpoint(BaseEndpoint):
return self._default_token_type
@catch_errors_and_unavailability
- def create_token_response(self, uri, http_method='GET', body=None,
+ def create_token_response(self, uri, http_method='POST', 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)
-
+ self.validate_token_request(request)
# '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
@@ -115,3 +117,7 @@ class TokenEndpoint(BaseEndpoint):
request.grant_type, grant_type_handler)
return grant_type_handler.create_token_response(
request, self.default_token_type)
+
+ def validate_token_request(self, request):
+ self._raise_on_bad_method(request)
+ self._raise_on_bad_post_request(request)
diff --git a/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py b/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py
index 5f03d9c..9b84c4c 100644
--- a/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py
+++ b/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py
@@ -405,12 +405,15 @@ class AuthorizationCodeGrant(GrantTypeBase):
raise errors.MissingCodeChallengeError(request=request)
if request.code_challenge is not None:
+ request_info["code_challenge"] = request.code_challenge
+
# OPTIONAL, defaults to "plain" if not present in the request.
if request.code_challenge_method is None:
request.code_challenge_method = "plain"
if request.code_challenge_method not in self._code_challenge_methods:
raise errors.UnsupportedCodeChallengeMethodError(request=request)
+ request_info["code_challenge_method"] = request.code_challenge_method
# OPTIONAL. The scope of the access request as described by Section 3.3
# https://tools.ietf.org/html/rfc6749#section-3.3
diff --git a/oauthlib/oauth2/rfc6749/parameters.py b/oauthlib/oauth2/rfc6749/parameters.py
index 4d0baee..14d4c0d 100644
--- a/oauthlib/oauth2/rfc6749/parameters.py
+++ b/oauthlib/oauth2/rfc6749/parameters.py
@@ -98,7 +98,7 @@ def prepare_token_request(grant_type, body='', include_client_id=True, **kwargs)
"authorization_code" or "client_credentials".
:param body: Existing request body (URL encoded string) to embed parameters
- into. This may contain extra paramters. Default ''.
+ into. This may contain extra parameters. Default ''.
:param include_client_id: `True` (default) to send the `client_id` in the
body of the upstream request. This is required
@@ -142,7 +142,7 @@ def prepare_token_request(grant_type, body='', include_client_id=True, **kwargs)
if 'scope' in kwargs:
kwargs['scope'] = list_to_scope(kwargs['scope'])
- # pull the `client_id` out of the kwargs.
+ # pull the `client_id` out of the kwargs.
client_id = kwargs.pop('client_id', None)
if include_client_id:
if client_id is not None:
@@ -264,12 +264,15 @@ def parse_authorization_code_response(uri, state=None):
query = urlparse.urlparse(uri).query
params = dict(urlparse.parse_qsl(query))
- if not 'code' in params:
- raise MissingCodeError("Missing code parameter in response.")
-
if state and params.get('state', None) != state:
raise MismatchingStateError()
+ if 'error' in params:
+ raise_from_error(params.get('error'), params)
+
+ if not 'code' in params:
+ raise MissingCodeError("Missing code parameter in response.")
+
return params
@@ -419,7 +422,10 @@ def parse_token_response(body, scope=None):
params['scope'] = scope_to_list(params['scope'])
if 'expires_in' in params:
- params['expires_at'] = time.time() + int(params['expires_in'])
+ if params['expires_in'] is None:
+ params.pop('expires_in')
+ else:
+ params['expires_at'] = time.time() + int(params['expires_in'])
params = OAuth2Token(params, old_scope=scope)
validate_token_parameters(params)
diff --git a/oauthlib/oauth2/rfc6749/request_validator.py b/oauthlib/oauth2/rfc6749/request_validator.py
index 193a9e1..86509b6 100644
--- a/oauthlib/oauth2/rfc6749/request_validator.py
+++ b/oauthlib/oauth2/rfc6749/request_validator.py
@@ -266,21 +266,19 @@ class RequestValidator(object):
- the redirect URI used (``request.redirect_uri``)
- a resource owner / user (``request.user``)
- the authorized scopes (``request.scopes``)
- - the client state, if given (``code.get('state')``)
To support PKCE, you MUST associate the code with:
- Code Challenge (``request.code_challenge``) and
- Code Challenge Method (``request.code_challenge_method``)
+ To support OIDC, you MUST associate the code with:
+ - nonce, if present (``code["nonce"]``)
+
The ``code`` argument is actually a dictionary, containing at least a
``code`` key with the actual authorization code:
``{'code': 'sdf345jsdf0934f'}``
- It may also have a ``state`` key containing a nonce for the client, if it
- chose to send one. That value should be saved and used in
- ``.validate_code``.
-
It may also have a ``claims`` parameter which, when present, will be a dict
deserialized from JSON as described at
http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter
@@ -296,32 +294,6 @@ class RequestValidator(object):
"""
raise NotImplementedError('Subclasses must implement this method.')
- def get_authorization_code_scopes(self, client_id, code, redirect_uri, request):
- """ Extracts scopes from saved authorization code.
-
- The scopes returned by this method is used to route token requests
- based on scopes passed to Authorization Code requests.
-
- With that the token endpoint knows when to include OpenIDConnect
- id_token in token response only based on authorization code scopes.
-
- Only code param should be sufficient to retrieve grant code from
- any storage you are using, `client_id` and `redirect_uri` can gave a
- blank value `""` don't forget to check it before using those values
- in a select query if a database is used.
-
- :param client_id: Unicode client identifier.
- :param code: Unicode authorization code grant.
- :param redirect_uri: Unicode absolute URI.
- :param request: OAuthlib request.
- :type request: oauthlib.common.Request
- :return: A list of scopes
-
- Method is used by:
- - Authorization Token Grant Dispatcher
- """
- raise NotImplementedError('Subclasses must implement this method.')
-
def save_token(self, token, request, *args, **kwargs):
"""Persist the token with a token type specific method.
@@ -352,7 +324,7 @@ class RequestValidator(object):
'expires_in': 3600,
'scope': 'string of space separated authorized scopes',
'refresh_token': '23sdf876234', # if issued
- 'state': 'given_by_client', # if supplied by client
+ 'state': 'given_by_client', # if supplied by client (implicit ONLY)
}
Note that while "scope" is a string-separated list of authorized scopes,
@@ -383,104 +355,6 @@ class RequestValidator(object):
"""
raise NotImplementedError('Subclasses must implement this method.')
- def get_jwt_bearer_token(self, token, token_handler, request):
- """Get JWT Bearer token or OpenID Connect ID token
-
- If using OpenID Connect this SHOULD call `oauthlib.oauth2.RequestValidator.get_id_token`
-
- :param token: A Bearer token dict.
- :param token_handler: The token handler (BearerToken class).
- :param request: OAuthlib request.
- :type request: oauthlib.common.Request
- :return: The JWT Bearer token or OpenID Connect ID token (a JWS signed JWT)
-
- Method is used by JWT Bearer and OpenID Connect tokens:
- - JWTToken.create_token
- """
- raise NotImplementedError('Subclasses must implement this method.')
-
- def get_id_token(self, token, token_handler, request):
- """Get OpenID Connect ID token
-
- In the OpenID Connect workflows when an ID Token is requested this method is called.
- Subclasses should implement the construction, signing and optional encryption of the
- ID Token as described in the OpenID Connect spec.
-
- In addition to the standard OAuth2 request properties, the request may also contain
- these OIDC specific properties which are useful to this method:
-
- - nonce, if workflow is implicit or hybrid and it was provided
- - claims, if provided to the original Authorization Code request
-
- The token parameter is a dict which may contain an ``access_token`` entry, in which
- case the resulting ID Token *should* include a calculated ``at_hash`` claim.
-
- Similarly, when the request parameter has a ``code`` property defined, the ID Token
- *should* include a calculated ``c_hash`` claim.
-
- http://openid.net/specs/openid-connect-core-1_0.html (sections `3.1.3.6`_, `3.2.2.10`_, `3.3.2.11`_)
-
- .. _`3.1.3.6`: http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
- .. _`3.2.2.10`: http://openid.net/specs/openid-connect-core-1_0.html#ImplicitIDToken
- .. _`3.3.2.11`: http://openid.net/specs/openid-connect-core-1_0.html#HybridIDToken
-
- :param token: A Bearer token dict.
- :param token_handler: The token handler (BearerToken class)
- :param request: OAuthlib request.
- :type request: oauthlib.common.Request
- :return: The ID Token (a JWS signed JWT)
- """
- # the request.scope should be used by the get_id_token() method to determine which claims to include in the resulting id_token
- raise NotImplementedError('Subclasses must implement this method.')
-
- def validate_jwt_bearer_token(self, token, scopes, request):
- """Ensure the JWT Bearer token or OpenID Connect ID token are valids and authorized access to scopes.
-
- If using OpenID Connect this SHOULD call `oauthlib.oauth2.RequestValidator.get_id_token`
-
- If not using OpenID Connect this can `return None` to avoid 5xx rather 401/3 response.
-
- OpenID connect core 1.0 describe how to validate an id_token:
- - http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
- - http://openid.net/specs/openid-connect-core-1_0.html#ImplicitIDTValidation
- - http://openid.net/specs/openid-connect-core-1_0.html#HybridIDTValidation
- - http://openid.net/specs/openid-connect-core-1_0.html#HybridIDTValidation2
-
- :param token: Unicode Bearer token.
- :param scopes: List of scopes (defined by you).
- :param request: OAuthlib request.
- :type request: oauthlib.common.Request
- :rtype: True or False
-
- Method is indirectly used by all core OpenID connect JWT token issuing grant types:
- - Authorization Code Grant
- - Implicit Grant
- - Hybrid Grant
- """
- raise NotImplementedError('Subclasses must implement this method.')
-
- def validate_id_token(self, token, scopes, request):
- """Ensure the id token is valid and authorized access to scopes.
-
- OpenID connect core 1.0 describe how to validate an id_token:
- - http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
- - http://openid.net/specs/openid-connect-core-1_0.html#ImplicitIDTValidation
- - http://openid.net/specs/openid-connect-core-1_0.html#HybridIDTValidation
- - http://openid.net/specs/openid-connect-core-1_0.html#HybridIDTValidation2
-
- :param token: Unicode Bearer token.
- :param scopes: List of scopes (defined by you).
- :param request: OAuthlib request.
- :type request: oauthlib.common.Request
- :rtype: True or False
-
- Method is indirectly used by all core OpenID connect JWT token issuing grant types:
- - Authorization Code Grant
- - Implicit Grant
- - Hybrid Grant
- """
- raise NotImplementedError('Subclasses must implement this method.')
-
def validate_bearer_token(self, token, scopes, request):
"""Ensure the Bearer token is valid and authorized access to scopes.
@@ -559,7 +433,6 @@ class RequestValidator(object):
with the code in 'save_authorization_code':
- request.user
- - request.state (if given)
- request.scopes
- request.claims (if given)
OBS! The request.user attribute should be set to the resource owner
@@ -674,44 +547,6 @@ class RequestValidator(object):
"""
raise NotImplementedError('Subclasses must implement this method.')
- def validate_silent_authorization(self, request):
- """Ensure the logged in user has authorized silent OpenID authorization.
-
- Silent OpenID authorization allows access tokens and id tokens to be
- granted to clients without any user prompt or interaction.
-
- :param request: OAuthlib request.
- :type request: oauthlib.common.Request
- :rtype: True or False
-
- Method is used by:
- - OpenIDConnectAuthCode
- - OpenIDConnectImplicit
- - OpenIDConnectHybrid
- """
- raise NotImplementedError('Subclasses must implement this method.')
-
- def validate_silent_login(self, request):
- """Ensure session user has authorized silent OpenID login.
-
- If no user is logged in or has not authorized silent login, this
- method should return False.
-
- If the user is logged in but associated with multiple accounts and
- not selected which one to link to the token then this method should
- raise an oauthlib.oauth2.AccountSelectionRequired error.
-
- :param request: OAuthlib request.
- :type request: oauthlib.common.Request
- :rtype: True or False
-
- Method is used by:
- - OpenIDConnectAuthCode
- - OpenIDConnectImplicit
- - OpenIDConnectHybrid
- """
- raise NotImplementedError('Subclasses must implement this method.')
-
def validate_user(self, username, password, client, request, *args, **kwargs):
"""Ensure the username and password is valid.
@@ -732,26 +567,6 @@ class RequestValidator(object):
"""
raise NotImplementedError('Subclasses must implement this method.')
- def validate_user_match(self, id_token_hint, scopes, claims, request):
- """Ensure client supplied user id hint matches session user.
-
- If the sub claim or id_token_hint is supplied then the session
- user must match the given ID.
-
- :param id_token_hint: User identifier string.
- :param scopes: List of OAuth 2 scopes and OpenID claims (strings).
- :param claims: OpenID Connect claims dict.
- :param request: OAuthlib request.
- :type request: oauthlib.common.Request
- :rtype: True or False
-
- Method is used by:
- - OpenIDConnectAuthCode
- - OpenIDConnectImplicit
- - OpenIDConnectHybrid
- """
- raise NotImplementedError('Subclasses must implement this method.')
-
def is_pkce_required(self, client_id, request):
"""Determine if current request requires PKCE. Default, False.
This is called for both "authorization" and "token" requests.
diff --git a/oauthlib/oauth2/rfc6749/tokens.py b/oauthlib/oauth2/rfc6749/tokens.py
index 7973923..3587af4 100644
--- a/oauthlib/oauth2/rfc6749/tokens.py
+++ b/oauthlib/oauth2/rfc6749/tokens.py
@@ -254,7 +254,7 @@ def get_token_from_header(request):
if 'Authorization' in request.headers:
split_header = request.headers.get('Authorization').split()
- if len(split_header) == 2 and split_header[0] == 'Bearer':
+ if len(split_header) == 2 and split_header[0].lower() == 'bearer':
token = split_header[1]
else:
token = request.access_token
@@ -353,7 +353,7 @@ class BearerToken(TokenBase):
:param request: OAuthlib request.
:type request: oauthlib.common.Request
"""
- if request.headers.get('Authorization', '').split(' ')[0] == 'Bearer':
+ if request.headers.get('Authorization', '').split(' ')[0].lower() == 'bearer':
return 9
elif request.access_token is not None:
return 5
diff --git a/oauthlib/openid/__init__.py b/oauthlib/openid/__init__.py
index 03f0fa2..7f1a876 100644
--- a/oauthlib/openid/__init__.py
+++ b/oauthlib/openid/__init__.py
@@ -7,3 +7,4 @@ oauthlib.openid
from __future__ import absolute_import, unicode_literals
from .connect.core.endpoints import Server
+from .connect.core.request_validator import RequestValidator
diff --git a/oauthlib/openid/connect/core/grant_types/authorization_code.py b/oauthlib/openid/connect/core/grant_types/authorization_code.py
index b0b1015..becfcfa 100644
--- a/oauthlib/openid/connect/core/grant_types/authorization_code.py
+++ b/oauthlib/openid/connect/core/grant_types/authorization_code.py
@@ -22,3 +22,23 @@ class AuthorizationCodeGrant(GrantTypeBase):
self.custom_validators.post_auth.append(
self.openid_authorization_validator)
self.register_token_modifier(self.add_id_token)
+
+ def add_id_token(self, token, token_handler, request):
+ """
+ Construct an initial version of id_token, and let the
+ request_validator sign or encrypt it.
+
+ The authorization_code version of this method is used to
+ retrieve the nonce accordingly to the code storage.
+ """
+ # Treat it as normal OAuth 2 auth code request if openid is not present
+ if not request.scopes or 'openid' not in request.scopes:
+ return token
+
+ nonce = self.request_validator.get_authorization_code_nonce(
+ request.client_id,
+ request.code,
+ request.redirect_uri,
+ request
+ )
+ return super(AuthorizationCodeGrant, self).add_id_token(token, token_handler, request, nonce=nonce)
diff --git a/oauthlib/openid/connect/core/grant_types/base.py b/oauthlib/openid/connect/core/grant_types/base.py
index 4f5c944..32a21b6 100644
--- a/oauthlib/openid/connect/core/grant_types/base.py
+++ b/oauthlib/openid/connect/core/grant_types/base.py
@@ -1,7 +1,9 @@
from .exceptions import OIDCNoPrompt
-import datetime
+import base64
+import hashlib
import logging
+import time
from json import loads
from oauthlib.oauth2.rfc6749.errors import ConsentRequired, InvalidRequestError, LoginRequired
@@ -49,7 +51,45 @@ class GrantTypeBase(object):
raise InvalidRequestError(description="Malformed claims parameter",
uri="http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter")
- def add_id_token(self, token, token_handler, request):
+ def id_token_hash(self, value, hashfunc=hashlib.sha256):
+ """
+ Its value is the base64url encoding of the left-most half of the
+ hash of the octets of the ASCII representation of the access_token
+ value, where the hash algorithm used is the hash algorithm used in
+ the alg Header Parameter of the ID Token's JOSE Header.
+
+ For instance, if the alg is RS256, hash the access_token value
+ with SHA-256, then take the left-most 128 bits and
+ base64url-encode them.
+ For instance, if the alg is HS512, hash the code value with
+ SHA-512, then take the left-most 256 bits and base64url-encode
+ them. The c_hash value is a case-sensitive string.
+
+ Example of hash from OIDC specification (bound to a JWS using RS256):
+
+ code:
+ Qcb0Orv1zh30vL1MPRsbm-diHiMwcLyZvn1arpZv-Jxf_11jnpEX3Tgfvk
+
+ c_hash:
+ LDktKdoQak3Pk0cnXxCltA
+ """
+ digest = hashfunc(value.encode()).digest()
+ left_most = len(digest) // 2
+ return base64.urlsafe_b64encode(digest[:left_most]).decode().rstrip("=")
+
+ def add_id_token(self, token, token_handler, request, nonce=None):
+ """
+ Construct an initial version of id_token, and let the
+ request_validator sign or encrypt it.
+
+ The initial version can contain the fields below, accordingly
+ to the spec:
+ - aud
+ - iat
+ - nonce
+ - at_hash
+ - c_hash
+ """
# Treat it as normal OAuth 2 auth code request if openid is not present
if not request.scopes or 'openid' not in request.scopes:
return token
@@ -58,13 +98,54 @@ class GrantTypeBase(object):
if request.response_type and 'id_token' not in request.response_type:
return token
- if request.max_age:
- d = datetime.datetime.utcnow()
- token['auth_time'] = d.isoformat("T") + "Z"
-
- # TODO: acr claims (probably better handled by server code using oauthlib in get_id_token)
+ # Implementation mint its own id_token without help.
+ id_token = self.request_validator.get_id_token(token, token_handler, request)
+ if id_token:
+ token['id_token'] = id_token
+ return token
- token['id_token'] = self.request_validator.get_id_token(token, token_handler, request)
+ # Fallback for asking some help from oauthlib framework.
+ # Start with technicals fields bound to the specification.
+ id_token = {}
+ id_token['aud'] = request.client_id
+ id_token['iat'] = int(time.time())
+
+ # nonce is REQUIRED when response_type value is:
+ # - id_token token (Implicit)
+ # - id_token (Implicit)
+ # - code id_token (Hybrid)
+ # - code id_token token (Hybrid)
+ #
+ # nonce is OPTIONAL when response_type value is:
+ # - code (Authorization Code)
+ # - code token (Hybrid)
+ if nonce is not None:
+ id_token["nonce"] = nonce
+
+ # at_hash is REQUIRED when response_type value is:
+ # - id_token token (Implicit)
+ # - code id_token token (Hybrid)
+ #
+ # at_hash is OPTIONAL when:
+ # - code (Authorization code)
+ # - code id_token (Hybrid)
+ # - code token (Hybrid)
+ #
+ # at_hash MAY NOT be used when:
+ # - id_token (Implicit)
+ if "access_token" in token:
+ id_token["at_hash"] = self.id_token_hash(token["access_token"])
+
+ # c_hash is REQUIRED when response_type value is:
+ # - code id_token (Hybrid)
+ # - code id_token token (Hybrid)
+ #
+ # c_hash is OPTIONAL for others.
+ if "code" in token:
+ id_token["c_hash"] = self.id_token_hash(token["code"])
+
+ # Call request_validator to complete/sign/encrypt id_token
+ token['id_token'] = self.request_validator.finalize_id_token(id_token, token, token_handler, request)
return token
diff --git a/oauthlib/openid/connect/core/grant_types/implicit.py b/oauthlib/openid/connect/core/grant_types/implicit.py
index d3797b2..c2dbc27 100644
--- a/oauthlib/openid/connect/core/grant_types/implicit.py
+++ b/oauthlib/openid/connect/core/grant_types/implicit.py
@@ -27,9 +27,9 @@ class ImplicitGrant(GrantTypeBase):
self.register_token_modifier(self.add_id_token)
def add_id_token(self, token, token_handler, request):
- if 'state' not in token:
+ if 'state' not in token and request.state:
token['state'] = request.state
- return super(ImplicitGrant, self).add_id_token(token, token_handler, request)
+ return super(ImplicitGrant, self).add_id_token(token, token_handler, request, nonce=request.nonce)
def openid_authorization_validator(self, request):
"""Additional validation when following the implicit flow.
diff --git a/oauthlib/openid/connect/core/request_validator.py b/oauthlib/openid/connect/core/request_validator.py
index 1587754..d96c9ef 100644
--- a/oauthlib/openid/connect/core/request_validator.py
+++ b/oauthlib/openid/connect/core/request_validator.py
@@ -24,7 +24,7 @@ class RequestValidator(OAuth2RequestValidator):
id_token in token response only based on authorization code scopes.
Only code param should be sufficient to retrieve grant code from
- any storage you are using, `client_id` and `redirect_uri` can gave a
+ any storage you are using, `client_id` and `redirect_uri` can have a
blank value `""` don't forget to check it before using those values
in a select query if a database is used.
@@ -38,6 +38,30 @@ class RequestValidator(OAuth2RequestValidator):
"""
raise NotImplementedError('Subclasses must implement this method.')
+ def get_authorization_code_nonce(self, client_id, code, redirect_uri, request):
+ """ Extracts nonce from saved authorization code.
+
+ If present in the Authentication Request, Authorization
+ Servers MUST include a nonce Claim in the ID Token with the
+ Claim Value being the nonce value sent in the Authentication
+ Request. Authorization Servers SHOULD perform no other
+ processing on nonce values used. The nonce value is a
+ case-sensitive string.
+
+ Only code param should be sufficient to retrieve grant code from
+ any storage you are using. However, `client_id` and `redirect_uri`
+ have been validated and can be used also.
+
+ :param client_id: Unicode client identifier
+ :param code: Unicode authorization code grant
+ :param redirect_uri: Unicode absolute URI
+ :return: Unicode nonce
+
+ Method is used by:
+ - Authorization Token Grant Dispatcher
+ """
+ raise NotImplementedError('Subclasses must implement this method.')
+
def get_jwt_bearer_token(self, token, token_handler, request):
"""Get JWT Bearer token or OpenID Connect ID token
@@ -57,6 +81,12 @@ class RequestValidator(OAuth2RequestValidator):
def get_id_token(self, token, token_handler, request):
"""Get OpenID Connect ID token
+ This method is OPTIONAL and is NOT RECOMMENDED.
+ `finalize_id_token` SHOULD be implemented instead. However, if you
+ want a full control over the minting of the `id_token`, you
+ MAY want to override `get_id_token` instead of using
+ `finalize_id_token`.
+
In the OpenID Connect workflows when an ID Token is requested this method is called.
Subclasses should implement the construction, signing and optional encryption of the
ID Token as described in the OpenID Connect spec.
@@ -85,7 +115,49 @@ class RequestValidator(OAuth2RequestValidator):
:type request: oauthlib.common.Request
:return: The ID Token (a JWS signed JWT)
"""
- # the request.scope should be used by the get_id_token() method to determine which claims to include in the resulting id_token
+ return None
+
+ def finalize_id_token(self, id_token, token, token_handler, request):
+ """Finalize OpenID Connect ID token & Sign or Encrypt.
+
+ In the OpenID Connect workflows when an ID Token is requested
+ this method is called. Subclasses should implement the
+ construction, signing and optional encryption of the ID Token
+ as described in the OpenID Connect spec.
+
+ The `id_token` parameter is a dict containing a couple of OIDC
+ technical fields related to the specification. Prepopulated
+ attributes are:
+
+ - `aud`, equals to `request.client_id`.
+ - `iat`, equals to current time.
+ - `nonce`, if present, is equals to the `nonce` from the
+ authorization request.
+ - `at_hash`, hash of `access_token`, if relevant.
+ - `c_hash`, hash of `code`, if relevant.
+
+ This method MUST provide required fields as below:
+
+ - `iss`, REQUIRED. Issuer Identifier for the Issuer of the response.
+ - `sub`, REQUIRED. Subject Identifier
+ - `exp`, REQUIRED. Expiration time on or after which the ID
+ Token MUST NOT be accepted by the RP when performing
+ authentication with the OP.
+
+ Additionals claims must be added, note that `request.scope`
+ should be used to determine the list of claims.
+
+ More information can be found at `OpenID Connect Core#Claims`_
+
+ .. _`OpenID Connect Core#Claims`: https://openid.net/specs/openid-connect-core-1_0.html#Claims
+
+ :param id_token: A dict containing technical fields of id_token
+ :param token: A Bearer token dict
+ :param token_handler: the token handler (BearerToken class)
+ :param request: OAuthlib request.
+ :type request: oauthlib.common.Request
+ :return: The ID Token (a JWS signed JWT or JWE encrypted JWT)
+ """
raise NotImplementedError('Subclasses must implement this method.')
def validate_jwt_bearer_token(self, token, scopes, request):