public void AcquireTokenSilentScopeAndUserOverloadWithNoMatchingScopesInCacheTest()
        {
            // this test ensures that the API can
            // get authority (if unique) from the cache entries where scope does not match.
            // it should only happen for case where no authority is passed.

            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                                              .WithHttpManager(httpManager)
                                              .BuildConcrete();

                TokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor);
                var cacheAccess = app.UserTokenCache.RecordAccess();

                Task <AuthenticationResult> task = app
                                                   .AcquireTokenSilent(
                    TestConstants.s_scopeForAnotherResource.ToArray(),
                    new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null))
                                                   .ExecuteAsync(CancellationToken.None);

                AuthenticationResult result = task.Result;
                Assert.IsNotNull(result);
                Assert.AreEqual(TestConstants.DisplayableId, result.Account.Username);
                Assert.AreEqual(TestConstants.s_scopeForAnotherResource.AsSingleString(), result.Scopes.AsSingleString());
                Assert.AreEqual(2, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count());
                cacheAccess.AssertAccessCounts(1, 0);
            }
        }
Beispiel #2
0
        public async Task AfterAccess_Is_Called_When_BeforeAceess_Throws_Async()
        {
            using (var harness = CreateTestHarness())
            {
                var pca = PublicClientApplicationBuilder
                          .Create(TestConstants.ClientId)
                          .WithHttpManager(harness.HttpManager)
                          .BuildConcrete();

                TokenCacheHelper.PopulateCache(pca.UserTokenCacheInternal.Accessor, addSecondAt: false);
                var account = (await pca.GetAccountsAsync().ConfigureAwait(false)).First();

                // All these actions trigger a reloading of the cache
                await RunAfterAccessFailureAsync(pca, () => pca.GetAccountsAsync()).ConfigureAwait(false);
                await RunAfterAccessFailureAsync(pca,
                                                 () => pca.AcquireTokenSilent(new[] { "User.Read" }, account).ExecuteAsync())
                .ConfigureAwait(false);
                await RunAfterAccessFailureAsync(pca, () => pca.RemoveAsync(account)).ConfigureAwait(false);

                // AcquireTokenInteractive will save a token to the cache, but needs more setup
                harness.HttpManager.AddInstanceDiscoveryMockHandler();
                harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(TestConstants.AuthorityCommonTenant);

                pca.ServiceBundle.ConfigureMockWebUI();

                await RunAfterAccessFailureAsync(pca, () =>
                                                 pca.AcquireTokenInteractive(new[] { "User.Read" }).ExecuteAsync())
                .ConfigureAwait(false);
            }
        }
Beispiel #3
0
        public async Task AcquireTokenSilent_LoginHintAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(TestConstants.AuthorityTestTenant), true)
                                              .WithHttpManager(httpManager)
                                              .WithTelemetry(new TraceTelemetryConfig())
                                              .BuildConcrete();
                var tokenCacheHelper = new TokenCacheHelper();
                tokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor);
                var cacheAccess = app.UserTokenCache.RecordAccess();

                AuthenticationResult result = await app.AcquireTokenSilent(
                    TestConstants.s_scope.ToArray(),
                    TestConstants.DisplayableId)
                                              .WithAuthority(app.Authority, false)
                                              .ExecuteAsync()
                                              .ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.AreEqual(TestConstants.DisplayableId, result.Account.Username);
                Assert.AreEqual(TestConstants.s_scope.AsSingleString(), result.Scopes.AsSingleString());
                cacheAccess.AssertAccessCounts(1, 0);
            }
        }
Beispiel #4
0
        public void ExpiredTokenRefreshFlowTest()
        {
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false,
                                                            Guid.NewGuid());
            TokenCache cache = TokenCacheHelper.CreateCacheWithItems();

            HandlerData data = new HandlerData()
            {
                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()
            };

            AcquireTokenSilentHandler handler = new AcquireTokenSilentHandler(data, (string)null,
                                                                              new PlatformParameters(), false);
            Task <AuthenticationResult> task   = handler.RunAsync();
            AuthenticationResult        result = task.Result;

            Assert.IsNotNull(result);
            Assert.AreEqual("some-access-token", result.Token);
            Assert.AreEqual("some-scope1 some-scope2", result.Scope.AsSingleString());
        }
