public async Task ClientCreds_OnBehalfOf_NonExpired_NeedsRefresh_ValidResponse_Async()
        {
            // Arrange
            using (MockHttpAndServiceBundle harness = base.CreateTestHarness())
            {
                Trace.WriteLine("1. Setup an app with a token cache with one AT");
                ConfidentialClientApplication app = SetupCca(harness);

                Trace.WriteLine("2. Configure AT so that it shows it needs to be refreshed");
                UpdateATWithRefreshOn(app.UserTokenCacheInternal.Accessor, DateTime.UtcNow - TimeSpan.FromMinutes(1));
                TokenCacheAccessRecorder cacheAccess = app.UserTokenCache.RecordAccess();

                Trace.WriteLine("3. Configure AAD to respond with valid token to the refresh RT flow");
                harness.HttpManager.AddAllMocks(TokenResponseType.Valid);

                // Act
                Trace.WriteLine("4. ATS - should perform an RT refresh");
                AuthenticationResult result = await app.AcquireTokenOnBehalfOf(TestConstants.s_scope, new UserAssertion(TestConstants.UserAssertion, "assertiontype"))
                                              .ExecuteAsync()
                                              .ConfigureAwait(false);

                // Assert
                Assert.IsNotNull(result);
                Assert.AreEqual(0, harness.HttpManager.QueueSize,
                                "MSAL should have refreshed the token because the original AT was marked for refresh");
                cacheAccess.AssertAccessCounts(1, 1);
            }
        }
#pragma warning disable UseAsyncSuffix // Use Async suffix
        public async Task <long> Get()
#pragma warning restore UseAsyncSuffix // Use Async suffix
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            Guid          requestId = Guid.NewGuid();
            StringBuilder sb        = new StringBuilder();


            ConfidentialClientApplication local_cca = ConfidentialClientApplicationBuilder
                                                      .Create("d3adb33f-c0de-ed0c-c0de-deadb33fc0d3")
                                                      .WithAuthority($"https://login.microsoftonline.com/tid")
                                                      .WithHttpManager(s_httpManager)
                                                      .WithClientSecret("secret")
                                                      .WithLegacyCacheCompatibility(false)
                                                      .WithLogging((lvl, msg, pii) => sb.AppendLine(msg), LogLevel.Verbose, true, false)
                                                      .BuildConcrete();

            ConfidentialClientApplication cca = local_cca;


            var user = $"user_{s_random.Next(Settings.NumberOfUsers)}";

            s_inMemoryPartitionedCacheSerializer.Initialize(cca.UserTokenCache as TokenCache);

            string fakeUpstreamToken = $"upstream_token_{user}";


            var res = await cca.AcquireTokenOnBehalfOf(new[] { "scope" }, new UserAssertion(fakeUpstreamToken))
                      .WithCorrelationId(requestId)
                      .ExecuteAsync()
                      .ConfigureAwait(false);

            sw.Stop();

            TraceResult(res, user, sw.ElapsedMilliseconds);

            // Log the very bad requests
            if (res.AuthenticationResultMetadata.DurationTotalInMs > 2 * 1000 || sw.ElapsedMilliseconds > 2 * 1000)
            {
                s_traceSource.TraceEvent(TraceEventType.Error, 1, "##### FOUND!! " + requestId);


                System.IO.File.WriteAllText($"c:\\temp\\obo_{requestId}.txt", sb.ToString());
                System.IO.File.WriteAllText($"c:\\temp\\obo2_{requestId}.txt", sb2.ToString());
            }

            return(res.AuthenticationResultMetadata.DurationTotalInMs);
        }
예제 #3
0
        private static async Task RunObo_Async(MockHttpManager httpManager, ConfidentialClientApplication app)
        {
            httpManager.AddSuccessTokenResponseMockHandlerForPost();
            UserAssertion userAssertion = new UserAssertion(TestConstants.DefaultAccessToken);
            var           result        = await app.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false);

            Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource);

            // get AT from cache
            result = await app.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false);

            Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource);

            // get AT via OBO flow (no RT cached for OBO)
            TokenCacheHelper.ExpireAllAccessTokens(app.UserTokenCacheInternal);
            var handler = httpManager.AddSuccessTokenResponseMockHandlerForPost();

            handler.ExpectedPostData = new Dictionary <string, string> {
                { OAuth2Parameter.GrantType, OAuth2GrantType.JwtBearer }
            };
            result = await app.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false);

            Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource);
        }
예제 #4
0
#pragma warning disable UseAsyncSuffix // Use Async suffix
        public async Task <long> Get(bool refreshFlow)
