protected AcquireTokenHandlerBase(Authenticator authenticator, TokenCache tokenCache, string[] scope,
            ClientKey clientKey, TokenSubjectType subjectType)
        {
            this.Authenticator = authenticator;
            this.CallState = CreateCallState(this.Authenticator.CorrelationId);
            PlatformPlugin.Logger.Information(this.CallState,
                string.Format(
                    "=== accessToken Acquisition started:\n\tAuthority: {0}\n\tResource: {1}\n\tClientId: {2}\n\tCacheType: {3}\n\tAuthentication Target: {4}\n\t",
                    authenticator.Authority, scope, clientKey.ClientId,
                    (tokenCache != null)
                        ? tokenCache.GetType().FullName + string.Format(" ({0} items)", tokenCache.Count)
                        : "null",
                    subjectType));

            this.tokenCache = tokenCache;
            this.ClientKey = clientKey;
            this.TokenSubjectType = subjectType;

            this.LoadFromCache = (tokenCache != null);
            this.StoreToCache = (tokenCache != null);
            this.SupportADFS = false;
            if (ADALScopeHelper.IsNullOrEmpty(scope))
            {
                throw new ArgumentNullException("scope");
            }

            this.Scope = scope;
            ValidateScopeInput(scope);
        }
Exemplo n.º 2
0
        internal void StoreToCache(AuthenticationResultEx result, string authority, string resource, string clientId,
                                   TokenSubjectType subjectType, CallState callState)
        {
            lock (cacheLock)
            {
                callState.Logger.Verbose(callState, "Storing token in the cache...");

                string uniqueId      = (result.Result.UserInfo != null) ? result.Result.UserInfo.UniqueId : null;
                string displayableId = (result.Result.UserInfo != null) ? result.Result.UserInfo.DisplayableId : null;

                this.OnBeforeWrite(new TokenCacheNotificationArgs
                {
                    Resource      = resource,
                    ClientId      = clientId,
                    UniqueId      = uniqueId,
                    DisplayableId = displayableId
                });

                TokenCacheKey tokenCacheKey = new TokenCacheKey(authority, resource, clientId, subjectType,
                                                                result.Result.UserInfo);
                this.tokenCacheDictionary[tokenCacheKey] = result;
                callState.Logger.Verbose(callState, "An item was stored in the cache");
                this.UpdateCachedMrrtRefreshTokens(result, clientId, subjectType);

                this.HasStateChanged = true;
            }
        }
        internal async Task StoreToCacheAsync(AuthenticationResultEx result, string authority, string resource, string clientId,
                                              TokenSubjectType subjectType, CallState callState)
        {
            var metadata = await InstanceDiscovery.GetMetadataEntryAsync(new Uri(authority), false, callState).ConfigureAwait(false);

            StoreToCacheCommon(result, ReplaceHost(authority, metadata.PreferredCache), resource, clientId, subjectType, callState);
        }
        protected AcquireTokenHandlerBase(Authenticator authenticator, TokenCache tokenCache, string resource, ClientKey clientKey, TokenSubjectType subjectType, bool callSync)
        {
            this.Authenticator = authenticator;
            this.CallState = CreateCallState(this.Authenticator.CorrelationId, callSync);
            Logger.Information(this.CallState, 
                string.Format("=== Token Acquisition started:\n\tAuthority: {0}\n\tResource: {1}\n\tClientId: {2}\n\tCacheType: {3}\n\tAuthentication Target: {4}\n\t",
                authenticator.Authority, resource, clientKey.ClientId,
                (tokenCache != null) ? tokenCache.GetType().FullName + string.Format(" ({0} items)", tokenCache.Count) : "null",
                subjectType));

            this.tokenCache = tokenCache;

            if (string.IsNullOrWhiteSpace(resource))
            {
                var ex = new ArgumentNullException("resource");
                Logger.Error(this.CallState, ex);
                throw ex;
            }

            this.Resource = (resource != NullResource) ? resource : null;
            this.ClientKey = clientKey;
            this.TokenSubjectType = subjectType;

            this.LoadFromCache = (tokenCache != null);
            this.StoreToCache = (tokenCache != null);
            this.SupportADFS = false;
        }
 internal AdalTokenCacheKey(string authority, string resource, string clientId, TokenSubjectType tokenSubjectType, string uniqueId, string displayableId)
 {
     Authority        = authority;
     Resource         = resource;
     ClientId         = clientId;
     TokenSubjectType = tokenSubjectType;
     UniqueId         = uniqueId;
     DisplayableId    = displayableId;
 }
 internal TokenCacheKey(string authority, string resource, string clientId, TokenSubjectType tokenSubjectType, string uniqueId, string displayableId)
 {
     this.Authority = authority;
     this.Resource = resource;
     this.ClientId = clientId;
     this.TokenSubjectType = tokenSubjectType;
     this.UniqueId = uniqueId;
     this.DisplayableId = displayableId;
 }
        protected AcquireTokenHandlerBase(Authenticator authenticator, TokenCache tokenCache, string resource,
                                          ClientKey clientKey, TokenSubjectType subjectType)
        {
            this.Authenticator = authenticator;
            this.CallState     = CreateCallState(this.Authenticator.CorrelationId);
            PlatformPlugin.Logger.Information(this.CallState,
                                              string.Format(CultureInfo.CurrentCulture, "=== Token Acquisition started:\n\tAuthority: {0}\n\tResource: {1}\n\tClientId: {2}\n\tCacheType: {3}\n\tAuthentication Target: {4}\n\t",
                                                            authenticator.Authority, resource, clientKey.ClientId,
                                                            (tokenCache != null) ? tokenCache.GetType().FullName + string.Format(CultureInfo.CurrentCulture, " ({0} items)", tokenCache.Count) : "null",
                                                            subjectType));

            this.tokenCache = tokenCache;

            if (string.IsNullOrWhiteSpace(resource))
            {
                throw new ArgumentNullException("resource");
            }

            this.Resource         = (resource != NullResource) ? resource : null;
            this.ClientKey        = clientKey;
            this.TokenSubjectType = subjectType;

            this.LoadFromCache = (tokenCache != null);
            this.StoreToCache  = (tokenCache != null);
            this.SupportADFS   = false;

            this.brokerParameters              = new Dictionary <string, string>();
            brokerParameters["authority"]      = authenticator.Authority;
            brokerParameters["resource"]       = resource;
            brokerParameters["client_id"]      = clientKey.ClientId;
            brokerParameters["correlation_id"] = this.CallState.CorrelationId.ToString();
            brokerParameters["client_version"] = AdalIdHelper.GetAdalVersion();
            this.ResultEx = null;

            CacheQueryData               = new CacheQueryData();
            CacheQueryData.Authority     = Authenticator.Authority;
            CacheQueryData.Resource      = this.Resource;
            CacheQueryData.ClientId      = this.ClientKey.ClientId;
            CacheQueryData.SubjectType   = this.TokenSubjectType;
            CacheQueryData.UniqueId      = this.UniqueId;
            CacheQueryData.DisplayableId = this.DisplayableId;
        }
        protected AcquireTokenHandlerBase(Authenticator authenticator, TokenCache tokenCache, string resource, ClientKey clientKey, TokenSubjectType subjectType, bool callSync)
        {
            this.Authenticator = authenticator;

            this.tokenCache = tokenCache;

            if (string.IsNullOrWhiteSpace(resource))
            {
                throw new ArgumentNullException("resource");
            }

            this.Resource = (resource != NullResource) ? resource : null;
            this.ClientKey = clientKey;
            this.TokenSubjectType = subjectType;
            this.CallState = CreateCallState(this.Authenticator.CorrelationId, callSync);

            this.LoadFromCache = (tokenCache != null);
            this.StoreToCache = (tokenCache != null);
            this.SupportADFS = false;
        }