Beispiel #5
0
        public void ForceRefreshParameterFalseTestAsync()
        {
            var cache = new TokenCache();

            TokenCacheHelper.PopulateCache(cache.TokenCacheAccessor);

            var authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false).CanonicalAuthority;
            var app       = new ConfidentialClientApplication(TestConstants.ClientId, authority,
                                                              TestConstants.RedirectUri, new ClientCredential(TestConstants.ClientSecret),
                                                              null, cache)
            {
                ValidateAuthority = false
            };

            var accessTokens       = cache.GetAllAccessTokensForClient(new RequestContext(Guid.NewGuid(), null));
            var accessTokenInCache = accessTokens.Where(
                item =>
                item.ScopeSet.ScopeContains(TestConstants.Scope))
                                     .ToList()
                                     .FirstOrDefault();

            //add mock to fail in case of network call
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                ExceptionToThrow = new AssertFailedException("Unexpected Network Call")
            });

            var task   = app.AcquireTokenForClientAsync(TestConstants.Scope, false);
            var result = task.Result;

            Assert.AreEqual(accessTokenInCache?.AccessToken, result.AccessToken);
        }
Beispiel #6
0
        /*
         * Callback function when an authorization code is received
         */
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            // Extract the code from the response notification
            string code = notification.Code;

            // Extract signed in user id
            string signedInUserID = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

            // MSAL v3 confidential application creation
            IConfidentialClientApplication cca = ConfidentialClientApplicationBuilder.Create(ClientId)
                                                 .WithB2CAuthority(Authority)
                                                 .WithClientSecret(ClientSecret)
                                                 .WithRedirectUri(RedirectUri)
                                                 .Build();

            // Enable encrypted persistence to local file for tokens
            TokenCacheHelper.EnableSerialization(cca.UserTokenCache);

            try
            {
                // MSAL v3 get accesstoken by authorization code
                AuthenticationResult result = await cca.AcquireTokenByAuthorizationCode(Scopes, code).ExecuteAsync();
            }
            catch (Exception ex)
            {
                //TODO: Handle
                throw;
            }
        }
        public async Task AcquireTokenByOboAccessTokenExpiredRefreshTokenAvailableAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();

                AddMockHandlerAadSuccess(httpManager, TestConstants.AuthorityCommonTenant);

                var cca = ConfidentialClientApplicationBuilder
                          .Create(TestConstants.ClientId)
                          .WithClientSecret(TestConstants.ClientSecret)
                          .WithAuthority(TestConstants.AuthorityCommonTenant)
                          .WithHttpManager(httpManager)
                          .BuildConcrete();

                UserAssertion userAssertion = new UserAssertion(TestConstants.DefaultAccessToken);
                var           result        = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.AreEqual("some-access-token", result.AccessToken);

                //Expire access tokens
                TokenCacheHelper.ExpireAccessTokens(cca.UserTokenCacheInternal);

                MockHttpMessageHandler mockTokenRequestHttpHandlerRefresh = AddMockHandlerAadSuccess(httpManager, TestConstants.AuthorityCommonTenant);
                mockTokenRequestHttpHandlerRefresh.ExpectedPostData = new Dictionary <string, string> {
                    { "grant_type", "refresh_token" }
                };

                result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.AreEqual("some-access-token", result.AccessToken);
            }
        }
Beispiel #8
0
        /// <summary>
        /// Retrieves an access token for the specified scopes.
        /// </summary>
        private async Task <string> GetAccessTokenAsync(params string[] scopes)
        {
            string signedInUserID = User.GetId();

            // MSAL v3 confidential application creation
            IConfidentialClientApplication cca = ConfidentialClientApplicationBuilder.Create(Startup.ClientId)
                                                 .WithB2CAuthority(Startup.Authority)
                                                 .WithClientSecret(Startup.ClientSecret)
                                                 .WithRedirectUri(Startup.RedirectUri)
                                                 .Build();

            // Enable encrypted persistence to local file for tokens
            TokenCacheHelper.EnableSerialization(cca.UserTokenCache);
            IEnumerable <IAccount> accounts = await cca.GetAccountsAsync();

            IAccount account = accounts.FirstOrDefault(acc => acc.HomeAccountId.Identifier.StartsWith(signedInUserID));

            if (account == null)
            {
                throw new Exception("The account is NULL.  Please clear your cookies and try again.  Specifically delete cookies for 'login.microsoftonline.com'.  See this GitHub issue for more details: https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi/issues/9");
            }

            AuthenticationResult result = await cca.AcquireTokenSilent(Startup.Scopes, account)
                                          .WithB2CAuthority(Startup.Authority)
                                          .ExecuteAsync();

            return(result.AccessToken);
        }
