示例#1
0
        public void DeprecatedAuthorityTest()
        {
            const string uriNoPort     = "https://login.windows.net/mytenant.com";
            const string uriCustomPort = "https://login.windows.net:444/mytenant.com/";
            var          authority     = Authority.CreateAuthority(uriNoPort, false);

            Assert.AreEqual("https://login.microsoftonline.com/mytenant.com/", authority.CanonicalAuthority);
            authority = Authority.CreateAuthority(uriCustomPort, false);
            Assert.AreEqual("https://login.microsoftonline.com:444/mytenant.com/", authority.CanonicalAuthority);
            authority = Authority.CreateAuthority("https://login.windows.net/tfp/tenant/policy", false);
            Assert.AreEqual("https://login.microsoftonline.com/tfp/tenant/policy/", authority.CanonicalAuthority);
            authority = Authority.CreateAuthority("https://login.windows.net:444/tfp/tenant/policy", false);
            Assert.AreEqual("https://login.microsoftonline.com:444/tfp/tenant/policy/", authority.CanonicalAuthority);
        }
        public void OAuthClient_FailsWithServiceExceptionWhenEntireResponseIsNull()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager, _myReceiver);

                var authority = Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityHomeTenant, false);

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method          = HttpMethod.Get,
                    ResponseMessage = null
                });

                var parameters = new AuthenticationRequestParameters
                {
                    Authority      = authority,
                    ClientId       = MsalTestConstants.ClientId,
                    Scope          = MsalTestConstants.Scope,
                    TokenCache     = null,
                    RequestContext = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null)),
                    RedirectUri    = new Uri("some://uri"),
                };

                var ui = new MockWebUI();

                var request = new InteractiveRequest(
                    serviceBundle,
                    parameters,
                    ApiEvent.ApiIds.None,
                    MsalTestConstants.ScopeForAnotherResource.ToArray(),
                    MsalTestConstants.DisplayableId,
                    UIBehavior.SelectAccount,
                    ui);

                try
                {
                    request.ExecuteAsync(CancellationToken.None).Wait();

                    Assert.Fail("MsalException should have been thrown here");
                }
                catch (Exception exc)
                {
                    var innerException = exc.InnerException as InvalidOperationException;
                    Assert.IsNotNull(innerException);
                }
            }
        }
示例#3
0
        public void FailedValidationTest()
        {
            using (var harness = CreateTestHarness())
            {
                // add mock response for instance validation
                harness.HttpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod      = HttpMethod.Get,
                    ExpectedUrl         = "https://login.microsoftonline.com/common/discovery/instance",
                    ExpectedQueryParams = new Dictionary <string, string>
                    {
                        { "api-version", "1.1" },
                        {
                            "authorization_endpoint",
                            "https%3A%2F%2Flogin.microsoft0nline.com%2Fmytenant.com%2Foauth2%2Fv2.0%2Fauthorize"
                        },
                    },
                    ResponseMessage = MockHelpers.CreateFailureMessage(
                        HttpStatusCode.BadRequest,
                        "{\"error\":\"invalid_instance\"," + "\"error_description\":\"AADSTS50049: " +
                        "Unknown or invalid instance. Trace " + "ID: b9d0894d-a9a4-4dba-b38e-8fb6a009bc00 " +
                        "Correlation ID: 34f7b4cf-4fa2-4f35-a59b" + "-54b6f91a9c94 Timestamp: 2016-08-23 " +
                        "20:45:49Z\",\"error_codes\":[50049]," + "\"timestamp\":\"2016-08-23 20:45:49Z\"," +
                        "\"trace_id\":\"b9d0894d-a9a4-4dba-b38e-8f" + "b6a009bc00\",\"correlation_id\":\"34f7b4cf-" +
                        "4fa2-4f35-a59b-54b6f91a9c94\"}")
                });

                Authority instance = Authority.CreateAuthority(harness.ServiceBundle, "https://login.microsoft0nline.com/mytenant.com", true);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.Aad);
                try
                {
                    var resolver  = new AuthorityEndpointResolutionManager(harness.ServiceBundle);
                    var endpoints = resolver.ResolveEndpointsAsync(
                        instance.AuthorityInfo,
                        null,
                        new RequestContext(harness.ServiceBundle, Guid.NewGuid()))
                                    .ConfigureAwait(false).GetAwaiter().GetResult();

                    Assert.Fail("validation should have failed here");
                }
                catch (Exception exc)
                {
                    Assert.IsTrue(exc is MsalServiceException);
                    Assert.AreEqual(((MsalServiceException)exc).ErrorCode, "invalid_instance");
                }
            }
        }
        public void SilentRefreshFailedNoCacheItemFoundTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle        = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                var aadInstanceDiscovery = new AadInstanceDiscovery(httpManager, new TelemetryManager());
                var authority            = Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityHomeTenant, false);
                _cache = new TokenCache()
                {
                    ClientId      = MsalTestConstants.ClientId,
                    ServiceBundle = serviceBundle
                };

                httpManager.AddInstanceDiscoveryMockHandler();

                var parameters = new AuthenticationRequestParameters()
                {
                    Authority = authority,
                    ClientId  = MsalTestConstants.ClientId,
                    Scope     = ScopeHelper.CreateSortedSetFromEnumerable(
                        new[]
                    {
                        "some-scope1",
                        "some-scope2"
                    }),
                    TokenCache     = _cache,
                    Account        = new Account(MsalTestConstants.UserIdentifier, MsalTestConstants.DisplayableId, null),
                    RequestContext = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))
                };

                var crypto           = PlatformProxyFactory.GetPlatformProxy().CryptographyManager;
                var telemetryManager = new TelemetryManager();

                try
                {
                    var request = new SilentRequest(serviceBundle, parameters, ApiEvent.ApiIds.None, false);
                    Task <AuthenticationResult> task = request.RunAsync(CancellationToken.None);
                    var authenticationResult         = task.Result;
                    Assert.Fail("MsalUiRequiredException should be thrown here");
                }
                catch (AggregateException ae)
                {
                    var exc = ae.InnerException as MsalUiRequiredException;
                    Assert.IsNotNull(exc, "Actual exception type is " + ae.InnerException.GetType());
                    Assert.AreEqual(MsalUiRequiredException.NoTokensFoundError, exc.ErrorCode);
                }
            }
        }