Exemplo n.º 9
0
        private void UpdateCachedMrrtRefreshTokens(AuthenticationResultEx result, string clientId,
                                                   TokenSubjectType subjectType)
        {
            lock (cacheLock)
            {
                if (result.Result.UserInfo != null && result.IsMultipleResourceRefreshToken)
                {
                    //pass null for authority to update the token for all the tenants
                    List <KeyValuePair <TokenCacheKey, AuthenticationResultEx> > mrrtItems =
                        this.QueryCache(null, clientId, subjectType, result.Result.UserInfo.UniqueId,
                                        result.Result.UserInfo.DisplayableId, null)
                        .Where(p => p.Value.IsMultipleResourceRefreshToken)
                        .ToList();

                    foreach (KeyValuePair <TokenCacheKey, AuthenticationResultEx> mrrtItem in mrrtItems)
                    {
                        mrrtItem.Value.RefreshToken = result.RefreshToken;
                    }
                }
            }
        }
Exemplo n.º 10
0
        protected AcquireTokenHandlerBase(Authenticator authenticator, TokenCache tokenCache, string resource, ClientKey clientKey, TokenSubjectType subjectType, bool callSync)
        {
            this.Authenticator = authenticator;
            this.CallState     = CreateCallState(this.Authenticator.CorrelationId, callSync);
            Logger.Information(this.CallState,
                               string.Format("=== Token Acquisition started:\n\tAuthority: {0}\n\tResource: {1}\n\tClientId: {2}\n\tCacheType: {3}\n\tAuthentication Target: {4}\n\t",
                                             authenticator.Authority, resource, clientKey.ClientId,
                                             (tokenCache != null) ? tokenCache.GetType().FullName + string.Format(" ({0} items)", tokenCache.Count) : "null",
                                             subjectType));

            this.tokenCache = tokenCache;

            if (string.IsNullOrWhiteSpace(resource))
            {
                var ex = new ArgumentNullException("resource");
                Logger.Error(this.CallState, ex);
                throw ex;
            }

            this.Resource         = (resource != NullResource) ? resource : null;
            this.ClientKey        = clientKey;
            this.TokenSubjectType = subjectType;

            this.LoadFromCache = (tokenCache != null);
            this.StoreToCache  = (tokenCache != null);
            this.SupportADFS   = false;
        }
        private KeyValuePair <TokenCacheKey, AuthenticationResult>?LoadSingleItemFromCache(string authority, string resource, string clientId, TokenSubjectType subjectType, string uniqueId, string displayableId, CallState callState)
        {
            // First identify all potential tokens.
            List <KeyValuePair <TokenCacheKey, AuthenticationResult> > items = this.QueryCache(authority, clientId, subjectType, uniqueId, displayableId);

            List <KeyValuePair <TokenCacheKey, AuthenticationResult> > resourceSpecificItems =
                items.Where(p => p.Key.ResourceEquals(resource)).ToList();

            int resourceValuesCount = resourceSpecificItems.Count();
            KeyValuePair <TokenCacheKey, AuthenticationResult>?returnValue = null;

            if (resourceValuesCount == 1)
            {
                Logger.Information(callState, "An item matching the requested resource was found in the cache");
                returnValue = resourceSpecificItems.First();
            }
            else if (resourceValuesCount == 0)
            {
                // There are no resource specific tokens.  Choose any of the MRRT tokens if there are any.
                List <KeyValuePair <TokenCacheKey, AuthenticationResult> > mrrtItems =
                    items.Where(p => p.Value.IsMultipleResourceRefreshToken).ToList();

                if (mrrtItems.Any())
                {
                    returnValue = mrrtItems.First();
                    Logger.Information(callState, "A Multi Resource Refresh Token for a different resource was found which can be used");
                }
            }
            else
            {
                throw new AdalException(AdalError.MultipleTokensMatched);
            }

            return(returnValue);
        }
        private void UpdateCachedMrrtRefreshTokens(AuthenticationResult result, string authority, string clientId, TokenSubjectType subjectType)
        {
            if (result.UserInfo != null && result.IsMultipleResourceRefreshToken)
            {
                List <KeyValuePair <TokenCacheKey, AuthenticationResult> > mrrtItems =
                    this.QueryCache(authority, clientId, subjectType, result.UserInfo.UniqueId, result.UserInfo.DisplayableId).Where(p => p.Value.IsMultipleResourceRefreshToken).ToList();

                foreach (KeyValuePair <TokenCacheKey, AuthenticationResult> mrrtItem in mrrtItems)
                {
                    mrrtItem.Value.RefreshToken = result.RefreshToken;
                }
            }
        }
        internal AuthenticationResult LoadFromCache(string authority, string resource, string clientId, TokenSubjectType subjectType, string uniqueId, string displayableId, CallState callState)
        {
            AuthenticationResult result = null;

            KeyValuePair <TokenCacheKey, AuthenticationResult>?kvp = this.LoadSingleItemFromCache(authority, resource, clientId, subjectType, uniqueId, displayableId, callState);

            if (kvp.HasValue)
            {
                TokenCacheKey cacheKey = kvp.Value.Key;
                result = kvp.Value.Value;
                bool tokenNearExpiry = (result.ExpiresOn <= DateTime.UtcNow + TimeSpan.FromMinutes(ExpirationMarginInMinutes));

                if (tokenNearExpiry || !cacheKey.ResourceEquals(resource))
                {
                    result.AccessToken = null;
                    if (tokenNearExpiry)
                    {
                        Logger.Verbose(callState, "An expired or near expiry token was found in the cache");
                    }
                }

                if (result.AccessToken == null && result.RefreshToken == null)
                {
                    this.tokenCacheDictionary.Remove(cacheKey);
                    Logger.Information(callState, "An old item was removed from the cache");
                    this.HasStateChanged = true;
                    result = null;
                }

                if (result != null)
                {
                    Logger.Information(callState, "A matching token was found in the cache");
                }
            }
            else
            {
                Logger.Information(callState, "No matching token was found in the cache");
            }

            return(result);
        }
 /// <summary>
 /// Queries all values in the cache that meet the passed in values, plus the 
 /// authority value that this AuthorizationContext was created with.  In every case passing
 /// null results in a wildcard evaluation.
 /// </summary>
 private List<KeyValuePair<TokenCacheKey, AuthenticationResult>> QueryCache(string authority, string clientId,
     TokenSubjectType subjectType, string uniqueId, string displayableId)
 {
     lock (cacheLock)
     {
         return this.tokenCacheDictionary.Where(
             p =>
                 p.Key.Authority == authority
                 && (string.IsNullOrWhiteSpace(clientId) || p.Key.ClientIdEquals(clientId))
                 && (string.IsNullOrWhiteSpace(uniqueId) || p.Key.UniqueId == uniqueId)
                 && (string.IsNullOrWhiteSpace(displayableId) || p.Key.DisplayableIdEquals(displayableId))
                 && p.Key.TokenSubjectType == subjectType).ToList();
     }
 }
 internal TokenCacheKey(string authority, string resource, string clientId, TokenSubjectType tokenSubjectType, UserInfo userInfo)
     : this(authority, resource, clientId, tokenSubjectType, (userInfo != null) ? userInfo.UniqueId : null, (userInfo != null) ? userInfo.DisplayableId : null)
 {
 }
        internal AuthenticationResult LoadFromCache(string authority, string resource, string clientId, TokenSubjectType subjectType, string uniqueId, string displayableId, CallState callState)
        {
            lock (cacheLock)
            {
                Logger.Verbose(callState, "Looking up cache for a token...");

                AuthenticationResult result = null;

                KeyValuePair<TokenCacheKey, AuthenticationResult>? kvp = this.LoadSingleItemFromCache(authority,
                    resource, clientId, subjectType, uniqueId, displayableId, callState);

                if (kvp.HasValue)
                {
                    TokenCacheKey cacheKey = kvp.Value.Key;
                    result = kvp.Value.Value;
                    bool tokenNearExpiry = (result.ExpiresOn <=
                                            DateTime.UtcNow + TimeSpan.FromMinutes(ExpirationMarginInMinutes));

                    if (tokenNearExpiry)
                    {
                        result.AccessToken = null;
                        Logger.Verbose(callState, "An expired or near expiry token was found in the cache");
                    }
                    else if (!cacheKey.ResourceEquals(resource))
                    {
                        Logger.Verbose(callState,
                            string.Format(
                                "Multi resource refresh token for resource '{0}' will be used to acquire token for '{1}'",
                                cacheKey.Resource, resource));
                        var newResult = new AuthenticationResult(null, null, result.RefreshToken,
                            DateTimeOffset.MinValue);
                        newResult.UpdateTenantAndUserInfo(result.TenantId, result.IdToken, result.UserInfo);
                        result = newResult;
                    }
                    else
                    {
                        Logger.Verbose(callState,
                            string.Format("{0} minutes left until token in cache expires",
                                (result.ExpiresOn - DateTime.UtcNow).TotalMinutes));
                    }

                    if (result.AccessToken == null && result.RefreshToken == null)
                    {
                        this.tokenCacheDictionary.Remove(cacheKey);
                        Logger.Information(callState, "An old item was removed from the cache");
                        this.HasStateChanged = true;
                        result = null;
                    }

                    if (result != null)
                    {
                        Logger.Information(callState,
                            "A matching item (access token or refresh token or both) was found in the cache");
                    }
                }
                else
                {
                    Logger.Information(callState, "No matching token was found in the cache");
                }

                return result;
            }
        }