Beispiel #9
0
        [TestCategory(TestCategories.Regression)] //https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/2706
        public async Task NullAndIosBroker_RemoveAccounts_Async(Type brokerType)
        {
            using (var harness = CreateTestHarness())
            {
                var broker = CreateBroker(brokerType);

                var builder = PublicClientApplicationBuilder
                              .Create(TestConstants.ClientId)
                              .WithHttpManager(harness.HttpManager);

                builder.Config.BrokerCreatorFunc = (parent, config, logger) => { return(broker); };

                var app = builder.WithBroker(true).BuildConcrete();

                TokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor);

                // Act
                var accounts = await app.GetAccountsAsync().ConfigureAwait(false);

                await app.RemoveAsync(accounts.Single()).ConfigureAwait(false);

                var accounts2 = await app.GetAccountsAsync().ConfigureAwait(false);

                // Assert
                Assert.AreEqual(1, accounts.Count());
                Assert.IsFalse(accounts2.Any());
            }
        }
Beispiel #10
0
 public async Task Logout()
 {
     TokenCacheHelper.Clear();
     _graphClient = null;
     await _publicClientApp.RemoveAsync(Account)
     .ConfigureAwait(false);
 }
        public void AcquireTokenSilentServiceErrorTest()
        {
            PublicClientApplication app = new PublicClientApplication(TestConstants.DefaultClientId);

            app.UserTokenCache = TokenCacheHelper.CreateCacheWithItems();

            MockHttpMessageHandler mockHandler = new MockHttpMessageHandler();

            mockHandler.Method                    = HttpMethod.Post;
            mockHandler.ResponseMessage           = MockHelpers.CreateInvalidGrantTokenResponseMessage();
            HttpMessageHandlerFactory.MockHandler = mockHandler;
            try
            {
                Task <AuthenticationResult> task   = app.AcquireTokenSilentAsync(TestConstants.ScopeForAnotherResource.ToArray(), TestConstants.DefaultUniqueId);
                AuthenticationResult        result = task.Result;
                Assert.Fail("AdalSilentTokenAcquisitionException was expected");
            }
            catch (AggregateException ex)
            {
                Assert.IsNotNull(ex.InnerException);

                Assert.IsTrue(ex.InnerException is MsalSilentTokenAcquisitionException);
                var msalExc = (MsalSilentTokenAcquisitionException)ex.InnerException;
                Assert.AreEqual(MsalError.FailedToAcquireTokenSilently, msalExc.ErrorCode);
                Assert.IsNotNull(msalExc.InnerException, "MsalSilentTokenAcquisitionException inner exception is null");
                Assert.AreEqual(((MsalException)msalExc.InnerException).ErrorCode, "invalid_grant");
            }
        }
        public void GetTokenTest()
        {
            var           key    = new Uri("http://www.contoso.com/");
            SecurityToken actual = TokenCacheHelper.GetToken(key);

            Assert.IsNull(actual);
        }
