/// <summary>
        /// Algorithm to delete:
        ///
        /// DisplayableId cannot be null
        /// Removal is scoped by enviroment and clientId;
        ///
        /// If accountId != null then delete everything with the same clientInfo
        /// otherwise, delete everything with the same displayableId
        ///
        /// Notes:
        /// - displayableId can change rarely
        /// - ClientCredential Grant uses the app token cache, not the user token cache, so this algorithm does not apply
        /// (nor will GetAccounts / RemoveAccount work)
        ///
        /// </summary>
        public static void RemoveAdalUser(
            ILegacyCachePersistence legacyCachePersistence,
            string clientId,
            string displayableId,
            string accountOrUserId)
        {
            try
            {
                IDictionary <AdalTokenCacheKey, AdalResultWrapper> adalCache =
                    AdalCacheOperations.Deserialize(legacyCachePersistence.LoadCache());

                if (!string.IsNullOrEmpty(accountOrUserId))
                {
                    RemoveEntriesWithMatchingId(clientId, accountOrUserId, adalCache);
                }

                RemoveEntriesWithMatchingName(clientId, displayableId, adalCache);
                legacyCachePersistence.WriteCache(AdalCacheOperations.Serialize(adalCache));
            }
            catch (Exception ex)
            {
                MsalLogger.Default.WarningPiiWithPrefix(ex, "An error occurred while deleting account in ADAL format from the cache. " +
                                                        "For details please see https://aka.ms/net-cache-persistence-errors. ");
            }
        }