示例#5
0
        public async Task ForceRefreshParameterTrueTestAsync()
        {
            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
            };

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(app.Authority)
            });

            //add mock response for successful token retrival
            const string tokenRetrievedFromNetCall = "token retrieved from network call";

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Post,
                ResponseMessage =
                    MockHelpers.CreateSuccessfulClientCredentialTokenResponseMessage(tokenRetrievedFromNetCall)
            });

            var result = await app.AcquireTokenForClientAsync(TestConstants.Scope, true);

            Assert.AreEqual(tokenRetrievedFromNetCall, result.AccessToken);

            // make sure token in Cache was updated
            var accessTokens       = cache.GetAllAccessTokensForClient(new RequestContext(Guid.NewGuid(), null));
            var accessTokenInCache = accessTokens.Where(
                item =>
                item.ScopeSet.ScopeContains(TestConstants.Scope))
                                     .ToList()
                                     .FirstOrDefault();

            Assert.AreEqual(tokenRetrievedFromNetCall, accessTokenInCache?.AccessToken);
            Assert.IsNotNull(_myReceiver.EventsReceived.Find(anEvent =>  // Expect finding such an event
                                                             anEvent[EventBase.EventNameKey].EndsWith("api_event") && anEvent[ApiEvent.WasSuccessfulKey] == "true" &&
                                                             anEvent[ApiEvent.ApiIdKey] == "727"));
        }
示例#6
0
        public void FailedValidationTest()
        {
            //add mock response for instance validation
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method      = HttpMethod.Get,
                Url         = "https://login.microsoftonline.com/common/discovery/instance",
                QueryParams = new Dictionary <string, string>
                {
                    { "api-version", "1.0" },
                    { "authorization_endpoint", "https%3A%2F%2Flogin.microsoft0nline.com%2Fmytenant.com%2Foauth2%2Fv2.0%2Fauthorize" },
                },
                ResponseMessage =
                    MockHelpers.CreateFailureMessage(HttpStatusCode.BadRequest, "{\"error\":\"invalid_instance\"," +
                                                     "\"error_description\":\"AADSTS50049: " +
                                                     "Unknown or invalid instance. Trace " +
                                                     "ID: b9d0894d-a9a4-4dba-b38e-8fb6a009bc00 " +
                                                     "Correlation ID: 34f7b4cf-4fa2-4f35-a59b" +
                                                     "-54b6f91a9c94 Timestamp: 2016-08-23 " +
                                                     "20:45:49Z\",\"error_codes\":[50049]," +
                                                     "\"timestamp\":\"2016-08-23 20:45:49Z\"," +
                                                     "\"trace_id\":\"b9d0894d-a9a4-4dba-b38e-8f" +
                                                     "b6a009bc00\",\"correlation_id\":\"34f7b4cf-" +
                                                     "4fa2-4f35-a59b-54b6f91a9c94\"}")
            });

            Authority instance = Authority.CreateAuthority("https://login.microsoft0nline.com/mytenant.com", true);

            Assert.IsNotNull(instance);
            Assert.AreEqual(instance.AuthorityType, AuthorityType.Aad);
            try
            {
                Task.Run(async() =>
                {
                    await instance.ResolveEndpointsAsync(null, new RequestContext(Guid.NewGuid(), null));
                })
                .GetAwaiter()
                .GetResult();
                Assert.Fail("validation should have failed here");
            }
            catch (Exception exc)
            {
                Assert.IsNotNull(exc is MsalServiceException);
                Assert.AreEqual(((MsalServiceException)exc).ErrorCode, "invalid_instance");
            }

            Assert.AreEqual(0, HttpMessageHandlerFactory.MockCount);
        }
