public async Task WsTrustRequestTestAsync()
        {
            string wsTrustAddress = "https://some/address/usernamemixed";
            var    endpoint       = new WsTrustEndpoint(new Uri(wsTrustAddress), WsTrustVersion.WsTrust13);

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler()
                {
                    Url             = wsTrustAddress,
                    Method          = HttpMethod.Post,
                    ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(
                            File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("WsTrustResponse13.xml")))
                    }
                });

                var requestContext  = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null));
                var wsTrustRequest  = endpoint.BuildTokenRequestMessageWindowsIntegratedAuth("urn:federation:SomeAudience");
                var wsTrustResponse = await serviceBundle.WsTrustWebRequestManager.GetWsTrustResponseAsync(endpoint, wsTrustRequest, requestContext)
                                      .ConfigureAwait(false);

                Assert.IsNotNull(wsTrustResponse.Token);
            }
        }
        public void B2CLoginAuthorityEndpoints()
        {
            using (var httpManager = new MockHttpManager())
            {
                var appConfig = new ApplicationConfiguration()
                {
                    HttpManager   = httpManager,
                    AuthorityInfo = AuthorityInfo.FromAuthorityUri(
                        "https://sometenantid.b2clogin.com/tfp/6babcaad-604b-40ac-a9d7-9fd97c0b779f/b2c_1_susi/", true)
                };

                var serviceBundle = ServiceBundle.Create(appConfig);

                Authority instance = Authority.CreateAuthority(
                    "https://sometenantid.b2clogin.com/tfp/6babcaad-604b-40ac-a9d7-9fd97c0b779f/b2c_1_susi/");
                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/tfp/6babcaad-604b-40ac-a9d7-9fd97c0b779f/b2c_1_susi/oauth2/v2.0/authorize",
                    endpoints.AuthorizationEndpoint);
                Assert.AreEqual(
                    "https://sometenantid.b2clogin.com/tfp/6babcaad-604b-40ac-a9d7-9fd97c0b779f/b2c_1_susi/oauth2/v2.0/token",
                    endpoints.TokenEndpoint);
                Assert.AreEqual("https://sometenantid.b2clogin.com/tfp/6babcaad-604b-40ac-a9d7-9fd97c0b779f/b2c_1_susi/oauth2/v2.0/token",
                                endpoints.SelfSignedJwtAudience);
            }
        }
        public async Task WsTrustRequestFailureTestAsync()
        {
            string uri      = "https://some/address/usernamemixed";
            var    endpoint = new WsTrustEndpoint(new Uri(uri), WsTrustVersion.WsTrust13);

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddMockHandlerContentNotFound(HttpMethod.Post, url: uri);

                var requestContext = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null));
                try
                {
                    var message = endpoint.BuildTokenRequestMessageWindowsIntegratedAuth("urn:federation:SomeAudience");

                    WsTrustResponse wstResponse =
                        await serviceBundle.WsTrustWebRequestManager.GetWsTrustResponseAsync(endpoint, message, requestContext).ConfigureAwait(false);

                    Assert.Fail("We expect an exception to be thrown here");
                }
                catch (MsalException ex)
                {
                    Assert.AreEqual(CoreErrorCodes.FederatedServiceReturnedError, ex.ErrorCode);
                }
            }
        }
        public void CanonicalAuthorityInitTest()
        {
            var serviceBundle = ServiceBundle.CreateDefault();

            const string UriNoPort          = CoreTestConstants.B2CAuthority;
            const string UriNoPortTailSlash = CoreTestConstants.B2CAuthority;

            const string UriDefaultPort = "https://login.microsoftonline.in:443/tfp/tenant/policy";

            const string UriCustomPort          = "https://login.microsoftonline.in:444/tfp/tenant/policy";
            const string UriCustomPortTailSlash = "https://login.microsoftonline.in:444/tfp/tenant/policy/";
            const string UriVanityPort          = CoreTestConstants.B2CLoginAuthority;

            var authority = new B2CAuthority(serviceBundle, UriNoPort, false);

            Assert.AreEqual(UriNoPortTailSlash, authority.CanonicalAuthority);

            authority = new B2CAuthority(serviceBundle, UriDefaultPort, false);
            Assert.AreEqual(UriNoPortTailSlash, authority.CanonicalAuthority);

            authority = new B2CAuthority(serviceBundle, UriCustomPort, false);
            Assert.AreEqual(UriCustomPortTailSlash, authority.CanonicalAuthority);

            authority = new B2CAuthority(serviceBundle, UriVanityPort, false);
            Assert.AreEqual(UriVanityPort, authority.CanonicalAuthority);
        }