Example #2
0
        /// <summary>
        /// Returns a tuple where
        ///
        /// Item1 is a map of ClientInfo -> AdalUserInfo for those users that have ClientInfo
        /// Item2 is a list of AdalUserInfo for those users that do not have ClientInfo
        /// </summary>
        public static AdalUsersForMsal GetAllAdalUsersForMsal(
            ICoreLogger logger,
            ILegacyCachePersistence legacyCachePersistence,
            string clientId)
        {
            var userEntries = new List <AdalUserForMsalEntry>();

            try
            {
                IDictionary <AdalTokenCacheKey, AdalResultWrapper> dictionary =
                    AdalCacheOperations.Deserialize(logger, legacyCachePersistence.LoadCache());

                // filter by client id
                dictionary.Where(p =>
                                 p.Key.ClientId.Equals(clientId, StringComparison.OrdinalIgnoreCase) &&
                                 !string.IsNullOrEmpty(p.Key.Authority))
                .ToList()
                .ForEach(kvp =>
                {
                    userEntries.Add(new AdalUserForMsalEntry(
                                        authority: kvp.Key.Authority,
                                        clientId: clientId,
                                        clientInfo: kvp.Value.RawClientInfo, // optional, missing in ADAL v3
                                        userInfo: kvp.Value.Result.UserInfo));
                });
            }
            catch (Exception ex)
            {
                logger.WarningPiiWithPrefix(ex, "An error occurred while reading accounts in ADAL format from the cache for MSAL. " +
                                            "For details please see https://aka.ms/net-cache-persistence-errors. ");
            }

            return(new AdalUsersForMsal(userEntries));
        }
        public static MsalRefreshTokenCacheItem GetAdalEntryForMsal(
            ICoreLogger logger,
            ILegacyCachePersistence legacyCachePersistence,
            IEnumerable <string> environmentAliases,
            string clientId,
            string upn,
            string uniqueId)
        {
            IEnumerable <MsalRefreshTokenCacheItem> adalRts = GetAllAdalEntriesForMsal(
                logger,
                legacyCachePersistence,
                environmentAliases,
                clientId,
                upn,
                uniqueId);

            IEnumerable <IGrouping <string, MsalRefreshTokenCacheItem> > rtGroupsByEnv = adalRts.GroupBy(rt => rt.Environment.ToLowerInvariant());

            // if we have more than 1 RT per env, there is smth wrong with the ADAL cache
            if (rtGroupsByEnv.Any(g => g.Count() > 1))
            {
                //Due to the fact that there is a problem with the ADAL cache that causes this exception, The ADAL cache will be removed when
                //this exception is triggered so that users can sign in interactivly and repopulate the cache.
                IDictionary <AdalTokenCacheKey, AdalResultWrapper> adalCache =
                    AdalCacheOperations.Deserialize(logger, legacyCachePersistence.LoadCache());

                adalCache.Clear();
                logger.Error(MsalErrorMessage.InvalidAdalCacheMultipleRTs);
                legacyCachePersistence.WriteCache(AdalCacheOperations.Serialize(logger, adalCache));
                return(null);
            }

            return(adalRts.FirstOrDefault());
        }
        public static void WriteAdalRefreshToken(
            ILegacyCachePersistence legacyCachePersistence,
            MsalRefreshTokenCacheItem rtItem,
            MsalIdTokenCacheItem idItem,
            string authority,
            string uniqueId,
            string scope)
        {
            try
            {
                if (rtItem == null)
                {
                    MsalLogger.Default.Info("No refresh token available. Skipping MSAL refresh token cache write");
                    return;
                }

                //Using scope instead of resource because that value does not exist. STS should return it.
                AdalTokenCacheKey key = new AdalTokenCacheKey(authority, scope, rtItem.ClientId, TokenSubjectType.User,
                                                              uniqueId, idItem.IdToken.PreferredUsername);
                AdalResultWrapper wrapper = new AdalResultWrapper()
                {
                    Result = new AdalResult(null, null, DateTimeOffset.MinValue)
                    {
                        UserInfo = new AdalUserInfo()
                        {
                            UniqueId      = uniqueId,
                            DisplayableId = idItem.IdToken.PreferredUsername
                        }
                    },
                    RefreshToken  = rtItem.Secret,
                    RawClientInfo = rtItem.RawClientInfo,
                    //ResourceInResponse is needed to treat RT as an MRRT. See IsMultipleResourceRefreshToken
                    //property in AdalResultWrapper and its usage. Stronger design would be for the STS to return resource
                    //for which the token was issued as well on v2 endpoint.
                    ResourceInResponse = scope
                };

                IDictionary <AdalTokenCacheKey, AdalResultWrapper> dictionary = AdalCacheOperations.Deserialize(legacyCachePersistence.LoadCache());
                dictionary[key] = wrapper;
                legacyCachePersistence.WriteCache(AdalCacheOperations.Serialize(dictionary));
            }
            catch (Exception ex)
            {
                if (!string.Equals(rtItem?.Environment, idItem?.Environment, StringComparison.OrdinalIgnoreCase))
                {
                    MsalLogger.Default.Error(DifferentEnvError);
                }

                if (!string.Equals(rtItem?.Environment, new Uri(authority).Host, StringComparison.OrdinalIgnoreCase))
                {
                    MsalLogger.Default.Error(DifferentAuthorityError);
                }

                MsalLogger.Default.WarningPiiWithPrefix(ex, "An error occurred while writing MSAL refresh token to the cache in ADAL format. " +
                                                        "For details please see https://aka.ms/net-cache-persistence-errors. ");
            }
        }
        /// <summary>
        /// Returns a tuple where
        ///
        /// Item1 is a map of ClientInfo -> AdalUserInfo for those users that have ClientInfo
        /// Item2 is a list of AdalUserInfo for those users that do not have ClientInfo
        /// </summary>
        public static AdalUsersForMsalResult GetAllAdalUsersForMsal(
            ILegacyCachePersistence legacyCachePersistence,
            string clientId)
        {
            var clientInfoToAdalUserMap    = new Dictionary <string, AdalUserInfo>();
            var adalUsersWithoutClientInfo = new List <AdalUserInfo>();

            try
            {
                IDictionary <AdalTokenCacheKey, AdalResultWrapper> dictionary =
                    AdalCacheOperations.Deserialize(legacyCachePersistence.LoadCache());
                // filter by client id and environment first
                // TODO - authority check needs to be updated for alias check
                List <KeyValuePair <AdalTokenCacheKey, AdalResultWrapper> > listToProcess =
                    dictionary.Where(p =>
                                     p.Key.ClientId.Equals(clientId, StringComparison.OrdinalIgnoreCase)).ToList();

                foreach (KeyValuePair <AdalTokenCacheKey, AdalResultWrapper> pair in listToProcess)
                {
                    if (!string.IsNullOrEmpty(pair.Value.RawClientInfo))
                    {
                        clientInfoToAdalUserMap[pair.Value.RawClientInfo] = pair.Value.Result.UserInfo;
                    }
                    else
                    {
                        adalUsersWithoutClientInfo.Add(pair.Value.Result.UserInfo);
                    }
                }
            }
            catch (Exception ex)
            {
                MsalLogger.Default.WarningPiiWithPrefix(ex, "An error occurred while reading accounts in ADAL format from the cache for MSAL. " +
                                                        "For details please see https://aka.ms/net-cache-persistence-errors. ");

                return(new AdalUsersForMsalResult());
            }
            return(new AdalUsersForMsalResult(clientInfoToAdalUserMap, adalUsersWithoutClientInfo));
        }
        public static List <MsalRefreshTokenCacheItem> GetAllAdalEntriesForMsal(ILegacyCachePersistence legacyCachePersistence,
                                                                                ISet <string> environmentAliases, string clientId, string upn, string uniqueId, string rawClientInfo)
        {
            try
            {
                IDictionary <AdalTokenCacheKey, AdalResultWrapper> dictionary =
                    AdalCacheOperations.Deserialize(legacyCachePersistence.LoadCache());
                //filter by client id and environment first
                //TODO - authority check needs to be updated for alias check
                List <KeyValuePair <AdalTokenCacheKey, AdalResultWrapper> > listToProcess =
                    dictionary.Where(p =>
                                     p.Key.ClientId.Equals(clientId, StringComparison.OrdinalIgnoreCase) &&
                                     environmentAliases.Contains(new Uri(p.Key.Authority).Host)).ToList();

                //if client info is provided then use it to filter
                if (!string.IsNullOrEmpty(rawClientInfo))
                {
                    List <KeyValuePair <AdalTokenCacheKey, AdalResultWrapper> > clientInfoEntries =
                        listToProcess.Where(p => rawClientInfo.Equals(p.Value.RawClientInfo, StringComparison.OrdinalIgnoreCase)).ToList();
                    if (clientInfoEntries.Any())
                    {
                        listToProcess = clientInfoEntries;
                    }
                }

                //if upn is provided then use it to filter
                if (!string.IsNullOrEmpty(upn))
                {
                    List <KeyValuePair <AdalTokenCacheKey, AdalResultWrapper> > upnEntries =
                        listToProcess.Where(p => upn.Equals(p.Key.DisplayableId, StringComparison.OrdinalIgnoreCase)).ToList();
                    if (upnEntries.Any())
                    {
                        listToProcess = upnEntries;
                    }
                }

                //if userId is provided then use it to filter
                if (!string.IsNullOrEmpty(uniqueId))
                {
                    List <KeyValuePair <AdalTokenCacheKey, AdalResultWrapper> > uniqueIdEntries =
                        listToProcess.Where(p => uniqueId.Equals(p.Key.UniqueId, StringComparison.OrdinalIgnoreCase)).ToList();
                    if (uniqueIdEntries.Any())
                    {
                        listToProcess = uniqueIdEntries;
                    }
                }

                List <MsalRefreshTokenCacheItem> list = new List <MsalRefreshTokenCacheItem>();
                foreach (KeyValuePair <AdalTokenCacheKey, AdalResultWrapper> pair in listToProcess)
                {
                    list.Add(new MsalRefreshTokenCacheItem
                                 (new Uri(pair.Key.Authority).Host, pair.Key.ClientId, pair.Value.RefreshToken, pair.Value.RawClientInfo));
                }

                return(list);
            }
            catch (Exception ex)
            {
                MsalLogger.Default.WarningPiiWithPrefix(ex, "An error occurred while searching for refresh tokens in ADAL format in the cache for MSAL. " +
                                                        "For details please see https://aka.ms/net-cache-persistence-errors. ");

                return(new List <MsalRefreshTokenCacheItem>());
            }
        }
