public void ConstructorTests()
        {
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false,
                Guid.NewGuid());
            TokenCache cache = new TokenCache();
            AuthenticationRequestParameters parameters = new AuthenticationRequestParameters()
            {
                Authenticator = authenticator,
                ClientKey = new ClientKey(TestConstants.DefaultClientId),
                Policy = TestConstants.DefaultPolicy,
                RestrictToSingleUser = true,
                Scope = TestConstants.DefaultScope.ToArray(),
                TokenCache = cache
            };

            SilentRequest request = new SilentRequest(parameters, (string) null,
                new PlatformParameters(), false);
            Assert.IsNotNull(request);

            request = new SilentRequest(parameters, (User) null, new PlatformParameters(), false);
            Assert.IsNotNull(request);

            request = new SilentRequest(parameters, TestConstants.DefaultDisplayableId, new PlatformParameters(), false);
            Assert.IsNotNull(request);

            request = new SilentRequest(parameters, TestConstants.DefaultUniqueId, new PlatformParameters(), false);
            Assert.IsNotNull(request);

            request = new SilentRequest(parameters, TestConstants.DefaultUser, new PlatformParameters(), false);
            Assert.IsNotNull(request);
        }
 public static void ExpireCacheItems(TokenCache cache)
 {
     foreach (var value in cache.tokenCacheDictionary.Values)
     {
         value.Result.ExpiresOn = DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc);
     }
 }
        static TokenCache()
        {
            DefaultSharedUserTokenCache = new TokenCache
            {
                BeforeAccess = PlatformPlugin.TokenCachePlugin.BeforeAccess,
                AfterAccess = PlatformPlugin.TokenCachePlugin.AfterAccess
            };


            DefaultSharedAppTokenCache = new TokenCache
            {
                BeforeAccess = PlatformPlugin.TokenCachePlugin.BeforeAccess,
                AfterAccess = PlatformPlugin.TokenCachePlugin.AfterAccess
            };
        }
        public void MapToIdentifierNullInputTest()
        {
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false,
                Guid.NewGuid());
            TokenCache cache = new TokenCache();
            AuthenticationRequestParameters parameters = new AuthenticationRequestParameters()
            {
                Authenticator = authenticator,
                ClientKey = new ClientKey(TestConstants.DefaultClientId),
                Policy = TestConstants.DefaultPolicy,
                RestrictToSingleUser = true,
                Scope = TestConstants.DefaultScope.ToArray(),
                TokenCache = cache
            };

            SilentRequest request = new SilentRequest(parameters, (string)null,
                new PlatformParameters(), false);
            User user = request.MapIdentifierToUser(null);
            Assert.IsNull(user);
        }
        public static TokenCache CreateCacheWithItems()
        {
            TokenCache cache = new TokenCache();
            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.ScopeSet = TestConstants.DefaultScope;

            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            cache.tokenCacheDictionary[key] = ex;

            key = new TokenCacheKey(TestConstants.DefaultAuthorityGuestTenant,
                TestConstants.ScopeForAnotherResource, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId + "more", TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId + "more",
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.ScopeSet = TestConstants.ScopeForAnotherResource;
            ex.RefreshToken = "someRT";
            cache.tokenCacheDictionary[key] = ex;

            return cache;
        }
        public void LoadFromCacheExpiredToken()
        {
            TokenCache cache = new TokenCache();
            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(), new DateTimeOffset(DateTime.UtcNow));
            ex.RefreshToken = "someRT";
            cache.tokenCacheDictionary[key] = ex;

            AuthenticationResultEx resultEx = cache.LoadFromCache(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUser,
                TestConstants.DefaultPolicy, null);
            Assert.IsNotNull(resultEx);
            Assert.IsNotNull(resultEx.Result);
            Assert.IsNull(resultEx.Result.Token);
            Assert.AreEqual(resultEx.RefreshToken, "someRT");
        }