示例#5
0
        public void ValidationOffSuccessTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                // add mock response for tenant endpoint discovery
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method          = HttpMethod.Get,
                    Url             = "https://fs.contoso.com/adfs/.well-known/openid-configuration",
                    ResponseMessage =
                        MockHelpers.CreateSuccessResponseMessage(
                            ResourceHelper.GetTestResourceRelativePath(File.ReadAllText("OpenidConfiguration-OnPremise.json")))
                });

                Authority instance = Authority.CreateAuthority(serviceBundle, CoreTestConstants.OnPremiseAuthority, false);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityType, AuthorityType.Adfs);
                Task.Run(
                    async() =>
                {
                    await instance.ResolveEndpointsAsync(
                        CoreTestConstants.FabrikamDisplayableId,
                        new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))).ConfigureAwait(false);
                }).GetAwaiter().GetResult();

                Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/authorize/", instance.AuthorizationEndpoint);
                Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/token/", instance.TokenEndpoint);
                Assert.AreEqual("https://fs.contoso.com/adfs", instance.SelfSignedJwtAudience);
            }
        }
        public void TestDeviceCodeCancel()
        {
            using (var httpManager = new MockHttpManager())
            {
                var       serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                const int NumberOfAuthorizationPendingRequestsToInject = 0;
                var       parameters = CreateAuthenticationParametersAndSetupMocks(
                    httpManager,
                    NumberOfAuthorizationPendingRequestsToInject,
                    out HashSet <string> expectedScopes);

                _cache.ServiceBundle = serviceBundle;

                var cancellationSource = new CancellationTokenSource();

                DeviceCodeResult actualDeviceCodeResult = null;
                var request = new DeviceCodeRequest(
                    serviceBundle,
                    parameters,
                    ApiEvent.ApiIds.None,
                    async result =>
                {
                    await Task.Delay(200, CancellationToken.None).ConfigureAwait(false);
                    actualDeviceCodeResult = result;
                });

                // We setup the cancel before calling the RunAsync operation since we don't check the cancel
                // until later and the mock network calls run insanely fast for us to timeout for them.
                cancellationSource.Cancel();
                AssertException.TaskThrows <OperationCanceledException>(() => request.RunAsync(cancellationSource.Token));
            }
        }
示例#7
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);
        }
        public async Task ValidateAuthorityFalse_SkipsNetworkCall_Async()
        {
            // Arrange
            var validationException = new MsalServiceException(MsalError.InvalidInstance, "authority validation failed");

            // Inject authority in service bundle
            var httpManager = new MockHttpManager();
            var appConfig   = new ApplicationConfiguration()
            {
                HttpManager   = httpManager,
                AuthorityInfo = AuthorityInfo.FromAuthorityUri(Authority, false)
            };

            var serviceBundle = ServiceBundle.Create(appConfig);

            RequestContext requestContext = new RequestContext(serviceBundle, Guid.NewGuid());

            // network fails with invalid_instance exception
            _networkMetadataProvider
            .When(x => x.GetMetadataAsync(Arg.Any <Uri>(), requestContext))
            .Do(x => throw validationException);

            InstanceDiscoveryMetadataEntry actualResult = await _discoveryManager.GetMetadataEntryAsync(Authority, requestContext).ConfigureAwait(false);

            // Since the validateAuthority is set to false, proceed without alias.
            ValidateSingleEntryMetadata(new Uri(Authority), actualResult);
        }
示例#9
0
 private static async Task RunWithMockHttpAsync(Func <MockHttpManager, IServiceBundle, MyReceiver, Task> action)
 {
     using (var httpManager = new MockHttpManager())
     {
         var receiver      = new MyReceiver();
         var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager, receiver);
         await action(httpManager, serviceBundle, receiver).ConfigureAwait(false);
     }
 }