示例#7
0
        public void FailedValidationResourceNotInTrustedRealmTest()
        {
            //add mock response for on-premise DRS request
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method      = HttpMethod.Get,
                Url         = "https://enterpriseregistration.fabrikam.com/enrollmentserver/contract",
                QueryParams = new Dictionary <string, string>
                {
                    { "api-version", "1.0" }
                },
                ResponseMessage = MockHelpers.CreateSuccessResponseMessage(File.ReadAllText("drs-response.json"))
            });


            //add mock response for on-premise webfinger request
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method      = HttpMethod.Get,
                Url         = "https://fs.fabrikam.com/adfs/.well-known/webfinger",
                QueryParams = new Dictionary <string, string>
                {
                    { "resource", "https://fs.contoso.com" },
                    { "rel", "http://schemas.microsoft.com/rel/trusted-realm" }
                },
                ResponseMessage = MockHelpers.CreateSuccessWebFingerResponseMessage("https://fs.some-other-sts.com")
            });

            Authority instance = Authority.CreateAuthority(TestConstants.OnPremiseAuthority, true);

            Assert.IsNotNull(instance);
            Assert.AreEqual(instance.AuthorityType, AuthorityType.Adfs);
            try
            {
                Task.Run(async() =>
                {
                    await instance.ResolveEndpointsAsync(TestConstants.FabrikamDisplayableId, new RequestContext(Guid.NewGuid(), null));
                }).GetAwaiter().GetResult();
                Assert.Fail("ResolveEndpointsAsync should have failed here");
            }
            catch (Exception exc)
            {
                Assert.IsNotNull(exc);
            }

            Assert.AreEqual(0, HttpMessageHandlerFactory.MockCount);
        }
示例#8
0
        public void ExpiredTokenRefreshFlowTest()
        {
            Authority  authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false);
            TokenCache cache     = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            TokenCacheHelper.PopulateCache(cache.TokenCacheAccessor);

            AuthenticationRequestParameters parameters = new AuthenticationRequestParameters()
            {
                Authority = authority,
                ClientId  = TestConstants.ClientId,
                Scope     = new[] { "some-scope1", "some-scope2" }.CreateSetFromEnumerable(),
                                            TokenCache     = cache,
                                            RequestContext = new RequestContext(Guid.Empty, null),
                                            User           = new User()
                {
                    Identifier    = TestConstants.UserIdentifier,
                    DisplayableId = TestConstants.DisplayableId
                }
            };

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(TestConstants.AuthorityHomeTenant)
            });

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

            SilentRequest request              = new SilentRequest(parameters, false);
            Task <AuthenticationResult> task   = request.RunAsync();
            AuthenticationResult        result = task.Result;

            Assert.IsNotNull(result);
            Assert.AreEqual("some-access-token", result.AccessToken);
            Assert.AreEqual("some-scope1 some-scope2", result.Scopes.AsSingleString());

            Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");
        }
示例#9
0
        public static Authority CreateAuthorityFromUrl(string uri)
        {
            var httpManager = new MockHttpManager();
            var appConfig   = new ApplicationConfiguration()
            {
                HttpManager   = httpManager,
                AuthorityInfo = AuthorityInfo.FromAuthorityUri(uri, false)
            };

            var serviceBundle = ServiceBundle.Create(appConfig);

            Authority authority = Authority.CreateAuthority(
                serviceBundle,
                uri);

            return(authority);
        }