Beispiel #13
0
 public DriveAccountService(SiteContext siteContext)
 {
     if (Configuration.Type == Configuration.OfficeType.China)
     {
         app = ConfidentialClientApplicationBuilder
               .Create(Configuration.ClientId)
               .WithClientSecret(Configuration.ClientSecret)
               .WithRedirectUri(Configuration.BaseUri + "/api/admin/bind/new")
               .WithAuthority(AzureCloudInstance.AzureChina, "common")
               .Build();
     }
     else
     {
         app = ConfidentialClientApplicationBuilder
               .Create(Configuration.ClientId)
               .WithClientSecret(Configuration.ClientSecret)
               .WithRedirectUri(Configuration.BaseUri + "/api/admin/bind/new")
               .WithAuthority(AzureCloudInstance.AzurePublic, "common")
               .Build();
     }
     //缓存Token
     TokenCacheHelper.EnableSerialization(app.UserTokenCache);
     //这里要传入一个 Scope 否则默认使用 https://graph.microsoft.com/.default
     //而导致无法使用世纪互联版本
     authProvider = new AuthorizationCodeProvider(app, Configuration.Scopes);
     //获取Token
     if (File.Exists(TokenCacheHelper.CacheFilePath))
     {
         authorizeResult = authProvider.ClientApplication.AcquireTokenSilent(Configuration.Scopes, Configuration.AccountName).ExecuteAsync().Result;
         //Debug.WriteLine(authorizeResult.AccessToken);
     }
     //启用代理
     if (!string.IsNullOrEmpty(Configuration.Proxy))
     {
         // Configure your proxy
         var httpClientHandler = new HttpClientHandler
         {
             Proxy = new WebProxy(Configuration.Proxy),
             UseDefaultCredentials = true
         };
         var httpProvider = new Microsoft.Graph.HttpProvider(httpClientHandler, false)
         {
             OverallTimeout = TimeSpan.FromSeconds(10)
         };
         Graph = new Microsoft.Graph.GraphServiceClient($"{Configuration.GraphApi}/v1.0", authProvider, httpProvider);
     }
     else
     {
         Graph = new Microsoft.Graph.GraphServiceClient($"{Configuration.GraphApi}/v1.0", authProvider);
     }
     this.SiteContext = siteContext;
     //定时更新Token
     Timer timer = new Timer(o =>
     {
         if (File.Exists(TokenCacheHelper.CacheFilePath))
         {
             authorizeResult = authProvider.ClientApplication.AcquireTokenSilent(Configuration.Scopes, Configuration.AccountName).ExecuteAsync().Result;
         }
     }, null, TimeSpan.FromSeconds(0), TimeSpan.FromHours(1));
 }
Beispiel #14
0
        public void FindAccessToken_ScopeCaseInsensitive()
        {
            var tokenCache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            TokenCacheHelper.PopulateCache(tokenCache.TokenCacheAccessor);

            var param = new AuthenticationRequestParameters()
            {
                RequestContext = new RequestContext(Guid.Empty, null),
                ClientId       = TestConstants.ClientId,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                Scope          = new SortedSet <string>(),
                User           = TestConstants.User
            };

            var scopeInCache = TestConstants.Scope.FirstOrDefault();

            var upperCaseScope = scopeInCache.ToUpper();

            param.Scope.Add(upperCaseScope);

            var item = tokenCache.FindAccessToken(param);

            Assert.IsNotNull(item);
            Assert.IsTrue(item.ScopeSet.Contains(scopeInCache));
        }
Beispiel #15
0
        public void AcquireTokenSilentCacheOnlyLookupTest()
        {
            PublicClientApplication app =
                new PublicClientApplication(TestConstants.ClientId, TestConstants.AuthorityHomeTenant)
            {
                ValidateAuthority = false
            };

            cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            app.UserTokenCache = cache;
            TokenCacheHelper.PopulateCache(cache.TokenCacheAccessor);
            cache.TokenCacheAccessor.AccessTokenCacheDictionary.Remove(new AccessTokenCacheKey(
                                                                           TestConstants.AuthorityGuestTenant,
                                                                           TestConstants.ScopeForAnotherResource, TestConstants.ClientId,
                                                                           TestConstants.UserIdentifier).ToString());

            Task <AuthenticationResult> task = app.AcquireTokenSilentAsync(TestConstants.Scope.ToArray(), new User()
            {
                DisplayableId = TestConstants.DisplayableId,
                Identifier    = TestConstants.UserIdentifier,
            }, app.Authority, false);

            AuthenticationResult result = task.Result;

            Assert.IsNotNull(result);
            Assert.AreEqual(TestConstants.DisplayableId, result.User.DisplayableId);
            Assert.AreEqual(TestConstants.Scope.AsSingleString(), result.Scopes.AsSingleString());
            Assert.IsNotNull(_myReceiver.EventsReceived.Find(anEvent =>  // Expect finding such an event
                                                             anEvent[EventBase.EventNameKey].EndsWith("api_event") && anEvent[ApiEvent.WasSuccessfulKey] == "true" &&
                                                             anEvent[ApiEvent.ApiIdKey] == "31"));
        }
Beispiel #16
0
 static App()
 {
     _clientApp = PublicClientApplicationBuilder.Create(ClientId)
                  .WithAuthority(AzureCloudInstance.AzurePublic, Tenant)
                  .Build();
     TokenCacheHelper.EnableSerialization(_clientApp.UserTokenCache);
 }