示例#10
0
 private static void RunWithMockHttp(Action <MockHttpManager, IServiceBundle, MyReceiver> action)
 {
     using (var httpManager = new MockHttpManager())
     {
         var receiver      = new MyReceiver();
         var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager, receiver);
         action(httpManager, serviceBundle, receiver);
     }
 }
        public void ExpiredTokenRefreshFlowTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var        serviceBundle        = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                var        aadInstanceDiscovery = new AadInstanceDiscovery(httpManager, new TelemetryManager());
                Authority  authority            = Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityHomeTenant, false);
                TokenCache cache = new TokenCache()
                {
                    ClientId      = MsalTestConstants.ClientId,
                    ServiceBundle = serviceBundle
                };
                _tokenCacheHelper.PopulateCache(cache.TokenCacheAccessor);

                AuthenticationRequestParameters parameters = new AuthenticationRequestParameters()
                {
                    Authority      = authority,
                    ClientId       = MsalTestConstants.ClientId,
                    Scope          = MsalTestConstants.Scope,
                    TokenCache     = cache,
                    RequestContext = new RequestContext(null, new MsalLogger(Guid.Empty, null)),
                    Account        = new Account(MsalTestConstants.UserIdentifier, MsalTestConstants.DisplayableId, null)
                };

                // set access tokens as expired
                foreach (var atCacheItemStr in cache.GetAllAccessTokenCacheItems(new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))))
                {
                    MsalAccessTokenCacheItem accessItem =
                        JsonHelper.DeserializeFromJson <MsalAccessTokenCacheItem>(atCacheItemStr);
                    accessItem.ExpiresOnUnixTimestamp =
                        ((long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds).ToString(CultureInfo.InvariantCulture);

                    cache.AddAccessTokenCacheItem(accessItem);
                }
                TestCommon.MockInstanceDiscoveryAndOpenIdRequest(httpManager);

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

                var crypto = PlatformProxyFactory.GetPlatformProxy().CryptographyManager;

                SilentRequest request = new SilentRequest(
                    serviceBundle,
                    parameters,
                    ApiEvent.ApiIds.None,
                    false);

                Task <AuthenticationResult> task   = request.RunAsync(CancellationToken.None);
                AuthenticationResult        result = task.Result;
                Assert.IsNotNull(result);
                Assert.AreEqual("some-access-token", result.AccessToken);
                Assert.AreEqual(MsalTestConstants.Scope.AsSingleString(), result.Scopes.AsSingleString());
            }
        }
示例#12
0
        public void FailedValidationResourceNotInTrustedRealmTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                //add mock 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.json")))
                });


                //add mock response for on-premise webfinger request
                httpManager.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(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 SuccessfulValidationTest()
        {
            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.microsoftonline.com/common/discovery/instance",
                    QueryParams = new Dictionary <string, string>
                    {
                        { "api-version", "1.1" },
                        {
                            "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
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method          = HttpMethod.Get,
                    Url             = "https://login.microsoftonline.in/mytenant.com/.well-known/openid-configuration",
                    ResponseMessage = MockHelpers.CreateSuccessResponseMessage(
                        File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("OpenidConfiguration.json")))
                });

                Authority instance = Authority.CreateAuthority(serviceBundle, "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(null, new MsalLogger(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("https://login.microsoftonline.in/common/userrealm/", instance.UserRealmUriPrefix);
            }
        }