예제 #7
0
        // Gets an access token. First tries to get the access token from the token cache.
        // Using password (secret) to authenticate. Production apps should use a certificate.
        public async Task <string> GetUserAccessTokenAsync(string userId)
        {
            _userTokenCache = new SessionTokenCache(userId, _memoryCache).GetCacheInstance();

            var cca = new ConfidentialClientApplication(
                _appId,
                _redirectUri,
                _credential,
                _userTokenCache,
                null);

            if (!cca.Users.Any())
            {
                throw new ServiceException(new Error
                {
                    Code    = "TokenNotFound",
                    Message = "User not found in token cache. Maybe the server was restarted."
                });
            }

            try
            {
                var result = await cca.AcquireTokenSilentAsync(_userScopes, cca.Users.First());

                return(result.AccessToken);
            }

            // Unable to retrieve the access token silently.
            catch (Exception)
            {
                throw new ServiceException(new Error
                {
                    Code    = GraphErrorCode.AuthenticationFailure.ToString(),
                    Message = "Caller needs to authenticate. Unable to retrieve the access token silently."
                });
            }
        }
 internal virtual AuthenticationRequestParameters GetHandlerData(Authenticator authenticator, string[] scope, string policy, TokenCache cache)
 {
     return new AuthenticationRequestParameters
     {
         Authenticator = authenticator,
         Scope = scope,
         Policy = policy,
         RestrictToSingleUser = this.RestrictToSingleUser,
         TokenCache = cache
     };
 }
        public void NoCacheLookup()
        {
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false, Guid.NewGuid());
            TokenCache cache = new TokenCache();
            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3599)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            cache.tokenCacheDictionary[key] = ex;

            IWebUI ui = Substitute.For<IWebUI>();
            AuthorizationResult ar = new AuthorizationResult(AuthorizationStatus.Success,
                TestConstants.DefaultAuthorityHomeTenant + "?code=some-code");
            ui.AcquireAuthorizationAsync(Arg.Any<Uri>(), Arg.Any<Uri>(), Arg.Any<IDictionary<string, string>>(),
                Arg.Any<CallState>())
                .Returns(ar);

            MockHttpMessageHandler mockHandler = new MockHttpMessageHandler();
            mockHandler.Method = HttpMethod.Post;
            mockHandler.QueryParams = new Dictionary<string, string>() {{"p", "some-policy"}};

            mockHandler.ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage();
            HttpMessageHandlerFactory.MockHandler = mockHandler;

            AuthenticationRequestParameters parameters = new AuthenticationRequestParameters()
            {
                Authenticator = authenticator,
                ClientKey = new ClientKey(TestConstants.DefaultClientId),
                Policy = "some-policy",
                RestrictToSingleUser = TestConstants.DefaultRestrictToSingleUser,
                Scope = TestConstants.DefaultScope.ToArray(),
                TokenCache = cache
            };

            InteractiveRequest request = new InteractiveRequest(parameters,
                TestConstants.ScopeForAnotherResource.ToArray(),
                new Uri("some://uri"), new PlatformParameters(), TestConstants.DefaultDisplayableId,
                UiOptions.SelectAccount, "extra=qp", ui);
            Task<AuthenticationResult> task = request.RunAsync();
            task.Wait();
            AuthenticationResult result = task.Result;
            Assert.IsNotNull(result);
            Assert.AreEqual(2, cache.Count);
            Assert.AreEqual(result.Token, "some-access-token");

            //both cache entry authorities are TestConstants.DefaultAuthorityHomeTenant
            foreach (var item in cache.ReadItems(TestConstants.DefaultClientId))
            {
                Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, item.Authority);
            }
        }
        public void LoadSingleItemFromCacheCrossTenantLookupTest()
        {
            var tokenCache = new TokenCache();

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            tokenCache.tokenCacheDictionary[key] = ex;

            User user = TestConstants.DefaultUser;
            user.DisplayableId = null;
            user.UniqueId = null;

            //cross-tenant works by default. search cache using non-existant authority
            //using root id. Code will find multiple results with the same root id. it can return any.
            KeyValuePair<TokenCacheKey, AuthenticationResultEx>? item =
                tokenCache.LoadSingleItemFromCache(TestConstants.DefaultAuthorityGuestTenant + "non-existant",
                    new HashSet<string>(new[] {"scope1", "random-scope"}),
                    TestConstants.DefaultClientId, user, TestConstants.DefaultPolicy, null);
            Assert.IsNotNull(item);
            key = item.Value.Key;
            AuthenticationResultEx resultEx = item.Value.Value;

            Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, key.Authority);
            Assert.AreEqual(TestConstants.DefaultScope, key.Scope);
            Assert.AreEqual(TestConstants.DefaultClientId, key.ClientId);
            Assert.AreEqual(TestConstants.DefaultUniqueId, key.UniqueId);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, key.DisplayableId);
            Assert.AreEqual(TestConstants.DefaultHomeObjectId, key.HomeObjectId);
            Assert.AreEqual(TestConstants.DefaultPolicy, key.Policy);
            Assert.AreEqual(key.ToString(), resultEx.Result.Token);
        }
  /// <summary>
  /// 
  /// </summary>
  /// <param name="clientId"></param>
  /// <param name="redirectUri"></param>
  /// <param name="clientCredential"></param>
  /// <param name="userTokenCache"></param>
  public ConfidentialClientApplication(string clientId, string redirectUri,
     ClientCredential clientCredential, TokenCache userTokenCache):this(DefaultAuthority, clientId, redirectUri, clientCredential, userTokenCache)
 {
 }
        private static void VerifyCacheItems(TokenCache cache, int expectedCount, TokenCacheKey firstKey,
            TokenCacheKey secondKey)
        {
            var items = cache.ReadItems(TestConstants.DefaultClientId).ToList();
            Assert.AreEqual(expectedCount, items.Count);

            if (firstKey != null)
            {
                Assert.IsTrue(AreEqual(items[0], firstKey) || AreEqual(items[0], secondKey));
            }

            if (secondKey != null)
            {
                Assert.IsTrue(AreEqual(items[1], firstKey) || AreEqual(items[1], secondKey));
            }
        }
 private static void VerifyCacheItems(TokenCache cache, int expectedCount, TokenCacheKey firstKey)
 {
     VerifyCacheItems(cache, expectedCount, firstKey, null);
 }
 private static void VerifyCacheItemCount(TokenCache cache, int expectedCount)
 {
     Assert.AreEqual(cache.Count, expectedCount);
 }
        public void StoreToCacheUniqueScopesTest()
        {
            var tokenCache = new TokenCache();
            tokenCache.AfterAccess = null;
            tokenCache.BeforeAccess = null;
            tokenCache.BeforeWrite = null;
            tokenCache = TokenCacheHelper.CreateCacheWithItems();

            //save result with intersecting scopes
            var result = new AuthenticationResult("Bearer", "some-access-token",
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)))
            {
                User =
                    new User
                    {
                        UniqueId = TestConstants.DefaultUniqueId,
                        DisplayableId = TestConstants.DefaultDisplayableId
                    },
                ScopeSet = new HashSet<string>(new string[] { "r1/scope5", "r1/scope7" })
            };

            AuthenticationResultEx resultEx = new AuthenticationResultEx
            {
                Result = result,
                RefreshToken = "someRT"
            };

            tokenCache.StoreToCache(resultEx, TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultClientId,
                TestConstants.DefaultPolicy, TestConstants.DefaultRestrictToSingleUser, null);

            Assert.AreEqual(3, tokenCache.Count);
            AuthenticationResultEx resultExOut =
                tokenCache.LoadFromCache(TestConstants.DefaultAuthorityHomeTenant,
                    new HashSet<string>(new string[] {"r1/scope5"}), TestConstants.DefaultClientId,
                    null, TestConstants.DefaultPolicy, null);

            Assert.AreEqual(resultEx.RefreshToken, resultExOut.RefreshToken);
            Assert.AreEqual(resultEx.Result.Token, resultExOut.Result.Token);
            Assert.AreEqual(resultEx.Result.TokenType, resultExOut.Result.TokenType);
            Assert.AreEqual(resultEx.Result.User.UniqueId, resultExOut.Result.User.UniqueId);
            Assert.AreEqual(resultEx.Result.User.DisplayableId, resultExOut.Result.User.DisplayableId);
            Assert.AreEqual(resultEx.Result.User.HomeObjectId, resultExOut.Result.User.HomeObjectId);
        }
        public void StoreToCacheNewUserRestrictToSingleUserTrueTest()
        {
            var tokenCache = new TokenCache();

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            tokenCache.tokenCacheDictionary[key] = ex;
            
            var result = new AuthenticationResult("Bearer", "some-access-token",
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)))
            {
                User =
                    new User
                    {
                        UniqueId = TestConstants.DefaultUniqueId+"more",
                        DisplayableId = TestConstants.DefaultDisplayableId
                    },
                ScopeSet = new HashSet<string>(new string[] { "r1/scope5", "r1/scope7" })
            };

            AuthenticationResultEx resultEx = new AuthenticationResultEx
            {
                Result = result,
                RefreshToken = "someRT"
            };
            try
            {
                tokenCache.StoreToCache(resultEx, TestConstants.DefaultAuthorityGuestTenant, TestConstants.DefaultClientId,
                    TestConstants.DefaultPolicy, true, null);
                Assert.Fail("MsalException should be thrown here");
            }
            catch (MsalException me)
            {
                Assert.AreEqual(MsalError.InvalidCacheOperation, me.ErrorCode);
                Assert.AreEqual("Cannot add more than 1 user with a different unique id when RestrictToSingleUser is set to TRUE.", me.Message);
            }
        }
        public void DeserializationNullAndEmptyBlobTest()
        {
            var tokenCache = new TokenCache(null);
            Assert.IsNotNull(tokenCache);
            Assert.IsNotNull(tokenCache.Count);

            tokenCache = new TokenCache(new byte[] {});
            Assert.IsNotNull(tokenCache);
            Assert.IsNotNull(tokenCache.Count);
        }
        public void SerializationDeserializationTest()
        {
            TokenCache tokenCache1 = TokenCacheHelper.CreateCacheWithItems();
            byte[] cacheBytes = tokenCache1.Serialize();
            Assert.IsNotNull(cacheBytes);
            Assert.IsTrue(cacheBytes.Length > 0);

            var tokenCache2 = new TokenCache(cacheBytes);
            Assert.AreEqual(tokenCache1.Count, tokenCache2.Count);

            foreach (TokenCacheKey key in tokenCache1.tokenCacheDictionary.Keys)
            {
                Assert.IsTrue(tokenCache2.tokenCacheDictionary.ContainsKey(key));
                AuthenticationResultEx result1 = tokenCache1.tokenCacheDictionary[key];
                AuthenticationResultEx result2 = tokenCache2.tokenCacheDictionary[key];

                Assert.AreEqual(result1.RefreshToken, result2.RefreshToken);
                Assert.AreEqual(result1.Exception, result2.Exception);
                Assert.AreEqual(result1.IsMultipleScopeRefreshToken, result2.IsMultipleScopeRefreshToken);
                Assert.AreEqual(result1.Result.ScopeSet.Count, result2.Result.ScopeSet.Count);
                foreach (var result1Scope in result1.Result.ScopeSet)
                {
                    Assert.IsTrue(result2.Result.ScopeSet.Contains(result1Scope));
                }

                Assert.AreEqual(result1.Result.Token, result2.Result.Token);
                Assert.AreEqual(result1.Result.FamilyId, result2.Result.FamilyId);
                Assert.AreEqual(result1.Result.TokenType, result2.Result.TokenType);
                Assert.AreEqual(result1.Result.IdToken, result2.Result.IdToken);
                Assert.AreEqual(result1.Result.User.DisplayableId, result2.Result.User.DisplayableId);
                Assert.AreEqual(result1.Result.User.UniqueId, result2.Result.User.UniqueId);
                Assert.AreEqual(result1.Result.User.HomeObjectId, result2.Result.User.HomeObjectId);
                Assert.AreEqual(result1.Result.User.IdentityProvider, result2.Result.User.IdentityProvider);
                Assert.IsTrue(AreDateTimeOffsetsEqual(result1.Result.ExpiresOn, result2.Result.ExpiresOn));
            }
        }
        public void SilentRefreshFailedNoCacheItemFoundTest()
        {
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false,
                Guid.NewGuid());
            TokenCache cache = new TokenCache();

            AuthenticationRequestParameters parameters = new AuthenticationRequestParameters()
            {
                Authenticator = authenticator,
                ClientKey = new ClientKey(TestConstants.DefaultClientId),
                Policy = TestConstants.DefaultPolicy,
                RestrictToSingleUser = TestConstants.DefaultRestrictToSingleUser,
                Scope = new[] { "some-scope1", "some-scope2" },
                TokenCache = cache
            };

            HttpMessageHandlerFactory.MockHandler = new MockHttpMessageHandler()
            {
                Method = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage()
            };

            try
            {
                SilentRequest request = new SilentRequest(parameters, (string) null,
                    new PlatformParameters(), false);
                Task<AuthenticationResult> task = request.RunAsync();
                var authenticationResult = task.Result;
                Assert.Fail("MsalSilentTokenAcquisitionException should be thrown here");
            }
            catch (AggregateException ae)
            {
                Assert.IsTrue(ae.InnerException is MsalSilentTokenAcquisitionException);
            }
        }
        public void LoadSingleItemFromCacheNullUserSingleUniqueIdInCacheTest()
        {
            TokenCache cache = new TokenCache();

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            cache.tokenCacheDictionary[key] = ex;

            KeyValuePair<TokenCacheKey, AuthenticationResultEx>? item =
                cache.LoadSingleItemFromCache(TestConstants.DefaultAuthorityCommonTenant,
                    TestConstants.DefaultScope, TestConstants.DefaultClientId,
                    null,
                    TestConstants.DefaultPolicy, null);
            Assert.IsNotNull(item);

            Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, key.Authority);
            Assert.AreEqual(TestConstants.DefaultScope, key.Scope);
            Assert.AreEqual(TestConstants.DefaultClientId, key.ClientId);
            Assert.AreEqual(TestConstants.DefaultUniqueId, key.UniqueId);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, key.DisplayableId);
            Assert.AreEqual(TestConstants.DefaultHomeObjectId, key.HomeObjectId);
            Assert.AreEqual(TestConstants.DefaultPolicy, key.Policy);
        }
 private static void AddToDictionary(TokenCache tokenCache, TokenCacheKey key, AuthenticationResultEx value)
 {
     tokenCache.OnBeforeAccess(new TokenCacheNotificationArgs {TokenCache = tokenCache});
     tokenCache.OnBeforeWrite(new TokenCacheNotificationArgs {TokenCache = tokenCache});
     tokenCache.tokenCacheDictionary.Add(key, value);
     tokenCache.HasStateChanged = true;
     tokenCache.OnAfterAccess(new TokenCacheNotificationArgs {TokenCache = tokenCache});
 }
        internal override AuthenticationRequestParameters GetHandlerData(Authenticator authenticator, string[] scope, string policy,
            TokenCache cache)
        {
            AuthenticationRequestParameters parameters = base.GetHandlerData(authenticator, scope, policy, cache);
            parameters.ClientKey = new ClientKey(this.ClientId, this.ClientCredential, authenticator);

            return parameters;
        }
        public void LoadFromCacheNullUserSingleEntry()
        {
            var tokenCache = new TokenCache();
            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            tokenCache.tokenCacheDictionary[key] = ex;

            AuthenticationResultEx resultEx = tokenCache.LoadFromCache(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope,
                TestConstants.DefaultClientId, null,
                TestConstants.DefaultPolicy, null);
            Assert.IsNotNull(resultEx);
            Assert.IsNotNull(resultEx.Result);
            Assert.IsNotNull(resultEx.Result.Token);
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="authority"></param>
 /// <param name="clientId"></param>
 /// <param name="redirectUri"></param>
 /// <param name="clientCredential"></param>
 /// <param name="userTokenCache"></param>
 public ConfidentialClientApplication(string authority, string clientId, string redirectUri, ClientCredential clientCredential, TokenCache userTokenCache) :base(authority, clientId, redirectUri, true)
 {
     this.ClientCredential = clientCredential;
     this.UserTokenCache = userTokenCache;
     this.AppTokenCache = TokenCache.DefaultSharedAppTokenCache;
 }
예제 #25
0
        public static AuthResult FromMSALAuthenticationResult(Microsoft.Identity.Client.AuthenticationResult authResult, Microsoft.Identity.Client.TokenCache tokenCache)
        {
            var result = new AuthResult
            {
                AccessToken       = authResult.AccessToken,
                UserName          = $"{authResult.User.Name}",
                UserUniqueId      = authResult.User.Identifier,
                ExpiresOnUtcTicks = authResult.ExpiresOn.UtcTicks,
                TokenCache        = tokenCache.Serialize()
            };

            return(result);
        }
        private static bool RemoveFromDictionary(TokenCache tokenCache, TokenCacheKey key)
        {
            tokenCache.OnBeforeAccess(new TokenCacheNotificationArgs {TokenCache = tokenCache});
            tokenCache.OnBeforeWrite(new TokenCacheNotificationArgs {TokenCache = tokenCache});
            bool result = tokenCache.tokenCacheDictionary.Remove(key);
            tokenCache.HasStateChanged = true;
            tokenCache.OnAfterAccess(new TokenCacheNotificationArgs {TokenCache = tokenCache});

            return result;
        }
        public void ActAsCurrentUserNoSsoHeaderForLoginHintOnlyTest()
        {
            //this test validates that no SSO header is added when developer passes only login hint and UiOption.ActAsCurrentUser
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false, Guid.NewGuid());
            TokenCache cache = new TokenCache();
            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3599)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            cache.tokenCacheDictionary[key] = ex;

            MockWebUI webUi = new MockWebUI();
            webUi.MockResult = new AuthorizationResult(AuthorizationStatus.Success,
                TestConstants.DefaultAuthorityHomeTenant + "?code=some-code");

            AuthenticationRequestParameters parameters = new AuthenticationRequestParameters()
            {
                Authenticator = authenticator,
                ClientKey = new ClientKey(TestConstants.DefaultClientId),
                Policy = TestConstants.DefaultPolicy,
                RestrictToSingleUser = TestConstants.DefaultRestrictToSingleUser,
                Scope = TestConstants.DefaultScope.ToArray(),
                TokenCache = cache
            };

            InteractiveRequest request = new InteractiveRequest(parameters,
                TestConstants.ScopeForAnotherResource.ToArray(),
                new Uri("some://uri"), new PlatformParameters(),
                ex.Result.User, UiOptions.ActAsCurrentUser, "extra=qp", webUi);
            request.PreRunAsync().Wait();
            request.PreTokenRequest().Wait();
        }