Beispiel #17
0
        public async Task AcquireTokenSilent_BypassesCacheForAccessTokens_IfClaimsUsed_Async()
        {
            using (var harness = CreateTestHarness())
            {
                Trace.WriteLine("1. Setup an app with a token cache with a valid AT");
                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithHttpManager(harness.HttpManager)
                                              .BuildConcrete();


                TokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor, addSecondAt: false);

                Trace.WriteLine("2. Silent Request without claims returns the AT from the cache");
                var account = (await app.GetAccountsAsync().ConfigureAwait(false)).Single();
                var result  = await app.AcquireTokenSilent(TestConstants.s_scope, account)
                              .ExecuteAsync()
                              .ConfigureAwait(false);

                Assert.IsNotNull(result, "A result is obtained from the cache, i.e. without HTTP calls");

                Trace.WriteLine("3. Silent Request + WithClaims does not return an AT from the cache");
                harness.HttpManager.AddInstanceDiscoveryMockHandler(TestConstants.AuthorityUtidTenant);
                harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(TestConstants.AuthorityUtidTenant);

                result = await app.AcquireTokenSilent(TestConstants.s_scope, account)
                         .WithClaims(TestConstants.Claims)
                         .ExecuteAsync()
                         .ConfigureAwait(false);

                Assert.IsNotNull(result, "An access token is no longer obtained from the cache. The RT is used to get one from the STS.");
            }
        }
Beispiel #18
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var scopes = new string[] { "https://admin.services.crm.dynamics.com/user_impersonation", "offline_access" };

            if (req.Method == "POST" && req.Form.ContainsKey("code"))
            {
                var code = req.Form["code"].FirstOrDefault();

                var app = ConfidentialClientApplicationBuilder.Create(_settings.ClientId)
                          .WithClientSecret(_settings.ClientSecret)
                          .WithTenantId(_settings.Tenant)
                          .WithRedirectUri(req.GetDisplayUrl())
                          .Build();

                var cache = new TokenCacheHelper(AzureApp.CacheFileDir);
                cache.EnableSerialization(app.UserTokenCache);

                _ = await app.AcquireTokenByAuthorizationCode(new string[] { $"{_settings.DynamicsUrl}/user_impersonation" }, code).ExecuteAsync();

                return(new OkObjectResult("The app is authorized to perform operations on behalf of your account."));
            }

            var url = new StringBuilder();

            url.Append($"https://login.microsoftonline.com/{_settings.Tenant}/oauth2/v2.0/authorize?");
            url.Append($"client_id={_settings.ClientId}&");
            url.Append($"response_type=code&");
            url.Append($"redirect_uri={req.GetEncodedUrl()}&");
            url.Append($"response_mode=form_post&");
            url.Append($"scope={WebUtility.UrlEncode(string.Join(" ", scopes))}&");
            return(new RedirectResult(url.ToString(), false));
        }