示例#14
0
        public void GetExactScopesMatchedAccessTokenTest()
        {
            var atItem = Credential.CreateAccessToken(
                MsalTestConstants.HomeAccountId,
                MsalTestConstants.ProductionPrefNetworkEnvironment,
                new Uri(MsalTestConstants.AuthorityTestTenant).GetRealm(),
                MsalTestConstants.ClientId,
                ScopeUtils.JoinScopes(MsalTestConstants.Scope),
                TimeUtils.GetSecondsFromEpochNow(),
                TimeUtils.GetSecondsFromEpochNow() + MsalCacheV2TestConstants.ValidExpiresIn,
                TimeUtils.GetSecondsFromEpochNow() + MsalCacheV2TestConstants.ValidExtendedExpiresIn,
                TheSecret,
                string.Empty);

            _storageWorker.WriteCredentials(
                new List <Credential>
            {
                atItem
            });

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                var cacheManager = new CacheManager(
                    _storageManager,
                    new AuthenticationRequestParameters
                {
                    Account = MsalTestConstants.User,

                    // TODO:  In MSALC++, the request parameters only really needs the
                    // Authority URI itself since the cache isn't meant to
                    // do ANY network calls.
                    // So it would be great if we could reduce the complexity/dependencies
                    // here and do any of the validated authority cache / instance discovery
                    // outside of the context of the authentication parameters and
                    // cache interaction and just track the authority we're using...

                    // AccountId = MsalTestConstants.HomeAccountId,
                    // Authority = new Uri(MsalTestConstants.AuthorityTestTenant),
                    Authority = Authority.CreateAuthority(
                        serviceBundle,
                        MsalTestConstants.AuthorityTestTenant,
                        false),
                    ClientId = MsalTestConstants.ClientId,
                    Scope    = new SortedSet <string>(MsalCacheV2TestConstants.Scope) // todo(mzuber):  WHY SORTED SET?
                });

                Assert.IsTrue(cacheManager.TryReadCache(out var tokenResponse, out var accountResponse));
                Assert.IsNotNull(tokenResponse);
                Assert.IsNull(accountResponse);

                Assert.AreEqual(TheSecret, tokenResponse.AccessToken);
            }
        }
        public void OAuthClient_FailsWithServiceExceptionWhenResponseIsHttpNotFound()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager, _myReceiver);

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

                var responseMessage = MockHelpers.CreateHttpStatusNotFoundResponseMessage();

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

                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 serverEx = exc.InnerException as MsalServiceException;
                    Assert.IsNotNull(serverEx);
                    Assert.AreEqual((int)HttpStatusCode.NotFound, serverEx.StatusCode);
                    Assert.IsNotNull(serverEx.ResponseBody);
                    Assert.AreEqual(MsalError.HttpStatusNotFound, serverEx.ErrorCode);
                }
            }
        }
        public void TestDeviceCodeAuthSuccess()
        {
            const int NumberOfAuthorizationPendingRequestsToInject = 1;

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                var parameters = CreateAuthenticationParametersAndSetupMocks(
                    httpManager,
                    NumberOfAuthorizationPendingRequestsToInject,
                    out HashSet <string> expectedScopes);

                _cache.ServiceBundle = serviceBundle;

                // Check that cache is empty
                Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount);
                Assert.AreEqual(0, _cache.TokenCacheAccessor.AccountCount);
                Assert.AreEqual(0, _cache.TokenCacheAccessor.IdTokenCount);
                Assert.AreEqual(0, _cache.TokenCacheAccessor.RefreshTokenCount);

                DeviceCodeResult actualDeviceCodeResult = null;
                var request = new DeviceCodeRequest(
                    serviceBundle,
                    parameters,
                    ApiEvent.ApiIds.None,
                    result =>
                {
                    actualDeviceCodeResult = result;
                    return(Task.FromResult(0));
                });
                Task <AuthenticationResult> task = request.RunAsync(CancellationToken.None);
                task.Wait();
                var authenticationResult = task.Result;
                Assert.IsNotNull(authenticationResult);
                Assert.IsNotNull(actualDeviceCodeResult);

                Assert.AreEqual(MsalTestConstants.ClientId, actualDeviceCodeResult.ClientId);
                Assert.AreEqual(ExpectedDeviceCode, actualDeviceCodeResult.DeviceCode);
                Assert.AreEqual(ExpectedInterval, actualDeviceCodeResult.Interval);
                Assert.AreEqual(ExpectedMessage, actualDeviceCodeResult.Message);
                Assert.AreEqual(ExpectedUserCode, actualDeviceCodeResult.UserCode);
                Assert.AreEqual(ExpectedVerificationUrl, actualDeviceCodeResult.VerificationUrl);

                CoreAssert.AreScopesEqual(expectedScopes.AsSingleString(), actualDeviceCodeResult.Scopes.AsSingleString());

                // Validate that entries were added to cache
                Assert.AreEqual(1, _cache.TokenCacheAccessor.AccessTokenCount);
                Assert.AreEqual(1, _cache.TokenCacheAccessor.AccountCount);
                Assert.AreEqual(1, _cache.TokenCacheAccessor.IdTokenCount);
                Assert.AreEqual(1, _cache.TokenCacheAccessor.RefreshTokenCount);
            }
        }
            public ServiceBundle AddServiceBundle(string ServiceBundleName, string ServiceCategoryCode, string ServiceCode)
            {
                ServiceBundle rowServiceBundle = ((ServiceBundle)(this.NewRow()));

                rowServiceBundle.ItemArray = new object[] {
                    ServiceBundleName,
                    ServiceCategoryCode,
                    ServiceCode
                };
                this.Rows.Add(rowServiceBundle);
                return(rowServiceBundle);
            }
        public void MexEndpointFailsToResolveTest()
        {
            var ui = new MockWebUI
            {
                MockResult = new AuthorizationResult(
                    AuthorizationStatus.Success,
                    MsalTestConstants.AuthorityOrganizationsTenant + "?code=some-code")
            };

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityOrganizationsTenant);
                AddMockHandlerDefaultUserRealmDiscovery(httpManager);

                // MEX
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Url             = "https://msft.sts.microsoft.com/adfs/services/trust/mex",
                    Method          = HttpMethod.Get,
                    ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(
                            File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("TestMex.xml"))
                            .Replace("<wsp:All>", " "))
                    }
                });

                _cache.ClientId = MsalTestConstants.ClientId;
                var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId,
                                                      ClientApplicationBase.DefaultAuthority)
                {
                    UserTokenCache = _cache
                };

                // Call acquire token, Mex parser fails
                var result = AssertException.TaskThrows <MsalException>(
                    async() => await app.AcquireTokenByUsernamePasswordAsync(
                        MsalTestConstants.Scope,
                        MsalTestConstants.User.Username,
                        _secureString).ConfigureAwait(false));

                // Check exception message
                Assert.AreEqual("Parsing WS metadata exchange failed", result.Message);
                Assert.AreEqual("parsing_ws_metadata_exchange_failed", result.ErrorCode);

                // There should be no cached entries.
                Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount);
            }
        }
        public void ManagedUsernamePasswordCommonAuthorityTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityCommonTenant);

                // user realm discovery
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method          = HttpMethod.Get,
                    ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(
                            "{\"ver\":\"1.0\",\"account_type\":\"Managed\",\"domain_name\":\"id.com\"}")
                    },
                    QueryParams = new Dictionary <string, string>
                    {
                        { "api-version", "1.0" }
                    }
                });

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

                _cache.ClientId = MsalTestConstants.ClientId;
                var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId,
                                                      ClientApplicationBase.DefaultAuthority)
                {
                    UserTokenCache = _cache
                };

                // Call acquire token
                var result = AssertException.TaskThrows <MsalException>(
                    async() => await app.AcquireTokenByUsernamePasswordAsync(
                        MsalTestConstants.Scope,
                        MsalTestConstants.User.Username,
                        _secureString).ConfigureAwait(false));

                // Check inner exception
                Assert.AreEqual(CoreErrorCodes.InvalidRequest, result.ErrorCode);

                // There should be no cached entries.
                Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount);
            }
        }
        public void FailedValidationTest()
        {
            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.microsoftonline.com/common/discovery/instance",
                    QueryParams = 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(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.IsTrue(exc is MsalServiceException);
                    Assert.AreEqual(((MsalServiceException)exc).ErrorCode, "invalid_instance");
                }
            }
        }
        public void FederatedUsernamePasswordCommonAuthorityTest()
        {
            var ui = new MockWebUI
            {
                MockResult = new AuthorizationResult(
                    AuthorizationStatus.Success,
                    MsalTestConstants.AuthorityCommonTenant + "?code=some-code")
            };

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityCommonTenant);
                AddMockHandlerDefaultUserRealmDiscovery(httpManager);
                AddMockHandlerMex(httpManager);
                AddMockHandlerWsTrustUserName(httpManager);

                // AAD
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Url             = "https://login.microsoftonline.com/common/oauth2/v2.0/token",
                    Method          = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateInvalidRequestTokenResponseMessage()
                });

                _cache.ClientId = MsalTestConstants.ClientId;
                var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId,
                                                      ClientApplicationBase.DefaultAuthority)
                {
                    UserTokenCache = _cache
                };

                // Call acquire token
                var result = AssertException.TaskThrows <MsalException>(
                    async() => await app.AcquireTokenByUsernamePasswordAsync(
                        MsalTestConstants.Scope,
                        MsalTestConstants.User.Username,
                        _secureString).ConfigureAwait(false));

                // Check inner exception
                Assert.AreEqual(CoreErrorCodes.InvalidRequest, result.ErrorCode);

                // There should be no cached entries.
                Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount);
            }
        }
        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);
                }
            }
        }