示例#10
0
        public void SaveAccessAndRefreshTokenWithLessScopesTest()
        {
            TokenCache cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            TokenResponse response = new TokenResponse();

            response.IdToken       = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId);
            response.ClientInfo    = MockHelpers.CreateClientInfo();
            response.AccessToken   = "access-token";
            response.ExpiresIn     = 3599;
            response.CorrelationId = "correlation-id";
            response.RefreshToken  = "refresh-token";
            response.Scope         = TestConstants.Scope.AsSingleString();
            response.TokenType     = "Bearer";

            RequestContext requestContext = new RequestContext(Guid.NewGuid(), null);
            AuthenticationRequestParameters requestParams = new AuthenticationRequestParameters()
            {
                RequestContext = requestContext,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                ClientId       = TestConstants.ClientId,
                TenantUpdatedCanonicalAuthority = TestConstants.AuthorityHomeTenant
            };

            cache.SaveAccessAndRefreshToken(requestParams, response);

            response               = new TokenResponse();
            response.IdToken       = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId);
            response.ClientInfo    = MockHelpers.CreateClientInfo();
            response.AccessToken   = "access-token-2";
            response.ExpiresIn     = 3599;
            response.CorrelationId = "correlation-id";
            response.RefreshToken  = "refresh-token-2";
            response.Scope         = TestConstants.Scope.First();
            response.TokenType     = "Bearer";

            cache.SaveAccessAndRefreshToken(requestParams, response);

            Assert.AreEqual(1, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
            Assert.AreEqual(1, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count);
            Assert.AreEqual("refresh-token-2", cache.GetAllRefreshTokensForClient(requestContext).First().RefreshToken);
            Assert.AreEqual("access-token-2", cache.GetAllAccessTokensForClient(requestContext).First().AccessToken);
        }
        public void NotEnoughPathSegmentsTest()
        {
            try
            {
                var serviceBundle = TestCommon.CreateDefaultServiceBundle();
                var instance      = Authority.CreateAuthority("https://login.microsoftonline.in/tfp/");
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.B2C);

                Assert.Fail("test should have failed");
            }
            catch (Exception exc)
            {
                Assert.IsInstanceOfType(exc, typeof(ArgumentException));
                Assert.AreEqual(MsalErrorMessage.B2cAuthorityUriInvalidPath, exc.Message);
            }
        }
示例#12
0
        public void GetRefreshTokenTest()
        {
            TokenCache cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };
            RefreshTokenCacheItem rtItem = new RefreshTokenCacheItem()
            {
                Environment      = TestConstants.ProductionEnvironment,
                ClientId         = TestConstants.ClientId,
                RefreshToken     = "someRT",
                RawClientInfo    = MockHelpers.CreateClientInfo(),
                DisplayableId    = TestConstants.DisplayableId,
                IdentityProvider = TestConstants.IdentityProvider,
                Name             = TestConstants.Name
            };

            rtItem.ClientInfo = ClientInfo.CreateFromJson(rtItem.RawClientInfo);

            RefreshTokenCacheKey rtKey = rtItem.GetRefreshTokenItemKey();

            cache.TokenCacheAccessor.RefreshTokenCacheDictionary[rtKey.ToString()] = JsonHelper.SerializeToJson(rtItem);
            var authParams = new AuthenticationRequestParameters()
            {
                RequestContext = new RequestContext(Guid.Empty, null),
                ClientId       = TestConstants.ClientId,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                Scope          = TestConstants.Scope,
                User           = TestConstants.User
            };

            Assert.IsNotNull(cache.FindRefreshToken(authParams));

            // RT is stored by environment, client id and userIdentifier as index.
            // any change to authority (within same environment), uniqueid and displyableid will not
            // change the outcome of cache look up.
            Assert.IsNotNull(cache.FindRefreshToken(new AuthenticationRequestParameters()
            {
                RequestContext = new RequestContext(Guid.Empty, null),
                ClientId       = TestConstants.ClientId,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant + "more", false),
                Scope          = TestConstants.Scope,
                User           = TestConstants.User
            }));
        }
示例#13
0
        public void GetIntersectedScopesMatchedAccessTokenTest()
        {
            TokenCache cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };
            AccessTokenCacheItem atItem = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ScopeSet  = TestConstants.Scope,
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId)
            };

            // create key out of access token cache item and then
            // set it as the value of the access token.
            AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();

            atItem.AccessToken = atKey.ToString();
            cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);

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

            param.Scope.Add(TestConstants.Scope.First());
            param.Scope.Add("non-existant-scopes");
            AccessTokenCacheItem item = cache.FindAccessToken(param);

            //intersected scopes are not returned.
            Assert.IsNull(item);
        }
示例#14
0
        public void ConstructorTests()
        {
            Authority  authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false);
            TokenCache cache     = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };
            AuthenticationRequestParameters parameters = new AuthenticationRequestParameters()
            {
                Authority      = authority,
                ClientId       = TestConstants.ClientId,
                Scope          = TestConstants.Scope,
                TokenCache     = cache,
                RequestContext = new RequestContext(Guid.Empty, null)
            };

            parameters.User = null;
            try
            {
                new SilentRequest(parameters, false);
                Assert.Fail("MsalUiRequiredException should have been thrown here");
            }
            catch (MsalUiRequiredException exc)
            {
                Assert.AreEqual(exc.ErrorCode, MsalUiRequiredException.UserNullError);
            }

            parameters.User = new User()
            {
                DisplayableId = TestConstants.DisplayableId
            };
            SilentRequest request = new SilentRequest(parameters, false);

            Assert.IsNotNull(request);

            parameters.User = new User()
            {
            };
            request = new SilentRequest(parameters, false);
            Assert.IsNotNull(request);

            request = new SilentRequest(parameters, false);
            Assert.IsNotNull(request);
        }