Beispiel #19
0
        public async Task BrokerSilentRequestTestExecutorAsync(bool brokerConfiguredByUser, bool brokerIsInstalledAndInvokable)
        {
            string brokerID = "*****@*****.**";

            using (var harness = new MockHttpTestHarness(TestConstants.AuthorityHomeTenant))
            {
                // resul will be from the cache
                TokenCacheHelper.PopulateCache(harness.Cache.Accessor,
                                               TestConstants.Uid,
                                               TestConstants.Utid,
                                               TestConstants.ClientId,
                                               TestConstants.ProductionPrefCacheEnvironment,
                                               brokerID);

                IBroker mockBroker = Substitute.For <IBroker>();
                mockBroker.IsBrokerInstalledAndInvokable().ReturnsForAnyArgs(brokerIsInstalledAndInvokable);

                harness.ServiceBundle.Config.BrokerCreatorFunc = (app, config, logger) => mockBroker;

                var parameters = harness.CreateRequestParams(
                    harness.Cache,
                    null,
                    TestConstants.ExtraQueryParameters,
                    null,
                    authorityOverride: AuthorityInfo.FromAuthorityUri(TestConstants.AuthorityCommonTenant, false));
                parameters.AppConfig.IsBrokerEnabled = brokerConfiguredByUser;

                var silentParameters = new AcquireTokenSilentParameters()
                {
                    Account = new Account(TestConstants.HomeAccountId, TestConstants.DisplayableId, TestConstants.ProductionPrefCacheEnvironment),
                };

                var request = new SilentRequest(harness.ServiceBundle, parameters, silentParameters);

                var result = await request.RunAsync(default).ConfigureAwait(false);
        private async Task <string> GetAccessToken()
        {
            IConfidentialClientApplication app = ConfidentialClientApplicationBuilder
                                                 .Create(_options.Value.ClientId)
                                                 .WithClientSecret(_options.Value.ClientSecret)
                                                 .WithAuthority(_options.Value.Authority)
                                                 .Build();

            string key = User.FindFirstValue("http://schemas.microsoft.com/identity/claims/objectidentifier");

            TokenCacheHelper.Initialize(
                key,
                _cache,
                app.UserTokenCache
                );
            //IEnumerable<string> scopes = _options.Value.Scopes.Split(";").Where(c => !string.IsNullOrEmpty(c));
            IEnumerable <string> scopes = new string[] { "api://core/.default" };

            try
            {
                var account = (await app.GetAccountsAsync()).FirstOrDefault();
                var result  = await app.AcquireTokenSilent(scopes, account)
                              .ExecuteAsync();

                return($"200:{result.AccessToken}");
            }
            catch (MsalUiRequiredException)
            {
                return($"401:unauthorized");
            }
            catch (Exception ex)
            {
                return($"500:{ex.Message}");
            }
        }
        public async Task AcquireTokenByOboMissMatchUserAssertionsAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();

                AddMockHandlerAadSuccess(httpManager, TestConstants.AuthorityCommonTenant);

                var cca = ConfidentialClientApplicationBuilder
                          .Create(TestConstants.ClientId)
                          .WithClientSecret(TestConstants.ClientSecret)
                          .WithAuthority(TestConstants.AuthorityCommonTenant)
                          .WithHttpManager(httpManager)
                          .BuildConcrete();

                UserAssertion userAssertion = new UserAssertion(TestConstants.DefaultAccessToken);
                var           result        = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.AreEqual("some-access-token", result.AccessToken);

                //Update user assertions
                TokenCacheHelper.UpdateUserAssertions(cca);

                MockHttpMessageHandler mockTokenRequestHttpHandlerRefresh = AddMockHandlerAadSuccess(httpManager, TestConstants.AuthorityCommonTenant);

                //Access and refresh tokens are have a different user assertion so MSAL should perform OBO.
                result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.AreEqual("some-access-token", result.AccessToken);
                Assert.AreEqual(result.AuthenticationResultMetadata.TokenSource, TokenSource.IdentityProvider);
            }
        }
        public void OBOUserAssertionHashUsernamePassedTest()
        {
            TokenCache    cache         = TokenCacheHelper.CreateCacheWithItems();
            string        someAssertion = "some-assertion-passed-by-developer";
            TokenCacheKey key           = cache.tokenCacheDictionary.Keys.First();

            //update cache entry with hash of an assertion that will not match
            cache.tokenCacheDictionary[key].UserAssertionHash =
                new CryptographyHelper().CreateSha256Hash(someAssertion);

            ConfidentialClientApplication app = new ConfidentialClientApplication(TestConstants.DefaultClientId,
                                                                                  TestConstants.DefaultRedirectUri, new ClientCredential(TestConstants.DefaultClientSecret), new TokenCache());

            app.UserTokenCache = cache;

            //this is a fail safe. No call should go on network
            HttpMessageHandlerFactory.MockHandler = new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Post,
                ResponseMessage =
                    MockHelpers.CreateInvalidGrantTokenResponseMessage()
            };

            UserAssertion assertion          = new UserAssertion(someAssertion, AssertionType, key.DisplayableId);
            Task <AuthenticationResult> task = app.AcquireTokenOnBehalfOfAsync(key.Scope.AsArray(),
                                                                               assertion, key.Authority, TestConstants.DefaultPolicy);
            AuthenticationResult result = task.Result;

            Assert.IsNotNull(result);
            Assert.AreEqual(key.UniqueId, result.User.UniqueId);
            Assert.AreEqual(key.DisplayableId, result.User.DisplayableId);
            Assert.AreEqual(HashAccessToken,
                            cache.tokenCacheDictionary[key].UserAssertionHash);
        }
        public void CacheWithMultipleUsersAndRestrictToSingleUserTrueTest()
        {
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false, Guid.NewGuid());
            TokenCache    cache         = TokenCacheHelper.CreateCacheWithItems();

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

                InteractiveRequest request = new InteractiveRequest(parameters,
                                                                    TestConstants.ScopeForAnotherResource.ToArray(),
                                                                    new Uri("some://uri"), new PlatformParameters(),
                                                                    new User {
                    UniqueId = TestConstants.DefaultUniqueId
                }, UiOptions.ForceLogin, "extra=qp",
                                                                    new MockWebUI());
                Assert.Fail("ArgumentException should be thrown here");
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual(
                    "Cache cannot have entries for more than 1 unique id when RestrictToSingleUser is set to TRUE.",
                    ae.Message);
            }
        }
