Example #1
0
        public async Task SaveAccessAndRefreshTokenWithDifferentAuthoritySameUserTestAsync()
        {
            var serviceBundle            = TestCommon.CreateDefaultServiceBundle();
            ITokenCacheInternal cache    = new TokenCache(serviceBundle);
            MsalTokenResponse   response = MsalTestConstants.CreateMsalTokenResponse();

            var requestParams = CreateAuthenticationRequestParameters(serviceBundle);

            requestParams.TenantUpdatedCanonicalAuthority = MsalTestConstants.AuthorityHomeTenant;

            AddHostToInstanceCache(serviceBundle, MsalTestConstants.ProductionPrefNetworkEnvironment);

            await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false);

            response              = MsalTestConstants.CreateMsalTokenResponse();
            response.Scope        = MsalTestConstants.Scope.AsSingleString() + " another-scope";
            response.AccessToken  = "access-token-2";
            response.RefreshToken = "refresh-token-2";

            requestParams = CreateAuthenticationRequestParameters(serviceBundle);
            requestParams.TenantUpdatedCanonicalAuthority = MsalTestConstants.AuthorityGuestTenant;

            cache.SetAfterAccess(AfterAccessChangedNotification);
            await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false);

#pragma warning disable CS0618 // Type or member is obsolete
            Assert.IsFalse(((TokenCache)cache).HasStateChanged);
#pragma warning restore CS0618 // Type or member is obsolete

            Assert.AreEqual(1, cache.Accessor.GetAllRefreshTokens().Count());
            Assert.AreEqual(2, cache.Accessor.GetAllAccessTokens().Count());

            Assert.AreEqual("refresh-token-2", (await cache.GetAllRefreshTokensAsync(true).ConfigureAwait(false)).First().Secret);
        }
Example #2
0
        public async Task NoAppMetadata_WhenFociIsDisabledAsync()
        {
            using (var harness = new MockHttpAndServiceBundle())
            {
                // Arrange
                var testFlags = Substitute.For <IFeatureFlags>();
                testFlags.IsFociEnabled.Returns(false);

                harness.ServiceBundle.PlatformProxy.SetFeatureFlags(testFlags);

                ITokenCacheInternal cache    = new TokenCache(harness.ServiceBundle);
                MsalTokenResponse   response = MsalTestConstants.CreateMsalTokenResponse();
                var requestParams            = CreateAuthenticationRequestParameters(harness.ServiceBundle);
                requestParams.TenantUpdatedCanonicalAuthority = MsalTestConstants.AuthorityTestTenant;
                AddHostToInstanceCache(harness.ServiceBundle, MsalTestConstants.ProductionPrefNetworkEnvironment);

                // Act
                await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false);

                // Assert
                cache.Accessor.AssertItemCount(
                    expectedAtCount: 1,
                    expectedRtCount: 1,
                    expectedAccountCount: 1,
                    expectedIdtCount: 1,
                    expectedAppMetadataCount: 0);

                // Don't save RT as an FRT if FOCI is disabled
                Assert.IsTrue(string.IsNullOrEmpty(cache.Accessor.GetAllRefreshTokens().First().FamilyId));
            }
        }
Example #3
0
        public async Task SaveAccessAndRefreshTokenWithIntersectingScopesTestAsync()
        {
            var serviceBundle            = TestCommon.CreateDefaultServiceBundle();
            ITokenCacheInternal cache    = new TokenCache(serviceBundle);
            MsalTokenResponse   response = MsalTestConstants.CreateMsalTokenResponse();

            var requestParams = CreateAuthenticationRequestParameters(serviceBundle);

            requestParams.TenantUpdatedCanonicalAuthority = MsalTestConstants.AuthorityTestTenant;

            AddHostToInstanceCache(serviceBundle, MsalTestConstants.ProductionPrefNetworkEnvironment);

            await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false);

            response              = MsalTestConstants.CreateMsalTokenResponse();
            response.Scope        = MsalTestConstants.Scope.AsSingleString() + " random-scope";
            response.AccessToken  = "access-token-2";
            response.RefreshToken = "refresh-token-2";

            await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false);

            Assert.AreEqual(1, cache.Accessor.GetAllRefreshTokens().Count());
            Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count());

            Assert.AreEqual("refresh-token-2", (await cache.GetAllRefreshTokensAsync(true).ConfigureAwait(false)).First().Secret);
            Assert.AreEqual("access-token-2", (await cache.GetAllAccessTokensAsync(true).ConfigureAwait(false)).First().Secret);
        }
