internal AuthenticationResult( MsalAccessTokenCacheItem msalAccessTokenCacheItem, MsalIdTokenCacheItem msalIdTokenCacheItem, IAuthenticationScheme authenticationScheme, Guid correlationID) { _authenticationScheme = authenticationScheme ?? throw new ArgumentNullException(nameof(authenticationScheme)); if (msalAccessTokenCacheItem.HomeAccountId != null) { string username = msalAccessTokenCacheItem.IsAdfs ? msalIdTokenCacheItem?.IdToken.Upn : msalIdTokenCacheItem?.IdToken?.PreferredUsername; Account = new Account( msalAccessTokenCacheItem.HomeAccountId, username, msalAccessTokenCacheItem.Environment); } AccessToken = authenticationScheme.FormatAccessToken(msalAccessTokenCacheItem); UniqueId = msalIdTokenCacheItem?.IdToken?.GetUniqueId(); ExpiresOn = msalAccessTokenCacheItem.ExpiresOn; ExtendedExpiresOn = msalAccessTokenCacheItem.ExtendedExpiresOn; TenantId = msalIdTokenCacheItem?.IdToken?.TenantId; IdToken = msalIdTokenCacheItem?.Secret; Scopes = msalAccessTokenCacheItem.ScopeSet; IsExtendedLifeTimeToken = msalAccessTokenCacheItem.IsExtendedLifeTimeToken; CorrelationId = correlationID; TokenType = msalAccessTokenCacheItem.TokenType; }
public void DoNotWriteFRTs() { // Arrange _legacyCachePersistence.ThrowOnWrite = true; string clientInfo = MockHelpers.CreateClientInfo("u1", "ut1"); string homeAccountId = ClientInfo.CreateFromJson(clientInfo).ToAccountIdentifier(); var rtItem = new MsalRefreshTokenCacheItem( TestConstants.ProductionPrefNetworkEnvironment, TestConstants.ClientId, "someRT", clientInfo, "familyId", homeAccountId); var idTokenCacheItem = new MsalIdTokenCacheItem( TestConstants.ProductionPrefNetworkEnvironment, // different env TestConstants.ClientId, MockHelpers.CreateIdToken("u1", "username"), clientInfo, tenantId: "ut1", homeAccountId: homeAccountId); // Act CacheFallbackOperations.WriteAdalRefreshToken( _logger, _legacyCachePersistence, rtItem, idTokenCacheItem, "https://some_env.com/common", // yet another env "uid", "scope1"); AssertCacheEntryCount(0); }
internal IdTokenCacheItemDetails(MsalIdTokenCacheItem msalIdTokenCacheItem) { InitializeComponent(); credentialTypeLabel.Text = msalIdTokenCacheItem.CredentialType; clientIdLabel.Text = msalIdTokenCacheItem.ClientId; authorityLabel.Text = msalIdTokenCacheItem.Authority; environmentLabel.Text = msalIdTokenCacheItem.Environment; tenantIdLabel.Text = msalIdTokenCacheItem.TenantId; userIdentifierLabel.Text = msalIdTokenCacheItem.HomeAccountId; secretLabel.Text = StringShortenerConverter.GetShortStr(msalIdTokenCacheItem.Secret, 100); idTokenLabel.Text = JsonHelper.SerializeToJson(msalIdTokenCacheItem.IdToken); rawClientInfoLabel.Text = msalIdTokenCacheItem.RawClientInfo; if (msalIdTokenCacheItem.RawClientInfo != null) { var clientInfo = ClientInfo.CreateFromJson(msalIdTokenCacheItem.RawClientInfo); clientInfoUniqueIdentifierLabel.Text = clientInfo.UniqueObjectIdentifier; clientInfoUniqueTenantIdentifierLabel.Text = clientInfo.UniqueTenantIdentifier; } }
public void WriteAdalRefreshToken_ErrorLog() { // Arrange _legacyCachePersistence.ThrowOnWrite = true; var rtItem = new MsalRefreshTokenCacheItem( CoreTestConstants.ProductionPrefNetworkEnvironment, CoreTestConstants.ClientId, "someRT", MockHelpers.CreateClientInfo("u1", "ut1")); var idTokenCacheItem = new MsalIdTokenCacheItem( CoreTestConstants.ProductionPrefCacheEnvironment, // different env CoreTestConstants.ClientId, MockHelpers.CreateIdToken("u1", "username"), MockHelpers.CreateClientInfo("u1", "ut1"), "ut1"); // Act CacheFallbackOperations.WriteAdalRefreshToken( _legacyCachePersistence, rtItem, idTokenCacheItem, "https://some_env.com/common", // yet another env "uid", "scope1"); // Assert MsalLogger.Default.Received().Error(Arg.Is <string>(CacheFallbackOperations.DifferentAuthorityError)); MsalLogger.Default.Received().Error(Arg.Is <string>(CacheFallbackOperations.DifferentEnvError)); }
internal IdTokenCacheItemDetails(MsalIdTokenCacheItem msalIdTokenCacheItem) { InitializeComponent(); credentialTypeLabel.Text = msalIdTokenCacheItem.CredentialType; clientIdLabel.Text = msalIdTokenCacheItem.ClientId; authorityLabel.Text = msalIdTokenCacheItem.Authority; environmentLabel.Text = msalIdTokenCacheItem.Environment; tenantIdLabel.Text = msalIdTokenCacheItem.TenantId; userIdentifierLabel.Text = msalIdTokenCacheItem.HomeAccountId; secretLabel.Text = StringShortenerConverter.GetShortStr(msalIdTokenCacheItem.Secret, 100); idTokenLabel.Text = JsonHelper.SerializeToJson(msalIdTokenCacheItem.IdToken); rawClientInfoLabel.Text = msalIdTokenCacheItem.RawClientInfo; clientInfoUniqueIdentifierLabel.Text = msalIdTokenCacheItem.ClientInfo.UniqueObjectIdentifier; clientInfoUniqueTenantIdentifierLabel.Text = msalIdTokenCacheItem.ClientInfo.UniqueTenantIdentifier; //userDisplayableIdLabel.Text = MsalAccountCacheItem.PreferredUsername; //userNameLabel.Text = MsalAccountCacheItem.Name; //userIdentityProviderLabel.Text = MsalAccountCacheItem.IdentityProvider; }
internal AccessTokenCacheItemDetails(MsalAccessTokenCacheItem msalAccessTokenCacheItem, MsalIdTokenCacheItem msalIdTokenCacheItem) { InitializeComponent(); clientIdLabel.Text = msalAccessTokenCacheItem.ClientId; credentialTypeLabel.Text = msalAccessTokenCacheItem.CredentialType; environmentLabel.Text = msalAccessTokenCacheItem.Environment; tenantIdLabel.Text = msalAccessTokenCacheItem.TenantId; userIdentifierLabel.Text = msalAccessTokenCacheItem.HomeAccountId; userAssertionHashLabel.Text = msalAccessTokenCacheItem.UserAssertionHash; expiresOnLabel.Text = msalAccessTokenCacheItem.ExpiresOn.ToString(CultureInfo.InvariantCulture); scopesLabel.Text = msalAccessTokenCacheItem.NormalizedScopes; cachedAtLabel.Text = CoreHelpers .UnixTimestampStringToDateTime(msalAccessTokenCacheItem.CachedAt) .ToString(CultureInfo.InvariantCulture); rawClientInfoLabel.Text = msalAccessTokenCacheItem.RawClientInfo; if (msalAccessTokenCacheItem.RawClientInfo != null) { var clientInfo = ClientInfo.CreateFromJson(msalAccessTokenCacheItem.RawClientInfo); clientInfoUniqueIdentifierLabel.Text = clientInfo.UniqueObjectIdentifier; clientInfoUniqueTenantIdentifierLabel.Text = clientInfo.UniqueTenantIdentifier; } secretLabel.Text = StringShortenerConverter.GetShortStr(msalAccessTokenCacheItem.Secret, 100); }
public void SaveIdToken(MsalIdTokenCacheItem item) { ISharedPreferencesEditor editor = _idTokenSharedPreference.Edit(); editor.PutString(item.GetKey().ToString(), item.ToJsonString()); editor.Apply(); }
public void SaveIdToken(MsalIdTokenCacheItem item) { ApplicationDataCompositeValue composite = new ApplicationDataCompositeValue(); SetCacheValue(composite, JsonHelper.SerializeToJson(item)); _idTokenContainer.Values[/*CoreCryptographyHelpers.CreateBase64UrlEncodedSha256Hash(cacheKey)*/ item.GetKey().ToString()] = composite; }
internal override async Task <AuthenticationResult> ExecuteAsync(CancellationToken cancellationToken) { if (TokenCache == null) { throw new MsalUiRequiredException( MsalUiRequiredException.TokenCacheNullError, "Token cache is set to null. Silent requests cannot be executed."); } // Look for access token. var msalAccessTokenItem = await TokenCache.FindAccessTokenAsync(AuthenticationRequestParameters).ConfigureAwait(false); MsalIdTokenCacheItem msalIdTokenItem = null; if (msalAccessTokenItem != null) { msalIdTokenItem = TokenCache.GetIdTokenCacheItem( msalAccessTokenItem.GetIdTokenItemKey(), AuthenticationRequestParameters.RequestContext); } if (ForceRefresh) { msalAccessTokenItem = null; } if (msalAccessTokenItem != null) { return(new AuthenticationResult(msalAccessTokenItem, msalIdTokenItem)); } var msalRefreshTokenItem = await TokenCache.FindRefreshTokenAsync(AuthenticationRequestParameters).ConfigureAwait(false); if (msalRefreshTokenItem == null) { AuthenticationRequestParameters.RequestContext.Logger.Verbose("No Refresh Token was found in the cache"); throw new MsalUiRequiredException( MsalUiRequiredException.NoTokensFoundError, "No Refresh Token found in the cache"); } AuthenticationRequestParameters.RequestContext.Logger.Verbose("Refreshing access token..."); await ResolveAuthorityEndpointsAsync().ConfigureAwait(false); var msalTokenResponse = await SendTokenRequestAsync(GetBodyParameters(msalRefreshTokenItem.Secret), cancellationToken) .ConfigureAwait(false); if (msalTokenResponse.RefreshToken == null) { msalTokenResponse.RefreshToken = msalRefreshTokenItem.Secret; AuthenticationRequestParameters.RequestContext.Logger.Info( "Refresh token was missing from the token refresh response, so the refresh token in the request is returned instead"); } return(CacheTokenResponseAndCreateAuthenticationResult(msalTokenResponse)); }
public void SaveIdToken(MsalIdTokenCacheItem item) { string itemKey = item.GetKey().ToString(); string partitionKey = CacheKeyFactory.GetKeyFromCachedItem(item); IdTokenCacheDictionary .GetOrAdd(partitionKey, new ConcurrentDictionary <string, MsalIdTokenCacheItem>())[itemKey] = item; }
public void TestSerializeMsalIdTokenCacheItem() { var item = CreateIdTokenItem(); string asJson = item.ToJsonString(); var item2 = MsalIdTokenCacheItem.FromJsonString(asJson); AssertIdTokenCacheItemsAreEqual(item, item2); }
internal AuthenticationResult( MsalAccessTokenCacheItem msalAccessTokenCacheItem, MsalIdTokenCacheItem msalIdTokenCacheItem, IAuthenticationScheme authenticationScheme, Guid correlationID, TokenSource tokenSource, ApiEvent apiEvent, Account account, string spaAuthCode = null) { _authenticationScheme = authenticationScheme ?? throw new ArgumentNullException(nameof(authenticationScheme)); string homeAccountId = msalAccessTokenCacheItem?.HomeAccountId ?? msalIdTokenCacheItem?.HomeAccountId; string environment = msalAccessTokenCacheItem?.Environment ?? msalIdTokenCacheItem?.Environment; ClaimsPrincipal = msalIdTokenCacheItem?.IdToken.ClaimsPrincipal; if (account != null) { Account = account; } else if (homeAccountId != null) { Account = new Account( homeAccountId, msalIdTokenCacheItem?.GetUsername(), environment); } UniqueId = msalIdTokenCacheItem?.IdToken?.GetUniqueId(); TenantId = msalIdTokenCacheItem?.IdToken?.TenantId; IdToken = msalIdTokenCacheItem?.Secret; SpaAuthCode = spaAuthCode; CorrelationId = correlationID; ApiEvent = apiEvent; AuthenticationResultMetadata = new AuthenticationResultMetadata(tokenSource); if (msalAccessTokenCacheItem != null) { AccessToken = authenticationScheme.FormatAccessToken(msalAccessTokenCacheItem); ExpiresOn = msalAccessTokenCacheItem.ExpiresOn; ExtendedExpiresOn = msalAccessTokenCacheItem.ExtendedExpiresOn; Scopes = msalAccessTokenCacheItem.ScopeSet; IsExtendedLifeTimeToken = msalAccessTokenCacheItem.IsExtendedLifeTimeToken; TokenType = msalAccessTokenCacheItem.TokenType; if (msalAccessTokenCacheItem.RefreshOn.HasValue) { AuthenticationResultMetadata.RefreshOn = msalAccessTokenCacheItem.RefreshOn; } } }
public void SaveIdToken(MsalIdTokenCacheItem item, RequestContext requestContext) { using (TelemetryManager.CreateTelemetryHelper(requestContext.TelemetryRequestId, requestContext.ClientId, new CacheEvent(CacheEvent.TokenCacheWrite) { TokenType = CacheEvent.TokenTypes.ID })) { SaveIdToken(item); } }
public static void AddIdTokenToCache(ITokenCacheAccessor accessor, string uid, string utid) { MsalIdTokenCacheItem idTokenCacheItem = new MsalIdTokenCacheItem( MsalTestConstants.ProductionPrefCacheEnvironment, MsalTestConstants.ClientId, MockHelpers.CreateIdToken(MsalTestConstants.UniqueId, MsalTestConstants.DisplayableId), MockHelpers.CreateClientInfo(), MsalTestConstants.Utid); accessor.SaveIdToken(idTokenCacheItem); }
public void DeleteIdToken(MsalIdTokenCacheItem item) { string partitionKey = CacheKeyFactory.GetKeyFromCachedItem(item); IdTokenCacheDictionary.TryGetValue(partitionKey, out var partition); if (partition == null || !partition.TryRemove(item.GetKey().ToString(), out _)) { _logger.InfoPii( $"Cannot delete ID token because it was not found in the cache. Key {item.GetKey()}.", "Cannot delete ID token because it was not found in the cache."); } }
public void SaveIdToken(MsalIdTokenCacheItem item) { var key = item.GetKey(); var account = key.GetiOSAccountKey(); var service = key.GetiOSServiceKey(); var generic = key.GetiOSGenericKey(); var type = (int)CredentialAttrType.IdToken; var value = JsonHelper.SerializeToJson(item); Save(account, service, generic, type, value); }
internal static (MsalAccessTokenCacheItem AT, MsalRefreshTokenCacheItem RT, MsalIdTokenCacheItem ID, MsalAccountCacheItem Account) PopulateCacheWithOneAccessToken(ITokenCacheAccessor accessor, bool randomizeClientInfo = false) { string uid = randomizeClientInfo ? Guid.NewGuid().ToString() : TestConstants.Uid; string utid = randomizeClientInfo ? Guid.NewGuid().ToString() : TestConstants.Utid; string clientInfo = MockHelpers.CreateClientInfo(uid, utid); string homeAccountId = ClientInfo.CreateFromJson(clientInfo).ToAccountIdentifier(); MsalAccessTokenCacheItem atItem = new MsalAccessTokenCacheItem( TestConstants.ProductionPrefCacheEnvironment, TestConstants.ClientId, TestConstants.s_scope.AsSingleString(), TestConstants.Utid, "", DateTimeOffset.UtcNow, new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)), new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExtendedExpiresIn)), clientInfo, homeAccountId); // add access token accessor.SaveAccessToken(atItem); MsalIdTokenCacheItem idTokenCacheItem = new MsalIdTokenCacheItem( TestConstants.ProductionPrefCacheEnvironment, TestConstants.ClientId, MockHelpers.CreateIdToken(TestConstants.UniqueId + "more", TestConstants.DisplayableId), clientInfo, homeAccountId, TestConstants.Utid); accessor.SaveIdToken(idTokenCacheItem); MsalAccountCacheItem accountCacheItem = new MsalAccountCacheItem( TestConstants.ProductionPrefNetworkEnvironment, null, clientInfo, homeAccountId, null, null, TestConstants.Utid, null, null, null); accessor.SaveAccount(accountCacheItem); var rt = AddRefreshTokenToCache(accessor, uid, utid); return(atItem, rt, idTokenCacheItem, accountCacheItem); }
internal AuthenticationResult( MsalAccessTokenCacheItem msalAccessTokenCacheItem, MsalIdTokenCacheItem msalIdTokenCacheItem, IAuthenticationScheme authenticationScheme, Guid correlationID, TokenSource tokenSource, ApiEvent apiEvent) { _authenticationScheme = authenticationScheme ?? throw new ArgumentNullException(nameof(authenticationScheme)); string homeAccountId = msalAccessTokenCacheItem?.HomeAccountId ?? msalIdTokenCacheItem?.HomeAccountId; string environment = msalAccessTokenCacheItem?.Environment ?? msalIdTokenCacheItem?.Environment; if (homeAccountId != null) { string username = null; if (msalIdTokenCacheItem != null) { username = msalIdTokenCacheItem.IsAdfs ? msalIdTokenCacheItem?.IdToken.Upn : msalIdTokenCacheItem?.IdToken?.PreferredUsername; } Account = new Account( homeAccountId, username, environment); } if (msalAccessTokenCacheItem != null) { AccessToken = authenticationScheme.FormatAccessToken(msalAccessTokenCacheItem); ExpiresOn = msalAccessTokenCacheItem.ExpiresOn; ExtendedExpiresOn = msalAccessTokenCacheItem.ExtendedExpiresOn; Scopes = msalAccessTokenCacheItem.ScopeSet; IsExtendedLifeTimeToken = msalAccessTokenCacheItem.IsExtendedLifeTimeToken; TokenType = msalAccessTokenCacheItem.TokenType; } UniqueId = msalIdTokenCacheItem?.IdToken?.GetUniqueId(); TenantId = msalIdTokenCacheItem?.IdToken?.TenantId; IdToken = msalIdTokenCacheItem?.Secret; CorrelationId = correlationID; ApiEvent = apiEvent; AuthenticationResultMetadata = new AuthenticationResultMetadata(tokenSource); }
public static void DeleteAccessToken( this ITokenCacheInternal tokenCache, MsalAccessTokenCacheItem msalAccessTokenCacheItem, MsalIdTokenCacheItem msalIdTokenCacheItem, RequestContext requestContext) { tokenCache.Semaphore.Wait(); try { tokenCache.Accessor.DeleteAccessToken(msalAccessTokenCacheItem.GetKey()); } finally { tokenCache.Semaphore.Release(); } }
internal static void PopulateCache(ITokenCacheAccessor accessor) { MsalAccessTokenCacheItem atItem = new MsalAccessTokenCacheItem( CoreTestConstants.ProductionPrefCacheEnvironment, CoreTestConstants.ClientId, "Bearer", CoreTestConstants.Scope.AsSingleString(), CoreTestConstants.Utid, "", new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)), new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExtendedExpiresIn)), MockHelpers.CreateClientInfo()); // add access token accessor.SaveAccessToken(atItem); MsalIdTokenCacheItem idTokenCacheItem = new MsalIdTokenCacheItem( CoreTestConstants.ProductionPrefCacheEnvironment, CoreTestConstants.ClientId, MockHelpers.CreateIdToken(CoreTestConstants.UniqueId + "more", CoreTestConstants.DisplayableId), MockHelpers.CreateClientInfo(), CoreTestConstants.Utid); accessor.SaveIdToken(idTokenCacheItem); MsalAccountCacheItem accountCacheItem = new MsalAccountCacheItem (CoreTestConstants.ProductionPrefNetworkEnvironment, null, MockHelpers.CreateClientInfo(), null, null, CoreTestConstants.Utid, null, null); accessor.SaveAccount(accountCacheItem); atItem = new MsalAccessTokenCacheItem( CoreTestConstants.ProductionPrefCacheEnvironment, CoreTestConstants.ClientId, "Bearer", CoreTestConstants.ScopeForAnotherResource.AsSingleString(), CoreTestConstants.Utid, "", new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)), new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExtendedExpiresIn)), MockHelpers.CreateClientInfo()); // add another access token accessor.SaveAccessToken(atItem); AddRefreshTokenToCache(accessor, CoreTestConstants.Uid, CoreTestConstants.Utid, CoreTestConstants.Name); }
internal void PopulateCacheWithOneAccessToken(ITokenCacheAccessor accessor) { string clientInfo = MockHelpers.CreateClientInfo(); string homeAccountId = ClientInfo.CreateFromJson(clientInfo).ToAccountIdentifier(); MsalAccessTokenCacheItem atItem = new MsalAccessTokenCacheItem( TestConstants.ProductionPrefCacheEnvironment, TestConstants.ClientId, TestConstants.s_scope.AsSingleString(), TestConstants.Utid, "", new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)), new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExtendedExpiresIn)), clientInfo, homeAccountId); // add access token accessor.SaveAccessToken(atItem); MsalIdTokenCacheItem idTokenCacheItem = new MsalIdTokenCacheItem( TestConstants.ProductionPrefCacheEnvironment, TestConstants.ClientId, MockHelpers.CreateIdToken(TestConstants.UniqueId + "more", TestConstants.DisplayableId), clientInfo, homeAccountId, TestConstants.Utid); accessor.SaveIdToken(idTokenCacheItem); MsalAccountCacheItem accountCacheItem = new MsalAccountCacheItem( TestConstants.ProductionPrefNetworkEnvironment, null, clientInfo, homeAccountId, null, null, TestConstants.Utid, null, null, null); accessor.SaveAccount(accountCacheItem); AddRefreshTokenToCache(accessor, TestConstants.Uid, TestConstants.Utid); }
internal static void PopulateLegacyWithRtAndId( ICoreLogger logger, ILegacyCachePersistence legacyCachePersistence, string clientId, string env, string uid, string uniqueTenantId, string username, string scope) { string clientInfoString; string homeAccountId; if (string.IsNullOrEmpty(uid) || string.IsNullOrEmpty(uniqueTenantId)) { clientInfoString = null; homeAccountId = null; } else { clientInfoString = MockHelpers.CreateClientInfo(uid, uniqueTenantId); homeAccountId = ClientInfo.CreateFromJson(clientInfoString).ToAccountIdentifier(); } var rtItem = new MsalRefreshTokenCacheItem(env, clientId, "someRT", clientInfoString, null, homeAccountId); var idTokenCacheItem = new MsalIdTokenCacheItem( env, clientId, MockHelpers.CreateIdToken(uid, username), clientInfoString, homeAccountId, tenantId: uniqueTenantId); CacheFallbackOperations.WriteAdalRefreshToken( logger, legacyCachePersistence, rtItem, idTokenCacheItem, "https://" + env + "/common", uid, scope); }
private void RefreshCacheView() { var tokenCache = App.MsalPublicClient.UserTokenCache; var requestContext = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null)); IDictionary <string, MsalAccessTokenCacheItem> accessTokens = new Dictionary <string, MsalAccessTokenCacheItem>(); foreach (var accessItemStr in tokenCache.GetAllAccessTokenCacheItems(requestContext)) { MsalAccessTokenCacheItem accessItem = JsonHelper.DeserializeFromJson <MsalAccessTokenCacheItem>(accessItemStr); accessTokens.Add(accessItem.GetKey().ToString(), accessItem); } accessTokenCacheItems.ItemsSource = accessTokens; IDictionary <string, MsalRefreshTokenCacheItem> refreshTokens = new Dictionary <string, MsalRefreshTokenCacheItem>(); foreach (var refreshItemStr in tokenCache.GetAllRefreshTokenCacheItems(requestContext)) { MsalRefreshTokenCacheItem refreshItem = JsonHelper.DeserializeFromJson <MsalRefreshTokenCacheItem>(refreshItemStr); refreshTokens.Add(refreshItem.GetKey().ToString(), refreshItem); } refreshTokenCacheItems.ItemsSource = refreshTokens; IDictionary <string, MsalIdTokenCacheItem> idTokens = new Dictionary <string, MsalIdTokenCacheItem>(); foreach (var idItemStr in tokenCache.GetAllIdTokenCacheItems(requestContext)) { MsalIdTokenCacheItem idItem = JsonHelper.DeserializeFromJson <MsalIdTokenCacheItem>(idItemStr); idTokens.Add(idItem.GetKey().ToString(), idItem); } idTokenCacheItems.ItemsSource = idTokens; IDictionary <string, MsalAccountCacheItem> accounts = new Dictionary <string, MsalAccountCacheItem>(); foreach (var accountStr in tokenCache.GetAllAccountCacheItems(requestContext)) { MsalAccountCacheItem accountItem = JsonHelper.DeserializeFromJson <MsalAccountCacheItem>(accountStr); accounts.Add(accountItem.GetKey().ToString(), accountItem); } accountsCacheItems.ItemsSource = accounts; }
private void PopulateLegacyWithRtAndId( ILegacyCachePersistence legacyCachePersistence, string clientId, string env, string uid, string uniqueTenantId, string username, string scope) { string clientInfoString; if (string.IsNullOrEmpty(uid) || string.IsNullOrEmpty(uniqueTenantId)) { clientInfoString = null; } else { clientInfoString = MockHelpers.CreateClientInfo(uid, uniqueTenantId); } var rtItem = new MsalRefreshTokenCacheItem(env, clientId, "someRT", clientInfoString); var idTokenCacheItem = new MsalIdTokenCacheItem( env, clientId, MockHelpers.CreateIdToken(uid, username), clientInfoString, uniqueTenantId); CacheFallbackOperations.WriteAdalRefreshToken( _logger, legacyCachePersistence, rtItem, idTokenCacheItem, "https://" + env + "/common", "uid", scope); }
public void WriteAdalRefreshToken_ErrorLog() { // Arrange _legacyCachePersistence.ThrowOnWrite = true; string clientInfo = MockHelpers.CreateClientInfo("u1", "ut1"); string homeAccountId = ClientInfo.CreateFromJson(clientInfo).ToAccountIdentifier(); var rtItem = new MsalRefreshTokenCacheItem( TestConstants.ProductionPrefNetworkEnvironment, TestConstants.ClientId, "someRT", clientInfo, null, homeAccountId); var idTokenCacheItem = new MsalIdTokenCacheItem( TestConstants.ProductionPrefCacheEnvironment, // different env TestConstants.ClientId, MockHelpers.CreateIdToken("u1", "username"), clientInfo, tenantId: "ut1", homeAccountId: homeAccountId); // Act CacheFallbackOperations.WriteAdalRefreshToken( _logger, _legacyCachePersistence, rtItem, idTokenCacheItem, "https://some_env.com/common", // yet another env "uid", "scope1"); // Assert _logger.Received().Error(Arg.Is <string>(CacheFallbackOperations.DifferentAuthorityError)); _logger.Received().Error(Arg.Is <string>(CacheFallbackOperations.DifferentEnvError)); }
public void TestSerializeMsalIdTokenCacheItemWithAdditionalFields() { var item = CreateIdTokenItem(); // Add an unknown field into the json var asJObject = item.ToJObject(); asJObject["unsupported_field_name"] = "this is a value"; // Ensure unknown field remains in the AdditionalFieldsJson block var item2 = MsalIdTokenCacheItem.FromJObject(asJObject); Assert.AreEqual("{\r\n \"unsupported_field_name\": \"this is a value\"\r\n}", item2.AdditionalFieldsJson); // Ensure additional fields make the round trip into json asJObject = item2.ToJObject(); AssertIdTokenHasJObjectFields( asJObject, new List <string> { "unsupported_field_name" }); }
async Task <Tuple <MsalAccessTokenCacheItem, MsalIdTokenCacheItem> > ITokenCacheInternal.SaveTokenResponseAsync( AuthenticationRequestParameters requestParams, MsalTokenResponse response) { var tenantId = Authority .CreateAuthority(requestParams.TenantUpdatedCanonicalAuthority.AuthorityInfo.CanonicalAuthority) .GetTenantId(); bool isAdfsAuthority = requestParams.AuthorityInfo.AuthorityType == AuthorityType.Adfs; IdToken idToken = IdToken.Parse(response.IdToken); string subject = idToken?.Subject; if (idToken != null && string.IsNullOrEmpty(subject)) { requestParams.RequestContext.Logger.Warning("Subject not present in Id token"); } string preferredUsername = GetPreferredUsernameFromIdToken(isAdfsAuthority, idToken); // Do a full instance discovery when saving tokens (if not cached), // so that the PreferredNetwork environment is up to date. var instanceDiscoveryMetadata = await ServiceBundle.InstanceDiscoveryManager .GetMetadataEntryAsync( requestParams.TenantUpdatedCanonicalAuthority.AuthorityInfo.CanonicalAuthority, requestParams.RequestContext) .ConfigureAwait(false); var msalAccessTokenCacheItem = new MsalAccessTokenCacheItem( instanceDiscoveryMetadata.PreferredCache, requestParams.ClientId, response, tenantId, subject, requestParams.AuthenticationScheme.KeyId) { UserAssertionHash = requestParams.UserAssertion?.AssertionHash, IsAdfs = isAdfsAuthority }; MsalRefreshTokenCacheItem msalRefreshTokenCacheItem = null; MsalIdTokenCacheItem msalIdTokenCacheItem = null; if (idToken != null) { msalIdTokenCacheItem = new MsalIdTokenCacheItem( instanceDiscoveryMetadata.PreferredCache, requestParams.ClientId, response, tenantId, subject) { IsAdfs = isAdfsAuthority }; } await _semaphoreSlim.WaitAsync().ConfigureAwait(false); try { try { Account account = null; string username = isAdfsAuthority ? idToken?.Upn : preferredUsername; if (msalAccessTokenCacheItem.HomeAccountId != null) { account = new Account( msalAccessTokenCacheItem.HomeAccountId, username, instanceDiscoveryMetadata.PreferredCache); } var args = new TokenCacheNotificationArgs(this, ClientId, account, true, (this as ITokenCacheInternal).IsApplicationCache); #pragma warning disable CS0618 // Type or member is obsolete HasStateChanged = true; #pragma warning restore CS0618 // Type or member is obsolete await(this as ITokenCacheInternal).OnBeforeAccessAsync(args).ConfigureAwait(false); try { await(this as ITokenCacheInternal).OnBeforeWriteAsync(args).ConfigureAwait(false); DeleteAccessTokensWithIntersectingScopes( requestParams, instanceDiscoveryMetadata.Aliases, tenantId, msalAccessTokenCacheItem.ScopeSet, msalAccessTokenCacheItem.HomeAccountId, msalAccessTokenCacheItem.TokenType); _accessor.SaveAccessToken(msalAccessTokenCacheItem); if (idToken != null) { _accessor.SaveIdToken(msalIdTokenCacheItem); var msalAccountCacheItem = new MsalAccountCacheItem( instanceDiscoveryMetadata.PreferredCache, response, preferredUsername, tenantId); //The ADFS direct scenario does not return client info so the home account id is acquired from the subject if (isAdfsAuthority && String.IsNullOrEmpty(msalAccountCacheItem.HomeAccountId)) { msalAccountCacheItem.HomeAccountId = idToken.Subject; } _accessor.SaveAccount(msalAccountCacheItem); } // if server returns the refresh token back, save it in the cache. if (response.RefreshToken != null) { msalRefreshTokenCacheItem = new MsalRefreshTokenCacheItem( instanceDiscoveryMetadata.PreferredCache, requestParams.ClientId, response, subject); if (!_featureFlags.IsFociEnabled) { msalRefreshTokenCacheItem.FamilyId = null; } requestParams.RequestContext.Logger.Info("Saving RT in cache..."); _accessor.SaveRefreshToken(msalRefreshTokenCacheItem); } UpdateAppMetadata(requestParams.ClientId, instanceDiscoveryMetadata.PreferredCache, response.FamilyId); // save RT in ADAL cache for public clients // do not save RT in ADAL cache for MSAL B2C scenarios if (!requestParams.IsClientCredentialRequest && !requestParams.AuthorityInfo.AuthorityType.Equals(AuthorityType.B2C)) { var authorityWithPrefferedCache = Authority.CreateAuthorityWithEnvironment( requestParams.TenantUpdatedCanonicalAuthority.AuthorityInfo, instanceDiscoveryMetadata.PreferredCache); CacheFallbackOperations.WriteAdalRefreshToken( Logger, LegacyCachePersistence, msalRefreshTokenCacheItem, msalIdTokenCacheItem, authorityWithPrefferedCache.AuthorityInfo.CanonicalAuthority, msalIdTokenCacheItem.IdToken.ObjectId, response.Scope); } } finally { await(this as ITokenCacheInternal).OnAfterAccessAsync(args).ConfigureAwait(false); } return(Tuple.Create(msalAccessTokenCacheItem, msalIdTokenCacheItem)); } finally { #pragma warning disable CS0618 // Type or member is obsolete HasStateChanged = false; #pragma warning restore CS0618 // Type or member is obsolete } } finally { _semaphoreSlim.Release(); } }
private void AssertIdTokenCacheItemsAreEqual(MsalIdTokenCacheItem expected, MsalIdTokenCacheItem actual) { AssertCredentialCacheItemBaseItemsAreEqual(expected, actual); Assert.AreEqual(expected.TenantId, actual.TenantId, nameof(actual.TenantId)); }
public void TestMsalNet2XCacheSerializationInterop() { var accessor = new InMemoryTokenCacheAccessor(Substitute.For <ICoreLogger>()); var s = new TokenCacheDictionarySerializer(accessor); string binFilePath = ResourceHelper.GetTestResourceRelativePath("cachecompat_dotnet_dictionary.bin"); byte[] bytes = File.ReadAllBytes(binFilePath); s.Deserialize(bytes, false); Assert.AreEqual(1, accessor.GetAllAccessTokens().Count()); Assert.AreEqual(1, accessor.GetAllRefreshTokens().Count()); Assert.AreEqual(1, accessor.GetAllIdTokens().Count()); Assert.AreEqual(1, accessor.GetAllAccounts().Count()); Assert.AreEqual(0, accessor.GetAllAppMetadata().Count()); var expectedAccessTokenItem = new MsalAccessTokenCacheItem("User.Read User.ReadBasic.All profile openid email") { AdditionalFieldsJson = "{\r\n \"access_token_type\": \"Bearer\"\r\n}", Environment = "login.windows.net", HomeAccountId = "13dd2c19-84cd-416a-ae7d-49573e425619.26039cce-489d-4002-8293-5b0c5134eacb", RawClientInfo = string.Empty, ClientId = "b945c513-3946-4ecd-b179-6499803a2167", TenantId = "26039cce-489d-4002-8293-5b0c5134eacb", CachedAt = "1548803419", ExpiresOnUnixTimestamp = "1548846619", ExtendedExpiresOnUnixTimestamp = "1548846619", UserAssertionHash = string.Empty, TokenType = StorageJsonValues.TokenTypeBearer }; AssertAccessTokenCacheItemsAreEqual(expectedAccessTokenItem, accessor.GetAllAccessTokens().First()); var expectedRefreshTokenItem = new MsalRefreshTokenCacheItem { Environment = "login.windows.net", HomeAccountId = "13dd2c19-84cd-416a-ae7d-49573e425619.26039cce-489d-4002-8293-5b0c5134eacb", RawClientInfo = string.Empty, ClientId = "b945c513-3946-4ecd-b179-6499803a2167" }; AssertRefreshTokenCacheItemsAreEqual(expectedRefreshTokenItem, accessor.GetAllRefreshTokens().First()); var expectedIdTokenItem = new MsalIdTokenCacheItem { Environment = "login.windows.net", HomeAccountId = "13dd2c19-84cd-416a-ae7d-49573e425619.26039cce-489d-4002-8293-5b0c5134eacb", RawClientInfo = string.Empty, ClientId = "b945c513-3946-4ecd-b179-6499803a2167", TenantId = "26039cce-489d-4002-8293-5b0c5134eacb" }; AssertIdTokenCacheItemsAreEqual(expectedIdTokenItem, accessor.GetAllIdTokens().First()); var expectedAccountItem = new MsalAccountCacheItem { Environment = "login.windows.net", HomeAccountId = "13dd2c19-84cd-416a-ae7d-49573e425619.26039cce-489d-4002-8293-5b0c5134eacb", RawClientInfo = "eyJ1aWQiOiIxM2RkMmMxOS04NGNkLTQxNmEtYWU3ZC00OTU3M2U0MjU2MTkiLCJ1dGlkIjoiMjYwMzljY2UtNDg5ZC00MDAyLTgyOTMtNWIwYzUxMzRlYWNiIn0", PreferredUsername = "******", Name = "Abhi Test", GivenName = string.Empty, FamilyName = string.Empty, LocalAccountId = "13dd2c19-84cd-416a-ae7d-49573e425619", TenantId = "26039cce-489d-4002-8293-5b0c5134eacb" }; AssertAccountCacheItemsAreEqual(expectedAccountItem, accessor.GetAllAccounts().First()); }
public void TestMsalIdTokenCacheItemFromJsonStringEmpty() { var item = MsalIdTokenCacheItem.FromJsonString(null); Assert.IsNull(item); }