#pragma warning restore UseAsyncSuffix // Use Async suffix
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            Guid          requestId = Guid.NewGuid();
            StringBuilder sb        = new StringBuilder();

            ConfidentialClientApplication local_cca = ConfidentialClientApplicationBuilder
                                                      .Create("d3adb33f-c0de-ed0c-c0de-deadb33fc0d3")
                                                      .WithAuthority($"https://login.microsoftonline.com/tid")
                                                      .WithHttpManager(refreshFlow ? s_httpManagerRefreshFlow : s_httpManager)
                                                      .WithClientSecret("secret")
                                                      .WithLegacyCacheCompatibility(false)
                                                      .WithLogging((lvl, msg, pii) => sb.AppendLine(msg), LogLevel.Verbose, true, false)
                                                      .BuildConcrete();

            ConfidentialClientApplication cca = local_cca;

            var user = $"user_{_random.Next(refreshFlow ? Settings.NumberOfUsersRefreshFlow : Settings.NumberOfUsers)}";

            s_distributedCacheWithDelay.Initialize(cca.UserTokenCache as TokenCache);

            string fakeUpstreamToken = $"upstream_token_{user}";

            var res = await cca.AcquireTokenOnBehalfOf(new[] { "scope" }, new UserAssertion(fakeUpstreamToken))
                      .WithCorrelationId(requestId)
                      .ExecuteAsync()
                      .ConfigureAwait(false);

            sw.Stop();

            TraceResult(res, user, sw.ElapsedMilliseconds);

            return(res.AuthenticationResultMetadata.DurationTotalInMs);
        }
예제 #5
0
        public async Task RefreshReasonExpired_ConfidentialClient_Async()
        {
            using (var harness = CreateTestHarness())
            {
                #region ClientCredential
                harness.HttpManager.AddInstanceDiscoveryMockHandler();
                harness.HttpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage();
                harness.HttpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage();

                ConfidentialClientApplication cca = ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId)
                                                    .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), false)
                                                    .WithRedirectUri(TestConstants.RedirectUri)
                                                    .WithClientSecret(TestConstants.ClientSecret)
                                                    .WithHttpManager(harness.HttpManager)
                                                    .BuildConcrete();

                // Act - AcquireTokenForClient returns result from IDP. Refresh reason is no access tokens.
                AuthenticationResult result = await cca.AcquireTokenForClient(TestConstants.s_scope.ToArray())
                                              .ExecuteAsync(CancellationToken.None)
                                              .ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource);
                Assert.AreEqual(CacheRefreshReason.NoCachedAccessToken, result.AuthenticationResultMetadata.CacheRefreshReason);

                //expire access tokens
                TokenCacheHelper.ExpireAllAccessTokens(cca.AppTokenCacheInternal);

                // Act - AcquireTokenForClient returns result from IDP because token is expired.
                result = await cca.AcquireTokenForClient(TestConstants.s_scope.ToArray())
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource);
                Assert.AreEqual(CacheRefreshReason.Expired, result.AuthenticationResultMetadata.CacheRefreshReason);

                // Act - AcquireTokenForClient returns result from Cache. Refresh reason is not applicable.
                result = await cca.AcquireTokenForClient(TestConstants.s_scope.ToArray())
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource);
                Assert.AreEqual(CacheRefreshReason.NotApplicable, result.AuthenticationResultMetadata.CacheRefreshReason);
                #endregion

                #region ObBehalfOf
                harness.HttpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage();
                harness.HttpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage();

                // Act - AcquireTokenForClient returns result from IDP. Refresh reason is no access tokens.
                result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope.ToArray(), new UserAssertion(TestConstants.UserAssertion))
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource);
                Assert.AreEqual(CacheRefreshReason.NoCachedAccessToken, result.AuthenticationResultMetadata.CacheRefreshReason);

                //expire access tokens
                TokenCacheHelper.ExpireAllAccessTokens(cca.UserTokenCacheInternal);

                // Act - AcquireTokenOnBehalfOf returns result from IDP because access token is expired.
                result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope.ToArray(), new UserAssertion(TestConstants.UserAssertion))
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource);
                Assert.AreEqual(CacheRefreshReason.Expired, result.AuthenticationResultMetadata.CacheRefreshReason);

                // Act - AcquireTokenOnBehalfOf returns result from cache. Refresh reason is not applicable.
                result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope.ToArray(), new UserAssertion(TestConstants.UserAssertion))
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource);
                Assert.AreEqual(CacheRefreshReason.NotApplicable, result.AuthenticationResultMetadata.CacheRefreshReason);
                #endregion
            }
        }
 public async Task <AuthenticationResult> AcquireTokenOnBehalfOf_TestAsync()
 {
     return(await _cca.AcquireTokenOnBehalfOf(_scope, _userAssertion)
            .ExecuteAsync()
            .ConfigureAwait(false));
 }