Example #4
0
        public async Task SaveAccessAndRefreshTokenWithEmptyCacheTestAsync()
        {
            var serviceBundle         = TestCommon.CreateDefaultServiceBundle();
            ITokenCacheInternal cache = new TokenCache(serviceBundle);

            MsalTokenResponse response = MsalTestConstants.CreateMsalTokenResponse();

            var requestParams = CreateAuthenticationRequestParameters(serviceBundle);

            requestParams.TenantUpdatedCanonicalAuthority = MsalTestConstants.AuthorityTestTenant;

            AddHostToInstanceCache(serviceBundle, MsalTestConstants.ProductionPrefNetworkEnvironment);

            await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false);

            cache.Accessor.AssertItemCount(
                expectedAtCount: 1,
                expectedRtCount: 1,
                expectedAccountCount: 1,
                expectedIdtCount: 1,
                expectedAppMetadataCount: 1);

            var metadata = cache.Accessor.GetAllAppMetadata().First();

            Assert.AreEqual(MsalTestConstants.ClientId, metadata.ClientId);
            Assert.AreEqual(MsalTestConstants.ProductionPrefNetworkEnvironment, metadata.Environment);
            Assert.IsNull(metadata.FamilyId);
        }
Example #5
0
        public async Task DoNotSaveRefreshTokenInAdalCacheForMsalB2CAuthorityTestAsync()
        {
            var appConfig = new ApplicationConfiguration()
            {
                ClientId      = MsalTestConstants.ClientId,
                RedirectUri   = MsalTestConstants.RedirectUri,
                AuthorityInfo = AuthorityInfo.FromAuthorityUri(MsalTestConstants.B2CAuthority, false)
            };

            var serviceBundle         = ServiceBundle.Create(appConfig);
            ITokenCacheInternal cache = new TokenCache(serviceBundle);

            MsalTokenResponse response = MsalTestConstants.CreateMsalTokenResponse();

            var requestParams = CreateAuthenticationRequestParameters(serviceBundle, authority: Authority.CreateAuthority(serviceBundle, MsalTestConstants.B2CAuthority));

            requestParams.TenantUpdatedCanonicalAuthority = MsalTestConstants.AuthorityTestTenant;

            AddHostToInstanceCache(serviceBundle, MsalTestConstants.ProductionPrefNetworkEnvironment);

            await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false);

            Assert.AreEqual(1, cache.Accessor.GetAllRefreshTokens().Count());
            Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count());

            IDictionary <AdalTokenCacheKey, AdalResultWrapper> dictionary =
                AdalCacheOperations.Deserialize(serviceBundle.DefaultLogger, cache.LegacyPersistence.LoadCache());

            cache.LegacyPersistence.WriteCache(AdalCacheOperations.Serialize(serviceBundle.DefaultLogger, dictionary));

            // ADAL cache is empty because B2C scenario is only for MSAL
            Assert.AreEqual(0, dictionary.Count);
        }
Example #6
0
        public void CacheB2CTokenTest()
        {
            using (var harness = CreateTestHarness())
            {
                ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle);

                string    tenantID  = "someTenantID";
                Authority authority = Authority.CreateAuthority(
                    harness.ServiceBundle,
                    $"https://login.microsoftonline.com/tfp/{tenantID}/somePolicy/oauth2/v2.0/authorize");

                // creating IDToken with empty tenantID and displayableID/PreferredUserName for B2C scenario
                MsalTokenResponse response = MsalTestConstants.CreateMsalTokenResponse();

                var requestContext = new RequestContext(harness.ServiceBundle, Guid.NewGuid());
                var requestParams  = CreateAuthenticationRequestParameters(harness.ServiceBundle, authority, requestContext: requestContext);
                authority.UpdateWithTenant(MsalTestConstants.Utid);
                requestParams.TenantUpdatedCanonicalAuthority = authority.AuthorityInfo.CanonicalAuthority;

                cache.SaveTokenResponseAsync(requestParams, response);

                Assert.AreEqual(1, cache.Accessor.GetAllRefreshTokens().Count());
                Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count());
            }
        }