示例#23
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);
        }
        public void ManagedUsernameIncorrectPasswordAcquireTokenTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddInstanceDiscoveryMockHandler();
                AddMockResponseforManagedAccounts(httpManager);

                var str = new SecureString();
                str.AppendChar('y');
                str.MakeReadOnly();

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method          = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateInvalidGrantTokenResponseMessage(),
                    PostDataObject  = new Dictionary <string, object>
                    {
                        { "grant_type", "password" },
                        { "username", MsalTestConstants.User.Username },
                        { "password", _secureString }
                    }
                });

                _cache.ClientId = MsalTestConstants.ClientId;
                var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId,
                                                      ClientApplicationBase.DefaultAuthority)
                {
                    UserTokenCache = _cache
                };

                // Call acquire token
                var result = AssertException.TaskThrows <MsalException>(
                    async() => await app.AcquireTokenByUsernamePasswordAsync(
                        MsalTestConstants.Scope,
                        MsalTestConstants.User.Username,
                        str).ConfigureAwait(false));

                // Check error code
                Assert.AreEqual(CoreErrorCodes.InvalidGrantError, result.ErrorCode);

                // There should be no cached entries.
                Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount);
            }
        }
        public void FederatedUsernameNullPasswordTest()
        {
            var ui = new MockWebUI
            {
                MockResult = new AuthorizationResult(
                    AuthorizationStatus.Success,
                    MsalTestConstants.AuthorityOrganizationsTenant + "?code=some-code")
            };

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityOrganizationsTenant);
                AddMockHandlerDefaultUserRealmDiscovery(httpManager);
                AddMockHandlerMex(httpManager);

                // Mex does not return integrated auth endpoint (.../13/windowstransport)
                httpManager.AddMockHandlerContentNotFound(HttpMethod.Post,
                                                          "https://msft.sts.microsoft.com/adfs/services/trust/13/windowstransport");

                _cache.ClientId = MsalTestConstants.ClientId;
                var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId,
                                                      ClientApplicationBase.DefaultAuthority)
                {
                    UserTokenCache = _cache
                };

                SecureString str = null;

                // Call acquire token
                var result = AssertException.TaskThrows <MsalException>(
                    async() => await app.AcquireTokenByUsernamePasswordAsync(
                        MsalTestConstants.Scope,
                        MsalTestConstants.User.Username,
                        str).ConfigureAwait(false));

                // Check inner exception
                Assert.AreEqual(CoreErrorCodes.ParsingWsTrustResponseFailed, result.ErrorCode);

                // There should be no cached entries.
                Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount);
            }
        }