示例#15
0
        public void B2CLoginAuthorityCreateAuthority()
        {
            using (var httpManager = new MockHttpManager())
            {
                var appConfig = new ApplicationConfiguration()
                {
                    HttpManager   = httpManager,
                    AuthorityInfo = AuthorityInfo.FromAuthorityUri(TestConstants.B2CLoginAuthority, false)
                };

                var serviceBundle = ServiceBundle.Create(appConfig);

                // add mock response for tenant endpoint discovery
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod  = HttpMethod.Get,
                    ExpectedUrl     = "https://sometenantid.b2clogin.com/tfp/sometenantid/policy/v2.0/.well-known/openid-configuration",
                    ResponseMessage = MockHelpers.CreateSuccessResponseMessage(
                        File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("OpenidConfiguration-B2CLogin.json")))
                });

                Authority instance = Authority.CreateAuthority(
                    serviceBundle,
                    TestConstants.B2CLoginAuthority);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.B2C);
                var resolver  = new AuthorityEndpointResolutionManager(serviceBundle);
                var endpoints = resolver.ResolveEndpointsAsync(
                    instance.AuthorityInfo,
                    null,
                    new RequestContext(serviceBundle, Guid.NewGuid()))
                                .GetAwaiter().GetResult();

                Assert.AreEqual(
                    "https://sometenantid.b2clogin.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/policy/oauth2/v2.0/authorize",
                    endpoints.AuthorizationEndpoint);
                Assert.AreEqual(
                    "https://sometenantid.b2clogin.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/policy/oauth2/v2.0/token",
                    endpoints.TokenEndpoint);
                Assert.AreEqual("https://sometenantid.b2clogin.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/v2.0/", endpoints.SelfSignedJwtAudience);
            }
        }
示例#16
0
        public void CreateEndpointsWithCommonTenantTest()
        {
            using (var harness = CreateTestHarness())
            {
                Authority instance = Authority.CreateAuthority("https://login.microsoftonline.com/common");
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.Aad);

                var resolver  = new AuthorityResolutionManager();
                var endpoints = resolver.ResolveEndpoints(
                    instance,
                    null,
                    new RequestContext(harness.ServiceBundle, Guid.NewGuid()));

                Assert.AreEqual("https://login.microsoftonline.com/common/oauth2/v2.0/authorize", endpoints.AuthorizationEndpoint);
                Assert.AreEqual("https://login.microsoftonline.com/common/oauth2/v2.0/token", endpoints.TokenEndpoint);
                Assert.AreEqual("https://login.microsoftonline.com/common/oauth2/v2.0/token", endpoints.SelfSignedJwtAudience);
            }
        }
示例#17
0
        public void GetSubsetScopesMatchedAccessTokenTest()
        {
            TokenCache cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };
            AccessTokenCacheItem atItem = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ScopeSet  = TestConstants.Scope,
                Scope     = TestConstants.Scope.AsSingleString(),
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                RawClientInfo          = MockHelpers.CreateClientInfo(),
            };

            atItem.IdToken    = IdToken.Parse(atItem.RawIdToken);
            atItem.ClientInfo = ClientInfo.CreateFromJson(atItem.RawClientInfo);

            // create key out of access token cache item and then
            // set it as the value of the access token.
            AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();

            atItem.AccessToken = atKey.ToString();

            cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);
            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
            };

            param.Scope.Add("r1/scope1");
            AccessTokenCacheItem item = cache.FindAccessToken(param);

            Assert.IsNotNull(item);
            Assert.AreEqual(atKey.ToString(), item.AccessToken);
        }
        public void SuccessfulValidationTest()
        {
            //add mock response for instance validation
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method      = HttpMethod.Get,
                Url         = "https://login.microsoftonline.com/common/discovery/instance",
                QueryParams = new Dictionary <string, string>
                {
                    { "api-version", "1.0" },
                    { "authorization_endpoint", "https%3A%2F%2Flogin.microsoftonline.in%2Fmytenant.com%2Foauth2%2Fv2.0%2Fauthorize" },
                },
                ResponseMessage = MockHelpers.CreateSuccessResponseMessage(
                    "{\"tenant_discovery_endpoint\":\"https://login.microsoftonline.in/mytenant.com/.well-known/openid-configuration\"}")
            });

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                Url             = "https://login.microsoftonline.in/mytenant.com/.well-known/openid-configuration",
                ResponseMessage = MockHelpers.CreateSuccessResponseMessage(File.ReadAllText("OpenidConfiguration.json"))
            });

            Authority instance = Authority.CreateAuthority("https://login.microsoftonline.in/mytenant.com", true);

            Assert.IsNotNull(instance);
            Assert.AreEqual(instance.AuthorityType, AuthorityType.Aad);
            Task.Run(async() =>
            {
                await instance.ResolveEndpointsAsync(null, new RequestContext(Guid.NewGuid(), null)).ConfigureAwait(false);
            })
            .GetAwaiter()
            .GetResult();

            Assert.AreEqual("https://login.microsoftonline.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/oauth2/v2.0/authorize",
                            instance.AuthorizationEndpoint);
            Assert.AreEqual("https://login.microsoftonline.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/oauth2/v2.0/token",
                            instance.TokenEndpoint);
            Assert.AreEqual("https://sts.windows.net/6babcaad-604b-40ac-a9d7-9fd97c0b779f/",
                            instance.SelfSignedJwtAudience);
            Assert.AreEqual(0, HttpMessageHandlerFactory.MockCount);
        }