Beispiel #24
0
        public void GetUserTest()
        {
            var app   = new PublicClientApplication(TestConstants.ClientId);
            var users = app.Users;

            Assert.IsNotNull(users);
            // no users in the cache
            Assert.AreEqual(0, users.Count());

            var fetchedUser = app.GetUser(null);

            Assert.IsNull(fetchedUser);

            fetchedUser = app.GetUser("");
            Assert.IsNull(fetchedUser);

            TokenCacheHelper.AddRefreshTokenToCache(app.UserTokenCache.TokenCacheAccessor, TestConstants.Uid,
                                                    TestConstants.Utid, TestConstants.Name);
            TokenCacheHelper.AddRefreshTokenToCache(app.UserTokenCache.TokenCacheAccessor, TestConstants.Uid + "1",
                                                    TestConstants.Utid, TestConstants.Name + "1");

            users = app.Users;
            Assert.IsNotNull(users);
            // two users in the cache
            Assert.AreEqual(2, users.Count());

            var userToFind = users.First();

            fetchedUser = app.GetUser(userToFind.Identifier);

            Assert.AreEqual(userToFind.DisplayableId, fetchedUser.DisplayableId);
            Assert.AreEqual(userToFind.Identifier, fetchedUser.Identifier);
            Assert.AreEqual(userToFind.IdentityProvider, fetchedUser.IdentityProvider);
            Assert.AreEqual(userToFind.Name, fetchedUser.Name);
        }
        public static string GetAccessToken(string[] scopes)
        {
            // create new public client application
            var appPublic = PublicClientApplicationBuilder.Create(applicationId)
                            .WithAuthority(tenantCommonAuthority)
                            .WithRedirectUri(redirectUri)
                            .Build();

            // connect application to token cache
            TokenCacheHelper.EnableSerialization(appPublic.UserTokenCache);

            AuthenticationResult authResult;

            try {
                // try to acquire token from token cache
                var user = appPublic.GetAccountsAsync().Result.FirstOrDefault();
                authResult = appPublic.AcquireTokenSilent(scopes, user).ExecuteAsync().Result;
            }
            catch {
                authResult = appPublic.AcquireTokenInteractive(scopes).ExecuteAsync().Result;
            }

            // return access token to caller
            return(authResult.AccessToken);
        }
Beispiel #26
0
        public async Task AcquireTokenSilentScopeAndUserMultipleTokensFoundTest()
        {
            PublicClientApplication app =
                new PublicClientApplication(TestConstants.ClientId)
            {
                ValidateAuthority = false
            };

            cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            app.UserTokenCache = cache;
            TokenCacheHelper.PopulateCache(cache.TokenCacheAccessor);
            try
            {
                AuthenticationResult result = await app.AcquireTokenSilentAsync(TestConstants.Scope.ToArray(),
                                                                                new User()
                {
                    DisplayableId = TestConstants.DisplayableId,
                    Identifier    = TestConstants.UserIdentifier,
                })
                                              .ConfigureAwait(false);
            }
            catch (MsalClientException exc)
            {
                Assert.AreEqual(MsalClientException.MultipleTokensMatchedError, exc.ErrorCode);
            }
        }