Exemplo n.º 17
0
        internal AuthenticationResultEx LoadFromCache(string authority, string[] scope, string clientId,
            TokenSubjectType subjectType, string uniqueId, string displayableId, CallState callState)
        {
            PlatformPlugin.Logger.Verbose(callState, "Looking up cache for a token...");
            if (ADALScopeHelper.CreateSetFromArray(scope).Contains(clientId))
            {
                PlatformPlugin.Logger.Verbose(callState, "Looking for id token...");
            }

            AuthenticationResultEx resultEx = null;

            //get either a matching token or an MRRT supported RT
            KeyValuePair<TokenCacheKey, AuthenticationResultEx>? kvp = this.LoadSingleItemFromCache(authority, scope,
                clientId, subjectType, uniqueId, displayableId, callState);

            if (kvp.HasValue)
            {
                TokenCacheKey cacheKey = kvp.Value.Key;
                resultEx = kvp.Value.Value;
                bool tokenNearExpiry = (resultEx.Result.ExpiresOn <=
                                        DateTime.UtcNow + TimeSpan.FromMinutes(ExpirationMarginInMinutes));

                if (tokenNearExpiry)
                {
                    resultEx.Result.Token = null;
                    PlatformPlugin.Logger.Verbose(callState, "An expired or near expiry token was found in the cache");
                }
                else if (!cacheKey.ScopeContains(scope))
                {
                    //requested scope are not a subset.
                    PlatformPlugin.Logger.Verbose(callState,
                        string.Format("Refresh token for scope '{0}' will be used to acquire token for '{1}'",
                            ADALScopeHelper.CreateSingleStringFromArray(cacheKey.Scope),
                            ADALScopeHelper.CreateSingleStringFromArray(scope)));
                    var newResultEx = new AuthenticationResultEx
                    {
                        Result = new AuthenticationResult(null, null, DateTimeOffset.MinValue),
                        RefreshToken = resultEx.RefreshToken,
                        ScopeInResponse = resultEx.ScopeInResponse
                    };

                    newResultEx.Result.UpdateTenantAndUserInfo(resultEx.Result.TenantId, resultEx.Result.ProfileInfo,
                        resultEx.Result.UserInfo);
                    resultEx = newResultEx;
                }
                else
                {
                    PlatformPlugin.Logger.Verbose(callState,
                        string.Format("{0} minutes left until token in cache expires",
                            (resultEx.Result.ExpiresOn - DateTime.UtcNow).TotalMinutes));
                }

                if (resultEx.Result.Token == null && resultEx.RefreshToken == null)
                {
                    this.tokenCacheDictionary.Remove(cacheKey);
                    PlatformPlugin.Logger.Information(callState, "An old item was removed from the cache");
                    this.HasStateChanged = true;
                    resultEx = null;
                }

                if (resultEx != null)
                {
                    PlatformPlugin.Logger.Information(callState,
                        "A matching item (access token or refresh token or both) was found in the cache");
                }
            }
            else
            {
                PlatformPlugin.Logger.Information(callState, "No matching token was found in the cache");
            }

            return resultEx;
        }
 internal AdalTokenCacheKey(string authority, string resource, string clientId, TokenSubjectType tokenSubjectType, AdalUserInfo adalUserInfo)
     : this(authority, resource, clientId, tokenSubjectType, adalUserInfo?.UniqueId, adalUserInfo?.DisplayableId)
 {
 }
        private void UpdateCachedMrrtRefreshTokens(AuthenticationResult result, string authority, string clientId, TokenSubjectType subjectType)
        {
            lock (cacheLock)
            {
                if (result.UserInfo != null && result.IsMultipleResourceRefreshToken)
                {
                    List<KeyValuePair<TokenCacheKey, AuthenticationResult>> mrrtItems =
                        this.QueryCache(authority, clientId, subjectType, result.UserInfo.UniqueId,
                            result.UserInfo.DisplayableId).Where(p => p.Value.IsMultipleResourceRefreshToken).ToList();

                    foreach (KeyValuePair<TokenCacheKey, AuthenticationResult> mrrtItem in mrrtItems)
                    {
                        mrrtItem.Value.RefreshToken = result.RefreshToken;
                    }
                }
            }
        }
