Skip to content

[Proof of Concept] Call remove_account when new account is created #1

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

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open
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
10 changes: 8 additions & 2 deletions msal/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def __init__(
http_client=None,
verify=True, proxies=None, timeout=None,
client_claims=None, app_name=None, app_version=None,
client_capabilities=None):
client_capabilities=None, remove_existing_account=True):
"""Create an instance of application.

:param str client_id: Your app has a client_id after you register it on AAD.
Expand Down Expand Up @@ -215,6 +215,10 @@ def __init__(
MSAL will combine them into
`claims parameter <https://openid.net/specs/openid-connect-core-1_0-final.html#ClaimsParameter`_
which you will later provide via one of the acquire-token request.
:param bool remove_existing_account: (optional)
After a successful sign-in, if the sign-in account already exists in the token
cache, remove it first along with its tokens to prevent MSAL from returning
cached access tokens from the previous session that may have been revoked.
"""
self.client_id = client_id
self.client_credential = client_credential
Expand Down Expand Up @@ -248,6 +252,7 @@ def __init__(
self.authority_groups = None
self._telemetry_buffer = {}
self._telemetry_lock = Lock()
self.remove_existing_account = remove_existing_account

def _build_telemetry_context(
self, api_id, correlation_id=None, refresh_reason=None):
Expand Down Expand Up @@ -309,7 +314,8 @@ def _build_client(self, client_credential, authority):
client_assertion=client_assertion,
client_assertion_type=client_assertion_type,
on_obtaining_tokens=lambda event: self.token_cache.add(dict(
event, environment=authority.instance)),
event, environment=authority.instance,
on_creating_account=self.remove_account if self.remove_existing_account else None)),
on_removing_rt=self.token_cache.remove_rt,
on_updating_rt=self.token_cache.update_rt)

Expand Down
2 changes: 1 addition & 1 deletion msal/oauth2cli/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -804,6 +804,7 @@ def obtain_token_by_refresh_token(self, token_item, scope=None,
if not isinstance(token_item, string_types) else token_item,
scope=scope,
also_save_rt=on_updating_rt is False,
on_obtaining_tokens=on_obtaining_tokens,
**kwargs)
if resp.get('error') == 'invalid_grant':
(on_removing_rt or self.on_removing_rt)(token_item) # Discard old RT
Expand All @@ -829,4 +830,3 @@ def obtain_token_by_assertion(
data = kwargs.pop("data", {})
data.update(scope=scope, assertion=encoder(assertion))
return self._obtain_token(grant_type, data=data, **kwargs)

62 changes: 32 additions & 30 deletions msal/token_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,31 +150,6 @@ def __add(self, event, now=None):
with self._lock:
now = int(time.time() if now is None else now)

if access_token:
expires_in = int( # AADv1-like endpoint returns a string
response.get("expires_in", 3599))
ext_expires_in = int( # AADv1-like endpoint returns a string
response.get("ext_expires_in", expires_in))
at = {
"credential_type": self.CredentialType.ACCESS_TOKEN,
"secret": access_token,
"home_account_id": home_account_id,
"environment": environment,
"client_id": event.get("client_id"),
"target": target,
"realm": realm,
"token_type": response.get("token_type", "Bearer"),
"cached_at": str(now), # Schema defines it as a string
"expires_on": str(now + expires_in), # Same here
"extended_expires_on": str(now + ext_expires_in) # Same here
}
if data.get("key_id"): # It happens in SSH-cert or POP scenario
at["key_id"] = data.get("key_id")
if "refresh_in" in response:
refresh_in = response["refresh_in"] # It is an integer
at["refresh_on"] = str(now + refresh_in) # Schema wants a string
self.modify(self.CredentialType.ACCESS_TOKEN, at, at)

if client_info and not event.get("skip_account_creation"):
account = {
Comment on lines 153 to 154
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The order of adding tokens to the cache matters. Always create the account first so that old account can be removed first.

"home_account_id": home_account_id,
Expand All @@ -183,13 +158,16 @@ def __add(self, event, now=None):
"local_account_id": id_token_claims.get(
"oid", id_token_claims.get("sub")),
"username": id_token_claims.get("preferred_username") # AAD
or id_token_claims.get("upn") # ADFS 2019
or "", # The schema does not like null
or id_token_claims.get("upn") # ADFS 2019
or "", # The schema does not like null
"authority_type":
self.AuthorityType.ADFS if realm == "adfs"
else self.AuthorityType.MSSTS,
# "client_info": response.get("client_info"), # Optional
}
}
on_creating_account = event.get('on_creating_account')
if on_creating_account:
on_creating_account(account)
self.modify(self.CredentialType.ACCOUNT, account, account)

if id_token:
Expand All @@ -201,9 +179,34 @@ def __add(self, event, now=None):
"realm": realm,
"client_id": event.get("client_id"),
# "authority": "it is optional",
}
}
self.modify(self.CredentialType.ID_TOKEN, idt, idt)

if access_token:
expires_in = int( # AADv1-like endpoint returns a string
response.get("expires_in", 3599))
ext_expires_in = int( # AADv1-like endpoint returns a string
response.get("ext_expires_in", expires_in))
at = {
"credential_type": self.CredentialType.ACCESS_TOKEN,
"secret": access_token,
"home_account_id": home_account_id,
"environment": environment,
"client_id": event.get("client_id"),
"target": target,
"realm": realm,
"token_type": response.get("token_type", "Bearer"),
"cached_at": str(now), # Schema defines it as a string
"expires_on": str(now + expires_in), # Same here
"extended_expires_on": str(now + ext_expires_in) # Same here
}
if data.get("key_id"): # It happens in SSH-cert or POP scenario
at["key_id"] = data.get("key_id")
if "refresh_in" in response:
refresh_in = response["refresh_in"] # It is an integer
at["refresh_on"] = str(now + refresh_in) # Schema wants a string
self.modify(self.CredentialType.ACCESS_TOKEN, at, at)

if refresh_token:
rt = {
"credential_type": self.CredentialType.REFRESH_TOKEN,
Expand Down Expand Up @@ -315,4 +318,3 @@ def serialize(self):
with self._lock:
self.has_state_changed = False
return json.dumps(self._cache, indent=4)