Example #7
0
        public static MsalRefreshTokenCacheItem GetRefreshToken(
            ICoreLogger logger,
            ILegacyCachePersistence legacyCachePersistence,
            IEnumerable <string> environmentAliases,
            string clientId,
            IAccount account)
        {
            try
            {
                IDictionary <AdalTokenCacheKey, AdalResultWrapper> dictionary =
                    AdalCacheOperations.Deserialize(logger, legacyCachePersistence.LoadCache());

                IEnumerable <KeyValuePair <AdalTokenCacheKey, AdalResultWrapper> > listToProcess =
                    dictionary.Where(p =>
                                     p.Key.ClientId.Equals(clientId, StringComparison.OrdinalIgnoreCase) &&
                                     environmentAliases.Contains(new Uri(p.Key.Authority).Host));

                bool filtered = false;

                if (!string.IsNullOrEmpty(account?.Username))
                {
                    listToProcess =
                        listToProcess.Where(p => account.Username.Equals(
                                                p.Key.DisplayableId, StringComparison.OrdinalIgnoreCase));

                    filtered = true;
                }

                if (!string.IsNullOrEmpty(account?.HomeAccountId?.ObjectId))
                {
                    listToProcess =
                        listToProcess.Where(p => account.HomeAccountId.ObjectId.Equals(
                                                p.Key.UniqueId, StringComparison.OrdinalIgnoreCase)).ToList();

                    filtered = true;
                }

                // We should filter at leasts by one criteria to ensure we retrun adequate RT
                if (!filtered)
                {
                    logger.Warning("Could not filter ADAL entries by either UPN or unique ID, skipping.");
                    return(null);
                }

                return(listToProcess.Select(adalEntry => new MsalRefreshTokenCacheItem(
                                                new Uri(adalEntry.Key.Authority).Host,
                                                adalEntry.Key.ClientId,
                                                adalEntry.Value.RefreshToken,
                                                adalEntry.Value.RawClientInfo,
                                                familyId: null,
                                                homeAccountId: GetHomeAccountId(adalEntry.Value)))
                       .FirstOrDefault());
            }
            catch (Exception ex)
            {
                logger.WarningPiiWithPrefix(ex, "An error occurred while searching for refresh tokens in ADAL format in the cache for MSAL. " +
                                            "For details please see https://aka.ms/net-cache-persistence-errors. ");

                return(null);
            }
        }