Exemplo n.º 20
0
        internal void StoreToCache(AuthenticationResultEx result, string authority, string[] scope, string clientId,
            TokenSubjectType subjectType, CallState callState)
        {
            PlatformPlugin.Logger.Verbose(callState, "Storing token in the cache...");

            if (ADALScopeHelper.IsNullOrEmpty(scope) || ADALScopeHelper.CreateSetFromArray(scope).Contains("openid"))
            {
                scope = new[] {clientId};
            }

            string uniqueId = (result.Result.UserInfo != null) ? result.Result.UserInfo.UniqueId : null;
            string displayableId = (result.Result.UserInfo != null) ? result.Result.UserInfo.DisplayableId : null;

            this.OnBeforeWrite(new TokenCacheNotificationArgs
            {
                Scope = scope,
                ClientId = clientId,
                UniqueId = uniqueId,
                DisplayableId = displayableId
            });

            TokenCacheKey tokenCacheKey = new TokenCacheKey(authority, scope, clientId, subjectType,
                result.Result.UserInfo);
            // First identify all potential tokens.
            List<KeyValuePair<TokenCacheKey, AuthenticationResultEx>> items = this.QueryCache(authority, clientId,
                subjectType, uniqueId, displayableId);
            List<KeyValuePair<TokenCacheKey, AuthenticationResultEx>> itemsToRemove =
                items.Where(p => p.Key.ScopeIntersects(scope)).ToList();

            if (!itemsToRemove.Any())
            {
                this.tokenCacheDictionary[tokenCacheKey] = result;
                PlatformPlugin.Logger.Verbose(callState, "An item was stored in the cache");
            }
            else
            {
                //remove all intersections
                foreach (var itemToRemove in itemsToRemove)
                {
                    this.tokenCacheDictionary.Remove(itemToRemove);
                }

                this.tokenCacheDictionary[tokenCacheKey] = result;
                PlatformPlugin.Logger.Verbose(callState, "An item was updated in the cache");
            }

            this.UpdateCachedMrrtRefreshTokens(result, authority, clientId, subjectType);
            this.HasStateChanged = true;
        }
        protected AcquireTokenHandlerBase(Authenticator authenticator, TokenCache tokenCache, string resource, ClientKey clientKey, TokenSubjectType subjectType, bool callSync)
        {
            this.Authenticator = authenticator;
            this.CallState     = CreateCallState(this.Authenticator.CorrelationId, callSync);
            PlatformPlugin.Logger.Information(this.CallState, "=== Token Acquisition started");

            this.tokenCache = tokenCache;

            if (string.IsNullOrWhiteSpace(resource))
            {
                throw new ArgumentNullException("resource");
            }

            this.Resource         = (resource != NullResource) ? resource : null;
            this.ClientKey        = clientKey;
            this.TokenSubjectType = subjectType;

            this.LoadFromCache = (tokenCache != null);
            this.StoreToCache  = (tokenCache != null);
            this.SupportADFS   = false;
        }
        /// <summary>
        /// Generate a series of <see cref="TokenCacheKey"/> instances based on the given <paramref name="reference"/>
        /// instance, but change one property in each instance.
        /// </summary>
        private static IEnumerable <TokenCacheKey> ChangeEachProperty(TokenCacheKey reference, string differentString, TokenSubjectType differentSubjectType)
        {
            // Different authority
            yield return(new TokenCacheKey(differentString, reference.Resource, reference.ClientId, reference.TokenSubjectType, reference.UniqueId, reference.DisplayableId));

            // Different resource
            yield return(new TokenCacheKey(reference.Authority, differentString, reference.ClientId, reference.TokenSubjectType, reference.UniqueId, reference.DisplayableId));

            // Different client ID
            yield return(new TokenCacheKey(reference.Authority, reference.Resource, differentString, reference.TokenSubjectType, reference.UniqueId, reference.DisplayableId));

            // Different token subject type
            yield return(new TokenCacheKey(reference.Authority, reference.Resource, reference.ClientId, differentSubjectType, reference.UniqueId, reference.DisplayableId));

            // Different unique ID
            yield return(new TokenCacheKey(reference.Authority, reference.Resource, reference.ClientId, reference.TokenSubjectType, differentString, reference.DisplayableId));

            // Different displayable ID
            yield return(new TokenCacheKey(reference.Authority, reference.Resource, reference.ClientId, reference.TokenSubjectType, reference.UniqueId, differentString));
        }
