From 73032fe688a899f80d2a65479c72fec450ec51a1 Mon Sep 17 00:00:00 2001 From: Jonathan Huot Date: Thu, 28 Feb 2019 10:06:37 +0100 Subject: [PATCH 01/11] Removed duplicated OIDC members in OAuth2.RequestValidator --- docs/oauth2/oidc/validator.rst | 6 +- oauthlib/oauth2/rfc6749/request_validator.py | 182 ------------------- oauthlib/openid/__init__.py | 1 + 3 files changed, 5 insertions(+), 184 deletions(-) diff --git a/docs/oauth2/oidc/validator.rst b/docs/oauth2/oidc/validator.rst index a03adfe4..7a6f5744 100644 --- a/docs/oauth2/oidc/validator.rst +++ b/docs/oauth2/oidc/validator.rst @@ -10,12 +10,14 @@ upgrade it by replacing one line of code: .. code-block:: python from oauthlib.oauth2 import Server + from oauthlib.oauth2 import RequestValidator Into .. code-block:: python from oauthlib.openid import Server + from oauthlib.openid import RequestValidator Then, you have to implement the new RequestValidator methods as shown below. @@ -24,5 +26,5 @@ RequestValidator Extension A couple of methods must be implemented in your validator subclass if you wish to support OpenID Connect: -.. autoclass:: oauthlib.oauth2.RequestValidator - :members: validate_silent_authorization, validate_silent_login, validate_user_match, get_id_token, get_authorization_code_scopes, validate_jwt_bearer_token +.. autoclass:: oauthlib.openid.RequestValidator + :members: diff --git a/oauthlib/oauth2/rfc6749/request_validator.py b/oauthlib/oauth2/rfc6749/request_validator.py index 5ff30d80..d6ec2abf 100644 --- a/oauthlib/oauth2/rfc6749/request_validator.py +++ b/oauthlib/oauth2/rfc6749/request_validator.py @@ -291,32 +291,6 @@ def save_authorization_code(self, client_id, code, request, *args, **kwargs): """ 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. @@ -378,104 +352,6 @@ def save_bearer_token(self, token, request, *args, **kwargs): """ 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. @@ -668,44 +544,6 @@ def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs): """ 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. @@ -726,26 +564,6 @@ def validate_user(self, username, password, client, request, *args, **kwargs): """ 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/openid/__init__.py b/oauthlib/openid/__init__.py index 03f0fa2e..7f1a8767 100644 --- a/oauthlib/openid/__init__.py +++ b/oauthlib/openid/__init__.py @@ -7,3 +7,4 @@ from __future__ import absolute_import, unicode_literals from .connect.core.endpoints import Server +from .connect.core.request_validator import RequestValidator From 7c570c763725fdaa40778d6cd6689b09b3971f50 Mon Sep 17 00:00:00 2001 From: Jonathan Huot Date: Thu, 28 Feb 2019 10:16:27 +0100 Subject: [PATCH 02/11] Add technicals fields of `id_token` in oauthlib OIDC support A new RequestValidator `fill_id_token` has been introduced to replace `get_id_token`. It aims to have the bare minimum amount of fields to complete a full OIDC id_token support. `get_id_token` is still valid but optional, and if it is implemented, `fill_id_token` will not be called. The current `fill_id_token` came with full support of `aud`, `iat`, `nonce`, `at_hash` and `c_hash`. More could come in the future e.g. `auth_time`, ... --- docs/oauth2/oidc/id_tokens.rst | 17 +++-- oauthlib/oauth2/rfc6749/request_validator.py | 3 + .../core/grant_types/authorization_code.py | 20 +++++ .../openid/connect/core/grant_types/base.py | 64 ++++++++++++++-- .../connect/core/grant_types/implicit.py | 4 +- .../openid/connect/core/request_validator.py | 75 ++++++++++++++++++- 6 files changed, 166 insertions(+), 17 deletions(-) diff --git a/docs/oauth2/oidc/id_tokens.rst b/docs/oauth2/oidc/id_tokens.rst index 999cfa7e..2387c01f 100644 --- a/docs/oauth2/oidc/id_tokens.rst +++ b/docs/oauth2/oidc/id_tokens.rst @@ -1,9 +1,9 @@ ID Tokens ========= -The creation of `ID Tokens`_ is ultimately done not by OAuthLib but by your ``RequestValidator`` subclass. This is because their +The creation of `ID Tokens`_ is ultimately not done by OAuthLib but by your ``RequestValidator`` subclass. This is because their content is dependent on your implementation of users, their attributes, any claims you may wish to support, as well as the -details of how you model the notion of a Client Application. As such OAuthLib simply calls your validator's ``get_id_token`` +details of how you model the notion of a Client Application. As such OAuthLib simply calls your validator's ``fill_id_token`` method at the appropriate times during the authorization flow, depending on the grant type requested (Authorization Code, Implicit, Hybrid, etc.). @@ -12,7 +12,7 @@ See examples below. .. _`ID Tokens`: http://openid.net/specs/openid-connect-core-1_0.html#IDToken .. autoclass:: oauthlib.oauth2.RequestValidator - :members: get_id_token + :members: fill_id_token JWT/JWS example with pyjwt library @@ -38,12 +38,13 @@ You can switch to jwcrypto library if you want to return JWE instead. super().__init__(self, **kwargs) - def get_id_token(self, token, token_handler, request): + def fill_id_token(self, id_token, token, token_handler, request): import jwt - data = {"nonce": request.nonce} if request.nonce is not None else {} - + id_token["iss"] = "https://my.cool.app.com" + id_token["sub"] = request.user.id + id_token["exp"] = id_token["iat"] + 3600 * 24 # keep it valid for 24hours for claim_key in request.claims: - data[claim_key] = request.userattributes[claim_key] # this must be set in another callback + id_token[claim_key] = request.userattributes[claim_key] # this must be set in another callback - return jwt.encode(data, self.private_pem, 'RS256') + return jwt.encode(id_token, self.private_pem, 'RS256') diff --git a/oauthlib/oauth2/rfc6749/request_validator.py b/oauthlib/oauth2/rfc6749/request_validator.py index d6ec2abf..86509b62 100644 --- a/oauthlib/oauth2/rfc6749/request_validator.py +++ b/oauthlib/oauth2/rfc6749/request_validator.py @@ -271,6 +271,9 @@ def save_authorization_code(self, client_id, code, request, *args, **kwargs): - 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: diff --git a/oauthlib/openid/connect/core/grant_types/authorization_code.py b/oauthlib/openid/connect/core/grant_types/authorization_code.py index b0b10155..becfcfab 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 @@ def __init__(self, request_validator=None, **kwargs): 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 4f5c9445..19a7f4f3 100644 --- a/oauthlib/openid/connect/core/grant_types/base.py +++ b/oauthlib/openid/connect/core/grant_types/base.py @@ -1,6 +1,8 @@ from .exceptions import OIDCNoPrompt +import base64 import datetime +import hashlib import logging from json import loads @@ -49,7 +51,45 @@ def _inflate_claims(self, request): 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 hash_id_token(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 = int(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,25 @@ def add_id_token(self, token, token_handler, request): 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" + # 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 + + # 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(datetime.datetime.now().timestamp()) + if nonce is not None: + id_token["nonce"] = nonce - # TODO: acr claims (probably better handled by server code using oauthlib in get_id_token) + if "access_token" in token: + id_token["at_hash"] = self.hash_id_token(token["access_token"]) - token['id_token'] = self.request_validator.get_id_token(token, token_handler, request) + # Call request_validator to complete/sign/encrypt id_token + token['id_token'] = self.request_validator.fill_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 d3797b28..c2dbc278 100644 --- a/oauthlib/openid/connect/core/grant_types/implicit.py +++ b/oauthlib/openid/connect/core/grant_types/implicit.py @@ -27,9 +27,9 @@ def __init__(self, request_validator=None, **kwargs): 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 15877541..f8aeed87 100644 --- a/oauthlib/openid/connect/core/request_validator.py +++ b/oauthlib/openid/connect/core/request_validator.py @@ -38,6 +38,31 @@ def get_authorization_code_scopes(self, client_id, code, redirect_uri, request): """ 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, `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 + :return: A list of scope + + 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 +82,12 @@ def get_jwt_bearer_token(self, token, token_handler, request): def get_id_token(self, token, token_handler, request): """Get OpenID Connect ID token + This method is OPTIONAL and is NOT RECOMMENDED. + `fill_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 + `fill_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 +116,49 @@ def get_id_token(self, token, token_handler, 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 + return None + + def fill_id_token(self, id_token, token, token_handler, request): + """Fill 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): From 62152d48e83cbc0eac3a2991b3b7fed2e84f7ec7 Mon Sep 17 00:00:00 2001 From: Jonathan Huot Date: Thu, 28 Feb 2019 15:03:34 +0100 Subject: [PATCH 03/11] Add c_hash. Add summary about when nonce/hashes are added to id_token --- .../openid/connect/core/grant_types/base.py | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/oauthlib/openid/connect/core/grant_types/base.py b/oauthlib/openid/connect/core/grant_types/base.py index 19a7f4f3..f925c646 100644 --- a/oauthlib/openid/connect/core/grant_types/base.py +++ b/oauthlib/openid/connect/core/grant_types/base.py @@ -109,12 +109,41 @@ def add_id_token(self, token, token_handler, request, nonce=None): id_token = {} id_token['aud'] = request.client_id id_token['iat'] = int(datetime.datetime.now().timestamp()) + + # 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.hash_id_token(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.hash_id_token(token["code"]) + # Call request_validator to complete/sign/encrypt id_token token['id_token'] = self.request_validator.fill_id_token(id_token, token, token_handler, request) From 84cd5a4265c2670af5a4b7ad2143c47fa68582c1 Mon Sep 17 00:00:00 2001 From: Jonathan Huot Date: Mon, 25 Feb 2019 15:36:13 +0100 Subject: [PATCH 04/11] Change to 3.0.2-dev as long as master is in "dev" --- CHANGELOG.rst | 2 +- oauthlib/__init__.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index f49fb928..ade6243b 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,7 +1,7 @@ Changelog ========= -TBD +3.0.2 (TBD) ------------------ * #650 Fixed space encoding in base string URI used in the signature base string. * #652: Fixed OIDC /token response which wrongly returned "&state=None" diff --git a/oauthlib/__init__.py b/oauthlib/__init__.py index b23102c3..8eb82a65 100644 --- a/oauthlib/__init__.py +++ b/oauthlib/__init__.py @@ -12,6 +12,6 @@ from logging import NullHandler __author__ = 'The OAuthlib Community' -__version__ = '3.0.1' +__version__ = '3.0.2-dev' logging.getLogger('oauthlib').addHandler(NullHandler()) From 53d3d335879f205ae705d93420f34984073cd5a1 Mon Sep 17 00:00:00 2001 From: Jonathan Huot Date: Tue, 26 Mar 2019 14:50:41 +0100 Subject: [PATCH 05/11] Renamed fill into finalize to add clarity --- docs/oauth2/oidc/id_tokens.rst | 6 +++--- oauthlib/openid/connect/core/grant_types/base.py | 2 +- oauthlib/openid/connect/core/request_validator.py | 8 ++++---- tests/openid/connect/core/test_request_validator.py | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/oauth2/oidc/id_tokens.rst b/docs/oauth2/oidc/id_tokens.rst index 2387c01f..a1bf7cf3 100644 --- a/docs/oauth2/oidc/id_tokens.rst +++ b/docs/oauth2/oidc/id_tokens.rst @@ -3,7 +3,7 @@ ID Tokens The creation of `ID Tokens`_ is ultimately not done by OAuthLib but by your ``RequestValidator`` subclass. This is because their content is dependent on your implementation of users, their attributes, any claims you may wish to support, as well as the -details of how you model the notion of a Client Application. As such OAuthLib simply calls your validator's ``fill_id_token`` +details of how you model the notion of a Client Application. As such OAuthLib simply calls your validator's ``finalize_id_token`` method at the appropriate times during the authorization flow, depending on the grant type requested (Authorization Code, Implicit, Hybrid, etc.). @@ -12,7 +12,7 @@ See examples below. .. _`ID Tokens`: http://openid.net/specs/openid-connect-core-1_0.html#IDToken .. autoclass:: oauthlib.oauth2.RequestValidator - :members: fill_id_token + :members: finalize_id_token JWT/JWS example with pyjwt library @@ -38,7 +38,7 @@ You can switch to jwcrypto library if you want to return JWE instead. super().__init__(self, **kwargs) - def fill_id_token(self, id_token, token, token_handler, request): + def finalize_id_token(self, id_token, token, token_handler, request): import jwt id_token["iss"] = "https://my.cool.app.com" diff --git a/oauthlib/openid/connect/core/grant_types/base.py b/oauthlib/openid/connect/core/grant_types/base.py index f925c646..31ff82ef 100644 --- a/oauthlib/openid/connect/core/grant_types/base.py +++ b/oauthlib/openid/connect/core/grant_types/base.py @@ -145,7 +145,7 @@ def add_id_token(self, token, token_handler, request, nonce=None): id_token["c_hash"] = self.hash_id_token(token["code"]) # Call request_validator to complete/sign/encrypt id_token - token['id_token'] = self.request_validator.fill_id_token(id_token, token, token_handler, request) + token['id_token'] = self.request_validator.finalize_id_token(id_token, token, token_handler, request) return token diff --git a/oauthlib/openid/connect/core/request_validator.py b/oauthlib/openid/connect/core/request_validator.py index f8aeed87..7ce7e170 100644 --- a/oauthlib/openid/connect/core/request_validator.py +++ b/oauthlib/openid/connect/core/request_validator.py @@ -83,10 +83,10 @@ def get_id_token(self, token, token_handler, request): """Get OpenID Connect ID token This method is OPTIONAL and is NOT RECOMMENDED. - `fill_id_token` SHOULD be implemented instead. However, if you + `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 - `fill_id_token`. + `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 @@ -118,8 +118,8 @@ def get_id_token(self, token, token_handler, request): """ return None - def fill_id_token(self, id_token, token, token_handler, request): - """Fill OpenID Connect ID token & Sign or Encrypt. + 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 diff --git a/tests/openid/connect/core/test_request_validator.py b/tests/openid/connect/core/test_request_validator.py index e20e88f0..ebe0aeb7 100644 --- a/tests/openid/connect/core/test_request_validator.py +++ b/tests/openid/connect/core/test_request_validator.py @@ -22,8 +22,8 @@ def test_method_contracts(self): ) self.assertRaises( NotImplementedError, - v.get_id_token, - 'token', 'token_handler', 'request' + v.finalize_id_token, + 'id_token', 'token', 'token_handler', 'request' ) self.assertRaises( NotImplementedError, From 4877b4837a9355bc74c9f3d59343d689be4c86fa Mon Sep 17 00:00:00 2001 From: Jonathan Huot Date: Tue, 26 Mar 2019 14:50:55 +0100 Subject: [PATCH 06/11] Use native operator instead type conversion --- oauthlib/openid/connect/core/grant_types/base.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/oauthlib/openid/connect/core/grant_types/base.py b/oauthlib/openid/connect/core/grant_types/base.py index 31ff82ef..c5d91e72 100644 --- a/oauthlib/openid/connect/core/grant_types/base.py +++ b/oauthlib/openid/connect/core/grant_types/base.py @@ -74,7 +74,7 @@ def hash_id_token(self, value, hashfunc=hashlib.sha256): LDktKdoQak3Pk0cnXxCltA """ digest = hashfunc(value.encode()).digest() - left_most = int(len(digest) / 2) + 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): From 09538c93d562f6230f3d257b6782d58eeb0a7c3e Mon Sep 17 00:00:00 2001 From: Jonathan Huot Date: Tue, 26 Mar 2019 16:15:13 +0100 Subject: [PATCH 07/11] Add unittests for OIDC GrantTypeBase. Rename hash_id_token into id_token_hash --- .../openid/connect/core/grant_types/base.py | 6 +- .../connect/core/grant_types/test_base.py | 104 ++++++++++++++++++ 2 files changed, 107 insertions(+), 3 deletions(-) create mode 100644 tests/openid/connect/core/grant_types/test_base.py diff --git a/oauthlib/openid/connect/core/grant_types/base.py b/oauthlib/openid/connect/core/grant_types/base.py index c5d91e72..6272ea27 100644 --- a/oauthlib/openid/connect/core/grant_types/base.py +++ b/oauthlib/openid/connect/core/grant_types/base.py @@ -51,7 +51,7 @@ def _inflate_claims(self, request): raise InvalidRequestError(description="Malformed claims parameter", uri="http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter") - def hash_id_token(self, value, hashfunc=hashlib.sha256): + 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 @@ -134,7 +134,7 @@ def add_id_token(self, token, token_handler, request, nonce=None): # at_hash MAY NOT be used when: # - id_token (Implicit) if "access_token" in token: - id_token["at_hash"] = self.hash_id_token(token["access_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) @@ -142,7 +142,7 @@ def add_id_token(self, token, token_handler, request, nonce=None): # # c_hash is OPTIONAL for others. if "code" in token: - id_token["c_hash"] = self.hash_id_token(token["code"]) + 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) diff --git a/tests/openid/connect/core/grant_types/test_base.py b/tests/openid/connect/core/grant_types/test_base.py new file mode 100644 index 00000000..319904b8 --- /dev/null +++ b/tests/openid/connect/core/grant_types/test_base.py @@ -0,0 +1,104 @@ +# -*- coding: utf-8 -*- +import datetime +import mock + +from oauthlib.common import Request +from oauthlib.openid.connect.core.grant_types.base import GrantTypeBase + +from tests.unittest import TestCase + + +class GrantBase(GrantTypeBase): + """Class to test GrantTypeBase""" + def __init__(self, request_validator=None, **kwargs): + self.request_validator = request_validator + + +class IDTokenTest(TestCase): + + def setUp(self): + self.request = Request('http://a.b/path') + self.request.scopes = ('hello', 'openid') + self.request.expires_in = 1800 + self.request.client_id = 'abcdef' + self.request.code = '1234' + self.request.response_type = 'id_token' + self.request.grant_type = 'authorization_code' + self.request.redirect_uri = 'https://a.b/cb' + self.request.state = 'abc' + self.request.nonce = None + + self.mock_validator = mock.MagicMock() + self.mock_validator.get_id_token.return_value = None + self.mock_validator.finalize_id_token.return_value = "eyJ.body.signature" + self.token = {} + + self.grant = GrantBase(request_validator=self.mock_validator) + + self.url_query = 'https://a.b/cb?code=abc&state=abc' + self.url_fragment = 'https://a.b/cb#code=abc&state=abc' + + def test_id_token_hash(self): + self.assertEqual(self.grant.id_token_hash( + "Qcb0Orv1zh30vL1MPRsbm-diHiMwcLyZvn1arpZv-Jxf_11jnpEX3Tgfvk", + ), "LDktKdoQak3Pk0cnXxCltA", "hash differs from RFC") + + def test_get_id_token_no_openid(self): + self.request.scopes = ('hello') + token = self.grant.add_id_token(self.token, "token_handler_mock", self.request) + self.assertNotIn("id_token", token) + + self.request.scopes = None + token = self.grant.add_id_token(self.token, "token_handler_mock", self.request) + self.assertNotIn("id_token", token) + + self.request.scopes = () + token = self.grant.add_id_token(self.token, "token_handler_mock", self.request) + self.assertNotIn("id_token", token) + + def test_get_id_token(self): + self.mock_validator.get_id_token.return_value = "toto" + token = self.grant.add_id_token(self.token, "token_handler_mock", self.request) + self.assertIn("id_token", token) + self.assertEqual(token["id_token"], "toto") + + def test_finalize_id_token(self): + token = self.grant.add_id_token(self.token, "token_handler_mock", self.request) + self.assertIn("id_token", token) + self.assertEqual(token["id_token"], "eyJ.body.signature") + id_token = self.mock_validator.finalize_id_token.call_args[0][0] + self.assertEqual(id_token['aud'], 'abcdef') + self.assertGreaterEqual(id_token['iat'], int(datetime.datetime.now().timestamp())) + + def test_finalize_id_token_with_nonce(self): + token = self.grant.add_id_token(self.token, "token_handler_mock", self.request, "my_nonce") + self.assertIn("id_token", token) + self.assertEqual(token["id_token"], "eyJ.body.signature") + id_token = self.mock_validator.finalize_id_token.call_args[0][0] + self.assertEqual(id_token['nonce'], 'my_nonce') + + def test_finalize_id_token_with_at_hash(self): + self.token["access_token"] = "Qcb0Orv1zh30vL1MPRsbm-diHiMwcLyZvn1arpZv-Jxf_11jnpEX3Tgfvk" + token = self.grant.add_id_token(self.token, "token_handler_mock", self.request) + self.assertIn("id_token", token) + self.assertEqual(token["id_token"], "eyJ.body.signature") + id_token = self.mock_validator.finalize_id_token.call_args[0][0] + self.assertEqual(id_token['at_hash'], 'LDktKdoQak3Pk0cnXxCltA') + + def test_finalize_id_token_with_c_hash(self): + self.token["code"] = "Qcb0Orv1zh30vL1MPRsbm-diHiMwcLyZvn1arpZv-Jxf_11jnpEX3Tgfvk" + token = self.grant.add_id_token(self.token, "token_handler_mock", self.request) + self.assertIn("id_token", token) + self.assertEqual(token["id_token"], "eyJ.body.signature") + id_token = self.mock_validator.finalize_id_token.call_args[0][0] + self.assertEqual(id_token['c_hash'], 'LDktKdoQak3Pk0cnXxCltA') + + def test_finalize_id_token_with_c_and_at_hash(self): + self.token["code"] = "Qcb0Orv1zh30vL1MPRsbm-diHiMwcLyZvn1arpZv-Jxf_11jnpEX3Tgfvk" + self.token["access_token"] = "Qcb0Orv1zh30vL1MPRsbm-diHiMwcLyZvn1arpZv-Jxf_11jnpEX3Tgfvk" + token = self.grant.add_id_token(self.token, "token_handler_mock", self.request) + self.assertIn("id_token", token) + self.assertEqual(token["id_token"], "eyJ.body.signature") + id_token = self.mock_validator.finalize_id_token.call_args[0][0] + self.assertEqual(id_token['at_hash'], 'LDktKdoQak3Pk0cnXxCltA') + self.assertEqual(id_token['c_hash'], 'LDktKdoQak3Pk0cnXxCltA') From ed8c4f253def93a0d4d78a6ead1a63091f8e4c26 Mon Sep 17 00:00:00 2001 From: Jonathan Huot Date: Tue, 26 Mar 2019 16:32:51 +0100 Subject: [PATCH 08/11] Python2.7 compatible --- oauthlib/openid/connect/core/grant_types/base.py | 4 ++-- tests/openid/connect/core/grant_types/test_base.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/oauthlib/openid/connect/core/grant_types/base.py b/oauthlib/openid/connect/core/grant_types/base.py index 6272ea27..32a21b62 100644 --- a/oauthlib/openid/connect/core/grant_types/base.py +++ b/oauthlib/openid/connect/core/grant_types/base.py @@ -1,9 +1,9 @@ from .exceptions import OIDCNoPrompt import base64 -import datetime import hashlib import logging +import time from json import loads from oauthlib.oauth2.rfc6749.errors import ConsentRequired, InvalidRequestError, LoginRequired @@ -108,7 +108,7 @@ def add_id_token(self, token, token_handler, request, nonce=None): # Start with technicals fields bound to the specification. id_token = {} id_token['aud'] = request.client_id - id_token['iat'] = int(datetime.datetime.now().timestamp()) + id_token['iat'] = int(time.time()) # nonce is REQUIRED when response_type value is: # - id_token token (Implicit) diff --git a/tests/openid/connect/core/grant_types/test_base.py b/tests/openid/connect/core/grant_types/test_base.py index 319904b8..76e017f9 100644 --- a/tests/openid/connect/core/grant_types/test_base.py +++ b/tests/openid/connect/core/grant_types/test_base.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -import datetime import mock +import time from oauthlib.common import Request from oauthlib.openid.connect.core.grant_types.base import GrantTypeBase @@ -68,7 +68,7 @@ def test_finalize_id_token(self): self.assertEqual(token["id_token"], "eyJ.body.signature") id_token = self.mock_validator.finalize_id_token.call_args[0][0] self.assertEqual(id_token['aud'], 'abcdef') - self.assertGreaterEqual(id_token['iat'], int(datetime.datetime.now().timestamp())) + self.assertGreaterEqual(id_token['iat'], int(time.time())) def test_finalize_id_token_with_nonce(self): token = self.grant.add_id_token(self.token, "token_handler_mock", self.request, "my_nonce") From 5405ca4cae31146ce2d2c6860b0c46dbbbe879c9 Mon Sep 17 00:00:00 2001 From: Jonathan Huot Date: Mon, 29 Apr 2019 10:11:24 +0200 Subject: [PATCH 09/11] Fix docstring about return value --- oauthlib/openid/connect/core/request_validator.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/oauthlib/openid/connect/core/request_validator.py b/oauthlib/openid/connect/core/request_validator.py index 7ce7e170..eebab550 100644 --- a/oauthlib/openid/connect/core/request_validator.py +++ b/oauthlib/openid/connect/core/request_validator.py @@ -56,7 +56,7 @@ def get_authorization_code_nonce(self, client_id, code, redirect_uri, request): :param client_id: Unicode client identifier :param code: Unicode authorization code grant :param redirect_uri: Unicode absolute URI - :return: A list of scope + :return: Unicode nonce Method is used by: - Authorization Token Grant Dispatcher From 247c89e13bdd017b99f22b154e521084df53d2f0 Mon Sep 17 00:00:00 2001 From: Jonathan Huot Date: Mon, 29 Apr 2019 10:12:10 +0200 Subject: [PATCH 10/11] Fix typo gave/have --- oauthlib/openid/connect/core/request_validator.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/oauthlib/openid/connect/core/request_validator.py b/oauthlib/openid/connect/core/request_validator.py index eebab550..344fd7d7 100644 --- a/oauthlib/openid/connect/core/request_validator.py +++ b/oauthlib/openid/connect/core/request_validator.py @@ -24,7 +24,7 @@ def get_authorization_code_scopes(self, client_id, code, redirect_uri, request): 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. @@ -49,7 +49,7 @@ def get_authorization_code_nonce(self, client_id, code, redirect_uri, request): case-sensitive string. 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. From d4d3f1088dc943a83641c9e86b7a09d98f6adce8 Mon Sep 17 00:00:00 2001 From: Jonathan Huot Date: Mon, 29 Apr 2019 10:20:39 +0200 Subject: [PATCH 11/11] Removed wrong assumption from copy/paste of get_autho.._scopes. This function should always have a good client_id and redirect_uri, because it is called after validate_token_request() --- oauthlib/openid/connect/core/request_validator.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/oauthlib/openid/connect/core/request_validator.py b/oauthlib/openid/connect/core/request_validator.py index 344fd7d7..d96c9efd 100644 --- a/oauthlib/openid/connect/core/request_validator.py +++ b/oauthlib/openid/connect/core/request_validator.py @@ -49,9 +49,8 @@ def get_authorization_code_nonce(self, client_id, code, redirect_uri, request): case-sensitive string. Only code param should be sufficient to retrieve grant code from - 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. + 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 pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy