Skip to content

Add max_age support #389

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Sep 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions msal/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,7 @@ def initiate_auth_code_flow(
login_hint=None, # type: Optional[str]
domain_hint=None, # type: Optional[str]
claims_challenge=None,
max_age=None,
):
"""Initiate an auth code flow.

Expand Down Expand Up @@ -588,6 +589,17 @@ def initiate_auth_code_flow(
`here <https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-authorization-code>`_ and
`here <https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-oapx/86fb452d-e34a-494e-ac61-e526e263b6d8>`_.

:param int max_age:
OPTIONAL. Maximum Authentication Age.
Specifies the allowable elapsed time in seconds
since the last time the End-User was actively authenticated.
If the elapsed time is greater than this value,
Microsoft identity platform will actively re-authenticate the End-User.

MSAL Python will also automatically validate the auth_time in ID token.

New in version 1.15.

:return:
The auth code flow. It is a dict in this form::

Expand Down Expand Up @@ -617,6 +629,7 @@ def initiate_auth_code_flow(
domain_hint=domain_hint,
claims=_merge_claims_challenge_and_capabilities(
self._client_capabilities, claims_challenge),
max_age=max_age,
)
flow["claims_challenge"] = claims_challenge
return flow
Expand Down Expand Up @@ -1403,6 +1416,7 @@ def acquire_token_interactive(
timeout=None,
port=None,
extra_scopes_to_consent=None,
max_age=None,
**kwargs):
"""Acquire token interactively i.e. via a local browser.

Expand Down Expand Up @@ -1448,6 +1462,17 @@ def acquire_token_interactive(
in the same interaction, but for which you won't get back a
token for in this particular operation.

:param int max_age:
OPTIONAL. Maximum Authentication Age.
Specifies the allowable elapsed time in seconds
since the last time the End-User was actively authenticated.
If the elapsed time is greater than this value,
Microsoft identity platform will actively re-authenticate the End-User.

MSAL Python will also automatically validate the auth_time in ID token.

New in version 1.15.

:return:
- A dict containing no "error" key,
and typically contains an "access_token" key.
Expand All @@ -1466,6 +1491,7 @@ def acquire_token_interactive(
port=port or 0),
prompt=prompt,
login_hint=login_hint,
max_age=max_age,
timeout=timeout,
auth_params={
"claims": claims,
Expand Down
30 changes: 26 additions & 4 deletions msal/oauth2cli/oidc.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def decode_id_token(id_token, client_id=None, issuer=None, nonce=None, now=None)
"""
decoded = json.loads(decode_part(id_token.split('.')[1]))
err = None # https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
_now = now or time.time()
_now = int(now or time.time())
skew = 120 # 2 minutes
if _now + skew < decoded.get("nbf", _now - 1): # nbf is optional per JWT specs
# This is not an ID token validation, but a JWT validation
Expand All @@ -67,14 +67,14 @@ def decode_id_token(id_token, client_id=None, issuer=None, nonce=None, now=None)
# the Client and the Token Endpoint (which it is during _obtain_token()),
# the TLS server validation MAY be used to validate the issuer
# in place of checking the token signature.
if _now > decoded["exp"]:
if _now - skew > decoded["exp"]:
err = "9. The current time MUST be before the time represented by the exp Claim."
if nonce and nonce != decoded.get("nonce"):
err = ("11. Nonce must be the same value "
"as the one that was sent in the Authentication Request.")
if err:
raise RuntimeError("%s The id_token was: %s" % (
err, json.dumps(decoded, indent=2)))
raise RuntimeError("%s Current epoch = %s. The id_token was: %s" % (
err, _now, json.dumps(decoded, indent=2)))
return decoded


Expand Down Expand Up @@ -187,6 +187,8 @@ def initiate_auth_code_flow(
flow = super(Client, self).initiate_auth_code_flow(
scope=_scope, nonce=_nonce_hash(nonce), **kwargs)
flow["nonce"] = nonce
if kwargs.get("max_age") is not None:
flow["max_age"] = kwargs["max_age"]
return flow

def obtain_token_by_auth_code_flow(self, auth_code_flow, auth_response, **kwargs):
Expand All @@ -208,6 +210,26 @@ def obtain_token_by_auth_code_flow(self, auth_code_flow, auth_response, **kwargs
raise RuntimeError(
'The nonce in id token ("%s") should match our nonce ("%s")' %
(nonce_in_id_token, expected_hash))

if auth_code_flow.get("max_age") is not None:
auth_time = result.get("id_token_claims", {}).get("auth_time")
if not auth_time:
raise RuntimeError(
"13. max_age was requested, ID token should contain auth_time")
now = int(time.time())
skew = 120 # 2 minutes. Hardcoded, for now
if now - skew > auth_time + auth_code_flow["max_age"]:
raise RuntimeError(
"13. auth_time ({auth_time}) was requested, "
"by using max_age ({max_age}) parameter, "
"and now ({now}) too much time has elasped "
"since last end-user authentication. "
"The ID token was: {id_token}".format(
auth_time=auth_time,
max_age=auth_code_flow["max_age"],
now=now,
id_token=json.dumps(result["id_token_claims"], indent=2),
))
return result

def obtain_token_by_browser(
Expand Down