示例#26
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);
            }
        }
        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 MexParsingFailsTest()
        {
            var ui = new MockWebUI
            {
                MockResult = new AuthorizationResult(
                    AuthorizationStatus.Success,
                    MsalTestConstants.AuthorityOrganizationsTenant + "?code=some-code")
            };

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityOrganizationsTenant);
                AddMockHandlerDefaultUserRealmDiscovery(httpManager);

                // MEX
                httpManager.AddMockHandlerContentNotFound(HttpMethod.Get,
                                                          "https://msft.sts.microsoft.com/adfs/services/trust/mex");

                _cache.ClientId = MsalTestConstants.ClientId;

                var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId,
                                                      ClientApplicationBase.DefaultAuthority)
                {
                    UserTokenCache = _cache
                };

                // Call acquire token
                var result = AssertException.TaskThrows <MsalException>(
                    async() => await app.AcquireTokenByUsernamePasswordAsync(
                        MsalTestConstants.Scope,
                        MsalTestConstants.User.Username,
                        _secureString).ConfigureAwait(false));

                // Check inner exception
                Assert.AreEqual("Response status code does not indicate success: 404 (NotFound).", result.Message);

                // There should be no cached entries.
                Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount);
            }
        }
        public async Task MexEndpointFailsToResolveTestAsync()
        {
            // TODO: should we move this into a separate test class for WsTrustWebRequestManager?
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddMockHandlerContentNotFound(HttpMethod.Get);

                try
                {
                    await serviceBundle.WsTrustWebRequestManager.GetMexDocumentAsync("http://somehost", _requestContext).ConfigureAwait(false);

                    Assert.Fail("We expect an exception to be thrown here");
                }
                catch (MsalException ex)
                {
                    Assert.AreEqual(CoreErrorCodes.AccessingWsMetadataExchangeFailed, ex.ErrorCode);
                }
            }
        }
        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);
                }
            }
        }
		/// <summary>
		/// Creates new <see cref="ServiceBundleWrapper"/> instance
		/// </summary>
		protected ServiceBundleWrapper()
		{
			this.wrappedBundle = new ServiceBundle();
		}