Exemplo n.º 23
0
        private KeyValuePair<TokenCacheKey, AuthenticationResultEx>? LoadSingleItemFromCache(string authority,
            string[] scope, string clientId, TokenSubjectType subjectType, string uniqueId, string displayableId,
            CallState callState)
        {
            // First identify all potential tokens.
            List<KeyValuePair<TokenCacheKey, AuthenticationResultEx>> items = this.QueryCache(authority, clientId,
                subjectType, uniqueId, displayableId);

            //using ScopeContains because user could be accessing a subset of the scope.
            List<KeyValuePair<TokenCacheKey, AuthenticationResultEx>> resourceSpecificItems =
                items.Where(p => p.Key.ScopeContains(scope)).ToList();

            int resourceValuesCount = resourceSpecificItems.Count();
            KeyValuePair<TokenCacheKey, AuthenticationResultEx>? returnValue = null;
            switch (resourceValuesCount)
            {
                case 1:
                    PlatformPlugin.Logger.Information(callState,
                        "An item matching the requested scope set was found in the cache");
                    returnValue = resourceSpecificItems.First();
                    break;
                case 0:
                {
                    // There are no resource specific tokens.  Choose any of the MRRT tokens if there are any.
                    List<KeyValuePair<TokenCacheKey, AuthenticationResultEx>> mrrtItems =
                        items.Where(p => p.Value.IsMultipleResourceRefreshToken).ToList();

                    if (mrrtItems.Any())
                    {
                        returnValue = mrrtItems.First();
                        PlatformPlugin.Logger.Information(callState,
                            "A Multi Resource Refresh accessToken for a different resource was found which can be used");
                    }
                }
                    break;
                default:
                    throw new AdalException(AdalError.MultipleTokensMatched);
            }

            return returnValue;
        }
        internal void StoreToCache(AuthenticationResult result, string authority, string resource, string clientId, TokenSubjectType subjectType, CallState callState)
        {
            lock (cacheLock)
            {
                Logger.Verbose(callState, "Storing token in the cache...");

                string uniqueId = (result.UserInfo != null) ? result.UserInfo.UniqueId : null;
                string displayableId = (result.UserInfo != null) ? result.UserInfo.DisplayableId : null;

                this.OnBeforeWrite(new TokenCacheNotificationArgs
                {
                    Resource = resource,
                    ClientId = clientId,
                    UniqueId = uniqueId,
                    DisplayableId = displayableId
                });

                TokenCacheKey tokenCacheKey = new TokenCacheKey(authority, resource, clientId, subjectType,
                    result.UserInfo);
                this.tokenCacheDictionary[tokenCacheKey] = result;
                Logger.Verbose(callState, "An item was stored in the cache");
                this.UpdateCachedMrrtRefreshTokens(result, authority, clientId, subjectType);

                this.HasStateChanged = true;
            }
        }
        internal AuthenticationResult LoadFromCache(string authority, string resource, string clientId, TokenSubjectType subjectType, string uniqueId, string displayableId, CallState callState)
        {
            Logger.Verbose(callState, "Looking up cache for a token...");

            AuthenticationResult result = null;

            KeyValuePair <TokenCacheKey, AuthenticationResult>?kvp = this.LoadSingleItemFromCache(authority, resource, clientId, subjectType, uniqueId, displayableId, callState);

            if (kvp.HasValue)
            {
                TokenCacheKey cacheKey = kvp.Value.Key;
                result = kvp.Value.Value;
                bool tokenNearExpiry = (result.ExpiresOn <= DateTime.UtcNow + TimeSpan.FromMinutes(ExpirationMarginInMinutes));

                if (tokenNearExpiry)
                {
                    result.AccessToken = null;
                    Logger.Verbose(callState, "An expired or near expiry token was found in the cache");
                }
                else if (!cacheKey.ResourceEquals(resource))
                {
                    Logger.Verbose(callState,
                                   string.Format("Multi resource refresh token for resource '{0}' will be used to acquire token for '{1}'", cacheKey.Resource, resource));
                    var newResult = new AuthenticationResult(null, null, result.RefreshToken, DateTimeOffset.MinValue);
                    newResult.UpdateTenantAndUserInfo(result.TenantId, result.IdToken, result.UserInfo);
                    result = newResult;
                }
                else
                {
                    Logger.Verbose(callState, string.Format("{0} minutes left until token in cache expires", (result.ExpiresOn - DateTime.UtcNow).TotalMinutes));
                }

                if (result.AccessToken == null && result.RefreshToken == null)
                {
                    this.tokenCacheDictionary.Remove(cacheKey);
                    Logger.Information(callState, "An old item was removed from the cache");
                    this.HasStateChanged = true;
                    result = null;
                }

                if (result != null)
                {
                    Logger.Information(callState, "A matching item (access token or refresh token or both) was found in the cache");
                }
            }
            else
            {
                Logger.Information(callState, "No matching token was found in the cache");
            }

            return(result);
        }
        private KeyValuePair<TokenCacheKey, AuthenticationResult>? LoadSingleItemFromCache(string authority, string resource, string clientId, TokenSubjectType subjectType, string uniqueId, string displayableId, CallState callState)
        {
            lock (cacheLock)
            {
                // First identify all potential tokens.
                List<KeyValuePair<TokenCacheKey, AuthenticationResult>> items = this.QueryCache(authority, clientId,
                    subjectType, uniqueId, displayableId);

                List<KeyValuePair<TokenCacheKey, AuthenticationResult>> resourceSpecificItems =
                    items.Where(p => p.Key.ResourceEquals(resource)).ToList();

                int resourceValuesCount = resourceSpecificItems.Count();
                KeyValuePair<TokenCacheKey, AuthenticationResult>? returnValue = null;
                if (resourceValuesCount == 1)
                {
                    Logger.Information(callState, "An item matching the requested resource was found in the cache");
                    returnValue = resourceSpecificItems.First();
                }
                else if (resourceValuesCount == 0)
                {
                    // There are no resource specific tokens.  Choose any of the MRRT tokens if there are any.
                    List<KeyValuePair<TokenCacheKey, AuthenticationResult>> mrrtItems =
                        items.Where(p => p.Value.IsMultipleResourceRefreshToken).ToList();

                    if (mrrtItems.Any())
                    {
                        returnValue = mrrtItems.First();
                        Logger.Information(callState,
                            "A Multi Resource Refresh Token for a different resource was found which can be used");
                    }
                }
                else
                {
                    throw new AdalException(AdalError.MultipleTokensMatched);
                }

                return returnValue;
            }
        }