Beispiel #27
0
        public void AcquireTokenSilentScopeAndUserOverloadDefaultAuthorityTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(TestConstants.AuthorityTestTenant), true)
                                              .WithHttpManager(httpManager)
                                              .WithTelemetry(new TraceTelemetryConfig())
                                              .BuildConcrete();

                var tokenCacheHelper = new TokenCacheHelper();
                tokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor);

                app.UserTokenCacheInternal.Accessor.DeleteAccessToken(
                    new MsalAccessTokenCacheKey(
                        TestConstants.ProductionPrefNetworkEnvironment,
                        TestConstants.Utid,
                        TestConstants.s_userIdentifier,
                        TestConstants.ClientId,
                        TestConstants.ScopeForAnotherResourceStr,
                        TestConstants.Bearer));

                Task <AuthenticationResult> task = app
                                                   .AcquireTokenSilent(
                    TestConstants.s_scope.ToArray(),
                    new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null))
                                                   .ExecuteAsync(CancellationToken.None);

                AuthenticationResult result = task.Result;
                Assert.IsNotNull(result);
                Assert.AreEqual(TestConstants.DisplayableId, result.Account.Username);
                Assert.AreEqual(TestConstants.s_scope.AsSingleString(), result.Scopes.AsSingleString());
            }
        }
Beispiel #28
0
        public void AcquireTokenSilentScopeAndUserOverloadTenantSpecificAuthorityTest()
        {
            PublicClientApplication app =
                new PublicClientApplication(TestConstants.ClientId, TestConstants.AuthorityGuestTenant)
            {
                ValidateAuthority = false
            };

            cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            app.UserTokenCache = cache;
            TokenCacheHelper.PopulateCache(cache.TokenCacheAccessor);
            cache.TokenCacheAccessor.AccessTokenCacheDictionary.Remove(new AccessTokenCacheKey(
                                                                           TestConstants.AuthorityGuestTenant,
                                                                           TestConstants.ScopeForAnotherResource, TestConstants.ClientId,
                                                                           TestConstants.UserIdentifier).ToString());

            Task <AuthenticationResult> task = app.AcquireTokenSilentAsync(TestConstants.Scope.ToArray(), new User()
            {
                DisplayableId = TestConstants.DisplayableId,
                Identifier    = TestConstants.UserIdentifier,
            });
            AuthenticationResult result = task.Result;

            Assert.IsNotNull(result);
            Assert.AreEqual(TestConstants.DisplayableId, result.User.DisplayableId);
            Assert.AreEqual(TestConstants.Scope.AsSingleString(), result.Scopes.AsSingleString());
        }
Beispiel #29
0
        public async Task AcquireTokenSilent_LoginHint_MultipleAccountsAsync()
        {
            var receiver = new MyReceiver();

            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(TestConstants.AuthorityTestTenant), true)
                                              .WithHttpManager(httpManager)
                                              .WithTelemetry(receiver.HandleTelemetryEvents)
                                              .BuildConcrete();

                var tokenCacheHelper = new TokenCacheHelper();
                var cacheAccess      = app.UserTokenCache.RecordAccess();

                tokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor, "uid1", "utid");
                tokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor, "uid2", "utid");

                var exception = await AssertException.TaskThrowsAsync <MsalUiRequiredException>(async() => await app.AcquireTokenSilent(
                                                                                                    TestConstants.s_scope.ToArray(),
                                                                                                    TestConstants.DisplayableId)
                                                                                                .WithAuthority(app.Authority, false)
                                                                                                .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false);

                Assert.AreEqual(MsalError.MultipleAccountsForLoginHint, exception.ErrorCode);
                Assert.AreEqual(UiRequiredExceptionClassification.AcquireTokenSilentFailed, exception.Classification);
                cacheAccess.AssertAccessCounts(1, 0);
            }
        }
        public void AcquireTokenSilentScopeAndUserOverloadTenantSpecificAuthorityTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(TestConstants.AuthorityGuestTenant), true)
                                              .WithHttpManager(httpManager)
                                              .BuildConcrete();

                TokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor);
                httpManager.AddInstanceDiscoveryMockHandler();

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler()
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(
                        TestConstants.Uid,
                        TestConstants.DisplayableId,
                        TestConstants.s_scope.ToArray())
                });

                Task <AuthenticationResult> task = app
                                                   .AcquireTokenSilent(
                    TestConstants.s_scope.ToArray(),
                    new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null))
                                                   .ExecuteAsync(CancellationToken.None);

                AuthenticationResult result = task.Result;
                Assert.IsNotNull(result);
                Assert.AreEqual(TestConstants.DisplayableId, result.Account.Username);
                Assert.AreEqual(TestConstants.s_scope.AsSingleString(), result.Scopes.AsSingleString());
            }
        }