Example #7
0
        public void CreateFrtFromTokenResponse()
        {
            MsalTokenResponse response = MsalTestConstants.CreateMsalTokenResponse();

            response.FamilyId = "1";

            var frt = new MsalRefreshTokenCacheItem("env", MsalTestConstants.ClientId, response);

            Assert.AreEqual("1", frt.FamilyId);
        }
        private void TestInitialize(MockHttpManager httpManager)
        {
            ModuleInitializer.ForceModuleInitializationTestOnly();

            new AadInstanceDiscovery(null, null, true);
            new ValidatedAuthoritiesCache(true);

            httpManager.AddMockHandler(
                MockHelpers.CreateInstanceDiscoveryMockHandler(
                    MsalTestConstants.GetDiscoveryEndpoint(MsalTestConstants.AuthorityCommonTenant)));
        }
Example #9
0
        public void ExpirationTimeTest()
        {
            // Need to get timestamp here since it needs to be before we create the token.
            // ExpireOn time is calculated from UtcNow when the object is created.
            DateTimeOffset current          = DateTimeOffset.UtcNow;
            const long     ExpiresInSeconds = 3599;

            var response = MsalTestConstants.CreateMsalTokenResponse();

            Assert.IsTrue(response.AccessTokenExpiresOn.Subtract(current) >= TimeSpan.FromSeconds(ExpiresInSeconds));
        }
Example #10
0
        public async Task SerializeDeserializeCacheTestAsync()
        {
            var serviceBundle         = TestCommon.CreateDefaultServiceBundle();
            ITokenCacheInternal cache = new TokenCache(serviceBundle);

            MsalTokenResponse response = MsalTestConstants.CreateMsalTokenResponse();

            var requestContext = RequestContext.CreateForTest(serviceBundle);
            var requestParams  = CreateAuthenticationRequestParameters(serviceBundle, requestContext: requestContext);

            requestParams.TenantUpdatedCanonicalAuthority = MsalTestConstants.AuthorityTestTenant;

            AddHostToInstanceCache(serviceBundle, MsalTestConstants.ProductionPrefNetworkEnvironment);

            await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false);

            byte[] serializedCache = cache.SerializeMsalV3();

            cache.Accessor.ClearAccessTokens();
            cache.Accessor.ClearRefreshTokens();

            Assert.AreEqual(0, cache.Accessor.GetAllRefreshTokens().Count());
            Assert.AreEqual(0, cache.Accessor.GetAllAccessTokens().Count());

            cache.DeserializeMsalV3(serializedCache);

            Assert.AreEqual(1, cache.Accessor.GetAllRefreshTokens().Count());
            Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count());

            serializedCache = cache.SerializeMsalV3();
            cache.DeserializeMsalV3(serializedCache);
            // item count should not change because old cache entries should have
            // been overriden

            Assert.AreEqual(1, cache.Accessor.GetAllRefreshTokens().Count());
            Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count());

            var atItem = (await cache.GetAllAccessTokensAsync(true).ConfigureAwait(false)).First();

            Assert.AreEqual(response.AccessToken, atItem.Secret);
            Assert.AreEqual(MsalTestConstants.AuthorityTestTenant, atItem.Authority);
            Assert.AreEqual(MsalTestConstants.ClientId, atItem.ClientId);
            Assert.AreEqual(response.Scope, atItem.ScopeSet.AsSingleString());

            // todo add test for idToken serialization
            // Assert.AreEqual(response.IdToken, atItem.RawIdToken);

            var rtItem = (await cache.GetAllRefreshTokensAsync(true).ConfigureAwait(false)).First();

            Assert.AreEqual(response.RefreshToken, rtItem.Secret);
            Assert.AreEqual(MsalTestConstants.ClientId, rtItem.ClientId);
            Assert.AreEqual(MsalTestConstants.UserIdentifier, rtItem.HomeAccountId);
            Assert.AreEqual(MsalTestConstants.ProductionPrefNetworkEnvironment, rtItem.Environment);
        }