Exemplo n.º 27
0
        internal void StoreToCache(AuthenticationResult result, string authority, string resource, string clientId, TokenSubjectType subjectType)
        {
            string uniqueId      = (result.UserInfo != null) ? result.UserInfo.UniqueId : null;
            string displayableId = (result.UserInfo != null) ? result.UserInfo.DisplayableId : null;

            this.OnBeforeWrite(new TokenCacheNotificationArgs
            {
                Resource      = resource,
                ClientId      = clientId,
                UniqueId      = uniqueId,
                DisplayableId = displayableId
            });

            TokenCacheKey tokenCacheKey = new TokenCacheKey(authority, resource, clientId, subjectType, result.UserInfo);

            this.tokenCacheDictionary[tokenCacheKey] = result;
            this.UpdateCachedMrrtRefreshTokens(result, authority, clientId, subjectType);

            this.HasStateChanged = true;
        }
Exemplo n.º 28
0
 internal TokenCacheKey(string authority, string resource, string clientId, TokenSubjectType tokenSubjectType, UserInfo userInfo)
     : this(authority, resource, clientId, tokenSubjectType, (userInfo != null) ? userInfo.UniqueId : null, (userInfo != null) ? userInfo.DisplayableId : null)
 {
 }
Exemplo n.º 29
0
        private KeyValuePair <TokenCacheKey, AuthenticationResult>?LoadSingleItemFromCache(string authority, string resource, string clientId, TokenSubjectType subjectType, string uniqueId, string displayableId)
        {
            // First identify all potential tokens.
            List <KeyValuePair <TokenCacheKey, AuthenticationResult> > items = this.QueryCache(authority, clientId, subjectType, uniqueId, displayableId);

            List <KeyValuePair <TokenCacheKey, AuthenticationResult> > resourceSpecificItems =
                items.Where(p => p.Key.ResourceEquals(resource)).ToList();

            int resourceValuesCount = resourceSpecificItems.Count();
            KeyValuePair <TokenCacheKey, AuthenticationResult>?returnValue = null;

            if (resourceValuesCount == 1)
            {
                returnValue = resourceSpecificItems.First();
            }
            else if (resourceValuesCount == 0)
            {
                // There are no resource specific tokens.  Choose any of the MRRT tokens if there are any.
                List <KeyValuePair <TokenCacheKey, AuthenticationResult> > mrrtItems =
                    items.Where(p => p.Value.IsMultipleResourceRefreshToken).ToList();

                if (mrrtItems.Any())
                {
                    returnValue = mrrtItems.First();
                }
            }
            else
            {
                // There is more than one resource specific token.  It is
                // ambiguous which one to return so throw.
                throw new AdalException(AdalError.MultipleTokensMatched);
            }

            return(returnValue);
        }