示例#19
0
        public async Task ConfidentialClientWithRSACertificateTestAsync()
        {
            AuthenticationResult           authResult;
            IConfidentialClientApplication confidentialApp;
            X509Certificate2 cert = GetCertificate(true);

            confidentialApp = ConfidentialClientApplicationBuilder
                              .Create(PublicCloudConfidentialClientID)
                              .WithAuthority(PublicCloudTestAuthority)
                              .WithCertificate(cert)
                              .Build();
            var appCacheRecorder = confidentialApp.AppTokenCache.RecordAccess();

            authResult = await confidentialApp
                         .AcquireTokenForClient(s_keyvaultScope)
                         .WithAuthority(PublicCloudTestAuthority, true)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(1, 1);
            Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            Assert.AreEqual(
                GetExpectedCacheKey(PublicCloudConfidentialClientID, Authority.CreateAuthority(PublicCloudTestAuthority, false).TenantId),
                appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);

            // Call again to ensure token cache is hit
            authResult = await confidentialApp
                         .AcquireTokenForClient(s_keyvaultScope)
                         .WithAuthority(PublicCloudTestAuthority, true)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(2, 1);
            Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            Assert.AreEqual(
                GetExpectedCacheKey(PublicCloudConfidentialClientID, Authority.CreateAuthority(PublicCloudTestAuthority, false).TenantId),
                appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
        }
示例#20
0
        public async Task RunTestWithClientSecretAsync(
            string clientID,
            string confidentialClientAuthority,
            string secret)
        {
            var confidentialApp = ConfidentialClientApplicationBuilder
                                  .Create(clientID)
                                  .WithClientSecret(secret)
                                  .WithAuthority(confidentialClientAuthority)
                                  .WithTestLogging()
                                  .Build();
            var appCacheRecorder = confidentialApp.AppTokenCache.RecordAccess();

            var authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                             .WithAuthority(confidentialClientAuthority)
                             .ExecuteAsync(CancellationToken.None)
                             .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(1, 1);
            Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            Assert.AreEqual(
                GetExpectedCacheKey(clientID, Authority.CreateAuthority(confidentialClientAuthority, false).TenantId),
                appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);


            // Call again to ensure token cache is hit
            authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                         .WithAuthority(confidentialClientAuthority)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(2, 1);
            Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource);

            Assert.AreEqual(
                GetExpectedCacheKey(clientID, Authority.CreateAuthority(confidentialClientAuthority, false).TenantId),
                appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
        }
        public void DuplicateQueryParameterErrorTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager, _myReceiver);
                var authority     = Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityHomeTenant, false);
                var parameters    = new AuthenticationRequestParameters
                {
                    Authority            = authority,
                    ClientId             = MsalTestConstants.ClientId,
                    Scope                = MsalTestConstants.Scope,
                    TokenCache           = null,
                    RequestContext       = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null)),
                    RedirectUri          = new Uri("some://uri"),
                    ExtraQueryParameters = "extra=qp&prompt=login"
                };

                MockInstanceDiscoveryAndOpenIdRequest(httpManager);

                var request = new InteractiveRequest(
                    serviceBundle,
                    parameters,
                    ApiEvent.ApiIds.None,
                    MsalTestConstants.ScopeForAnotherResource.ToArray(),
                    null,
                    UIBehavior.ForceLogin,
                    new MockWebUI());

                try
                {
                    request.ExecuteAsync(CancellationToken.None).Wait();
                    Assert.Fail("MsalException should be thrown here");
                }
                catch (Exception exc)
                {
                    Assert.IsTrue(exc.InnerException is MsalException);
                    Assert.AreEqual(
                        MsalClientException.DuplicateQueryParameterError,
                        ((MsalException)exc.InnerException).ErrorCode);
                }
            }
        }
 public void NotEnoughPathSegmentsTest()
 {
     try
     {
         Authority instance = Authority.CreateAuthority("https://login.microsoftonline.in/tfp/", false);
         Assert.IsNotNull(instance);
         Assert.AreEqual(instance.AuthorityType, AuthorityType.B2C);
         Task
         .Run(
             async() => { await instance.ResolveEndpointsAsync(null, new RequestContext(Guid.NewGuid(), null)).ConfigureAwait(false); })
         .GetAwaiter()
         .GetResult();
         Assert.Fail("test should have failed");
     }
     catch (Exception exc)
     {
         Assert.IsInstanceOfType(exc, typeof(ArgumentException));
         Assert.AreEqual(MsalErrorMessage.B2cAuthorityUriInvalidPath, exc.Message);
     }
 }
        private AuthenticationRequestParameters CreateAuthenticationRequestParameters(
            IServiceBundle serviceBundle,
            Authority authority           = null,
            SortedSet <string> scopes     = null,
            RequestContext requestContext = null)
        {
            var commonParameters = new AcquireTokenCommonParameters
            {
                Scopes = scopes ?? TestConstants.s_scope,
            };

            return(new AuthenticationRequestParameters(
                       serviceBundle,
                       new TokenCache(serviceBundle),
                       commonParameters,
                       requestContext ?? new RequestContext(serviceBundle, Guid.NewGuid()))
            {
                Authority = authority ?? Authority.CreateAuthority(serviceBundle, TestConstants.AuthorityTestTenant)
            });
        }
        public void CanonicalAuthorityInitTest()
        {
            const string uriNoPort          = "https://login.microsoftonline.in/mytenant.com";
            const string uriNoPortTailSlash = "https://login.microsoftonline.in/mytenant.com/";

            const string uriDefaultPort = "https://login.microsoftonline.in:443/mytenant.com";

            const string uriCustomPort          = "https://login.microsoftonline.in:444/mytenant.com";
            const string uriCustomPortTailSlash = "https://login.microsoftonline.in:444/mytenant.com/";

            var authority = Authority.CreateAuthority(uriNoPort, false);

            Assert.AreEqual(uriNoPortTailSlash, authority.CanonicalAuthority);

            authority = Authority.CreateAuthority(uriDefaultPort, false);
            Assert.AreEqual(uriNoPortTailSlash, authority.CanonicalAuthority);

            authority = Authority.CreateAuthority(uriCustomPort, false);
            Assert.AreEqual(uriCustomPortTailSlash, authority.CanonicalAuthority);
        }