Example #11
0
        public void CacheB2CTokenTest()
        {
            var serviceBundle         = TestCommon.CreateDefaultServiceBundle();
            ITokenCacheInternal cache = new TokenCache(serviceBundle);

            string tenantID  = "someTenantID";
            var    authority = Authority.CreateAuthority(
                serviceBundle,
                $"https://login.microsoftonline.com/tfp/{tenantID}/somePolicy/oauth2/v2.0/authorize");

            // creating IDToken with empty tenantID and displayableID/PreferredUserName for B2C scenario
            MsalTokenResponse response = MsalTestConstants.CreateMsalTokenResponse();

            var requestContext = RequestContext.CreateForTest(serviceBundle);
            var requestParams  = CreateAuthenticationRequestParameters(serviceBundle, authority, requestContext: requestContext);

            requestParams.TenantUpdatedCanonicalAuthority = MsalTestConstants.AuthorityTestTenant;

            cache.SaveTokenResponseAsync(requestParams, response);

            Assert.AreEqual(1, cache.Accessor.GetAllRefreshTokens().Count());
            Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count());
        }
Example #12
0
        public async Task SaveMultipleAppmetadataAsync()
        {
            var serviceBundle         = TestCommon.CreateDefaultServiceBundle();
            ITokenCacheInternal cache = new TokenCache(serviceBundle);

            MsalTokenResponse response  = MsalTestConstants.CreateMsalTokenResponse();
            MsalTokenResponse response2 = MsalTestConstants.CreateMsalTokenResponse();

            response2.FamilyId = "1";

            var requestParams = CreateAuthenticationRequestParameters(serviceBundle);

            requestParams.TenantUpdatedCanonicalAuthority = MsalTestConstants.AuthorityTestTenant;

            AddHostToInstanceCache(serviceBundle, MsalTestConstants.ProductionPrefNetworkEnvironment);

            await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false);

            await cache.SaveTokenResponseAsync(requestParams, response2).ConfigureAwait(false);

            cache.Accessor.AssertItemCount(
                expectedAtCount: 1,
                expectedRtCount: 2, // a normal RT and an FRT
                expectedAccountCount: 1,
                expectedIdtCount: 1,
                expectedAppMetadataCount: 1);

            var metadata = cache.Accessor.GetAllAppMetadata().First();

            Assert.AreEqual(MsalTestConstants.ClientId, metadata.ClientId);
            Assert.AreEqual(MsalTestConstants.ProductionPrefNetworkEnvironment, metadata.Environment);
            Assert.AreEqual(MsalTestConstants.FamilyId, metadata.FamilyId);

            Assert.IsTrue(cache.Accessor.GetAllRefreshTokens().Any(rt => rt.FamilyId == "1"));
            Assert.IsTrue(cache.Accessor.GetAllRefreshTokens().Any(rt => string.IsNullOrEmpty(rt.FamilyId)));
        }
 public static void AddInstanceDiscoveryMockHandler(this MockHttpManager httpManager, string url)
 {
     httpManager.AddMockHandler(MockHelpers.CreateInstanceDiscoveryMockHandler(MsalTestConstants.GetDiscoveryEndpoint(url)));
 }
Example #14
0
 private void Init(MockHttpManager httpManager)
 {
     httpManager.AddMockHandler(
         MockHelpers.CreateInstanceDiscoveryMockHandler(
             MsalTestConstants.GetDiscoveryEndpoint(MsalTestConstants.AuthorityCommonTenant)));
 }