示例#25
0
        private AuthenticationRequestParameters CreateAuthenticationRequestParameters(
            IServiceBundle serviceBundle,
            Authority authority           = null,
            SortedSet <string> scopes     = null,
            RequestContext requestContext = null)
        {
            var commonParameters = new AcquireTokenCommonParameters
            {
                Scopes = scopes ?? MsalTestConstants.Scope,
            };

            return(new AuthenticationRequestParameters(
                       serviceBundle,
                       null,
                       commonParameters,
                       requestContext ?? RequestContext.CreateForTest(serviceBundle))
            {
                Authority = authority ?? Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityTestTenant)
            });
        }
示例#26
0
        public AuthenticationRequestParameters CreateAuthenticationRequestParameters(
            string authority,
            IEnumerable <string> scopes    = null,
            ITokenCacheInternal tokenCache = null,
            IAccount account = null,
            IDictionary <string, string> extraQueryParameters = null,
            string claims          = null,
            ApiEvent.ApiIds apiId  = ApiEvent.ApiIds.None,
            bool validateAuthority = false)
        {
            scopes     = scopes ?? TestConstants.s_scope;
            tokenCache = tokenCache ?? new TokenCache(ServiceBundle, false);

            var commonParameters = new AcquireTokenCommonParameters
            {
                Scopes = scopes ?? TestConstants.s_scope,
                ExtraQueryParameters = extraQueryParameters ?? new Dictionary <string, string>(),
                Claims = claims,
                ApiId  = apiId
            };

            var authorityObj   = Authority.CreateAuthority(authority, validateAuthority);
            var requestContext = new RequestContext(ServiceBundle, Guid.NewGuid());
            AuthenticationRequestParameters authenticationRequestParameters =
                new AuthenticationRequestParameters(
                    ServiceBundle,
                    tokenCache,
                    commonParameters,
                    requestContext,
                    authorityObj)
            {
                Account = account,
            };

            authenticationRequestParameters.RequestContext.ApiEvent = new ApiEvent(
                authenticationRequestParameters.RequestContext.Logger,
                ServiceBundle.PlatformProxy.CryptographyManager,
                Guid.NewGuid().AsMatsCorrelationId());

            return(authenticationRequestParameters);
        }
        public void TestPluginSelection()
        {
            var ex = AssertException.Throws <MsalClientException>(
                () => _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.B2CAuthority), null, false).GetAwaiter().GetResult());

            Assert.AreEqual(MsalError.WamNoB2C, ex.ErrorCode);

            Assert.IsFalse(
                _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.ADFSAuthority), null, false).Result,
                "ADFS authorities should be handled by AAD plugin");

            Assert.IsTrue(
                _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.AuthorityCommonTenant), TestConstants.MsaTenantId, false).Result,
                "Common authority - look at account tenant ID to determine plugin");

            Assert.IsFalse(
                _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.AuthorityCommonTenant), TestConstants.TenantId, false).Result,
                "Common authority - look at account tenant ID to determine plugin");



            Assert.IsFalse(
                _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.AuthorityOrganizationsTenant), TestConstants.TenantId, false).Result,
                "Organizations authority - AAD plugin unless MSA-pt");

            Assert.IsFalse(
                _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.AuthorityOrganizationsTenant), TestConstants.TenantId, true).Result,
                "Organizations authority with MSA-pt - based on home account id");

            Assert.IsTrue(
                _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.AuthorityOrganizationsTenant), TestConstants.MsaTenantId, true).Result,
                "Organizations authority with MSA-pt - based on home account id");

            Assert.IsTrue(
                _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.AuthorityConsumersTenant), TestConstants.TenantId, false).Result,
                "Consumer authority - msa plugin");

            Assert.IsFalse(
                _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.AuthorityGuidTenant), TestConstants.TenantId, true).Result,
                "Tenanted authorities - AAD plugin");
        }
示例#28
0
        public void FailedValidationMissingFieldsInDrsResponseTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                //add mock failure response for on-premise DRS request
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method      = HttpMethod.Get,
                    Url         = "https://enterpriseregistration.fabrikam.com/enrollmentserver/contract",
                    QueryParams = new Dictionary <string, string>
                    {
                        { "api-version", "1.0" }
                    },
                    ResponseMessage =
                        MockHelpers.CreateSuccessResponseMessage(
                            ResourceHelper.GetTestResourceRelativePath(File.ReadAllText("drs-response-missing-field.json")))
                });

                Authority instance = Authority.CreateAuthority(serviceBundle, CoreTestConstants.OnPremiseAuthority, true);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityType, AuthorityType.Adfs);
                try
                {
                    Task.Run(
                        async() =>
                    {
                        await instance.ResolveEndpointsAsync(
                            CoreTestConstants.FabrikamDisplayableId,
                            new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))).ConfigureAwait(false);
                    }).GetAwaiter().GetResult();
                    Assert.Fail("ResolveEndpointsAsync should have failed here");
                }
                catch (Exception exc)
                {
                    Assert.IsNotNull(exc);
                }
            }
        }
        public void FailedValidationMissingFieldsTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                //add mock response for instance validation
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method      = HttpMethod.Get,
                    Url         = "https://login.windows.net/common/discovery/instance",
                    QueryParams = new Dictionary <string, string>
                    {
                        { "api-version", "1.0" },
                        { "authorization_endpoint", "https://login.microsoft0nline.com/mytenant.com/oauth2/v2.0/authorize" },
                    },
                    ResponseMessage = MockHelpers.CreateSuccessResponseMessage("{}")
                });

                var       aadInstanceDiscovery = new AadInstanceDiscovery(httpManager, new TelemetryManager());
                Authority instance             = Authority.CreateAuthority(serviceBundle, "https://login.microsoft0nline.com/mytenant.com", true);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityType, AuthorityType.Aad);
                try
                {
                    Task.Run(
                        async() =>
                    {
                        await instance.ResolveEndpointsAsync(
                            null,
                            new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))).ConfigureAwait(false);
                    }).GetAwaiter().GetResult();
                    Assert.Fail("validation should have failed here");
                }
                catch (Exception exc)
                {
                    Assert.IsNotNull(exc);
                }
            }
        }
示例#30
0
        public void GetExpiredAccessTokenTest()
        {
            cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            AccessTokenCacheItem item = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                RawClientInfo          = MockHelpers.CreateClientInfo(),
                ScopeSet = TestConstants.Scope
            };

            item.IdToken     = IdToken.Parse(item.RawIdToken);
            item.ClientInfo  = ClientInfo.CreateFromJson(item.RawClientInfo);
            item.AccessToken = item.GetAccessTokenItemKey().ToString();
            cache.TokenCacheAccessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] =
                JsonHelper.SerializeToJson(item);

            cache.TokenCacheAccessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] =
                JsonHelper.SerializeToJson(item);

            Assert.IsNull(cache.FindAccessToken(new AuthenticationRequestParameters()
            {
                RequestContext = new RequestContext(Guid.Empty, null),
                ClientId       = TestConstants.ClientId,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                Scope          = TestConstants.Scope,
                User           =
                    new User()
                {
                    DisplayableId = TestConstants.DisplayableId,
                    Identifier    = TestConstants.UserIdentifier
                }
            }));
        }