Ejemplo n.º 1
0
        public void DuplicateQueryParameterErrorTest()
        {
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false, Guid.NewGuid());

            HandlerData data = new HandlerData()
            {
                Authenticator        = authenticator,
                ClientKey            = new ClientKey(TestConstants.DefaultClientId),
                Policy               = TestConstants.DefaultPolicy,
                RestrictToSingleUser = TestConstants.DefaultRestrictToSingleUser,
                Scope      = TestConstants.DefaultScope.ToArray(),
                TokenCache = null
            };

            AcquireTokenInteractiveHandler handler = new AcquireTokenInteractiveHandler(data,
                                                                                        TestConstants.ScopeForAnotherResource.ToArray(),
                                                                                        new Uri("some://uri"), new PlatformParameters(),
                                                                                        (User)null, UiOptions.ForceLogin, "extra=qp&prompt=login", new MockWebUI());

            handler.PreRunAsync().Wait();

            try
            {
                handler.PreTokenRequest().Wait();
                Assert.Fail("MsalException should be thrown here");
            }
            catch (Exception exc)
            {
                Assert.IsTrue(exc.InnerException is MsalException);
                Assert.AreEqual(MsalError.DuplicateQueryParameter, ((MsalException)exc.InnerException).ErrorCode);
            }
        }
        public void AcquireTokenInteractiveHandlerConstructor_InitializeBrokerParameters()
        {
            var acquireTokenInteractiveHandler = new AcquireTokenInteractiveHandler(_requestData,
                                                                                    TestConstants.DefaultRedirectUri, null, UserIdentifier.AnyUser,
                                                                                    ExtraQueryParameters, null, Claims);

            Assert.AreEqual(11, acquireTokenInteractiveHandler.brokerParameters.Count);

            var brokerParams = acquireTokenInteractiveHandler.brokerParameters;

            Assert.AreEqual(CanonicalizedAuthority, brokerParams[BrokerParameter.Authority]);
            Assert.AreEqual(Resource, brokerParams[BrokerParameter.Resource]);
            Assert.AreEqual(ClientId, brokerParams[BrokerParameter.ClientId]);

            Assert.AreEqual(acquireTokenInteractiveHandler.CallState.CorrelationId.ToString(), brokerParams[BrokerParameter.CorrelationId]);
            Assert.AreEqual(AdalIdHelper.GetClientVersion(), brokerParams[BrokerParameter.ClientVersion]);
            Assert.AreEqual("NO", brokerParams[BrokerParameter.Force]);
            Assert.AreEqual(string.Empty, brokerParams[BrokerParameter.Username]);
            Assert.AreEqual(UserIdentifierType.OptionalDisplayableId.ToString(), brokerParams[BrokerParameter.UsernameType]);

            Assert.AreEqual(TestConstants.DefaultRedirectUri, brokerParams[BrokerParameter.RedirectUri]);

            Assert.AreEqual(ExtraQueryParameters, brokerParams[BrokerParameter.ExtraQp]);
            Assert.AreEqual(Claims, brokerParams[BrokerParameter.Claims]);
        }
Ejemplo n.º 3
0
        public void NullUserForActAsCurrentUserTest()
        {
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false, Guid.NewGuid());

            try
            {
                HandlerData data = new HandlerData()
                {
                    Authenticator        = authenticator,
                    ClientKey            = new ClientKey(TestConstants.DefaultClientId),
                    Policy               = TestConstants.DefaultPolicy,
                    RestrictToSingleUser = TestConstants.DefaultRestrictToSingleUser,
                    Scope      = TestConstants.DefaultScope.ToArray(),
                    TokenCache = null
                };

                AcquireTokenInteractiveHandler handler = new AcquireTokenInteractiveHandler(data,
                                                                                            TestConstants.ScopeForAnotherResource.ToArray(), new Uri("some://uri"), new PlatformParameters(),
                                                                                            (User)null, UiOptions.ActAsCurrentUser, "extra=qp", new MockWebUI());
                Assert.Fail("ArgumentException should be thrown here");
            }
            catch (ArgumentException ae)
            {
                Assert.IsTrue(ae.Message.Contains(MsalErrorMessage.LoginHintNullForUiOption));
            }
        }
Ejemplo n.º 4
0
        public void CacheWithMultipleUsersAndRestrictToSingleUserTrueTest()
        {
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false, Guid.NewGuid());
            TokenCache    cache         = TokenCacheHelper.CreateCacheWithItems();

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

                AcquireTokenInteractiveHandler handler = new AcquireTokenInteractiveHandler(data,
                                                                                            TestConstants.ScopeForAnotherResource.ToArray(),
                                                                                            new Uri("some://uri"), new PlatformParameters(),
                                                                                            new User {
                    UniqueId = TestConstants.DefaultUniqueId
                }, UiOptions.ForceLogin, "extra=qp",
                                                                                            new MockWebUI());
                Assert.Fail("ArgumentException should be thrown here");
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual(
                    "Cache cannot have entries for more than 1 unique id when RestrictToSingleUser is set to TRUE.",
                    ae.Message);
            }
        }
Ejemplo n.º 5
0
        public void VerifyAuthorizationResultTest()
        {
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false, Guid.NewGuid());

            MockWebUI webUi = new MockWebUI();

            webUi.MockResult = new AuthorizationResult(AuthorizationStatus.ErrorHttp,
                                                       TestConstants.DefaultAuthorityHomeTenant + "?error=" + OAuthError.LoginRequired);

            HandlerData data = new HandlerData()
            {
                Authenticator        = authenticator,
                ClientKey            = new ClientKey(TestConstants.DefaultClientId),
                Policy               = TestConstants.DefaultPolicy,
                RestrictToSingleUser = TestConstants.DefaultRestrictToSingleUser,
                Scope      = TestConstants.DefaultScope.ToArray(),
                TokenCache = null
            };

            AcquireTokenInteractiveHandler handler = new AcquireTokenInteractiveHandler(data,
                                                                                        TestConstants.ScopeForAnotherResource.ToArray(), new Uri("some://uri"), new PlatformParameters(),
                                                                                        (string)null, UiOptions.ForceLogin, "extra=qp", webUi);

            handler.PreRunAsync().Wait();
            try
            {
                handler.PreTokenRequest().Wait();
                Assert.Fail("MsalException should have been thrown here");
            }
            catch (Exception exc)
            {
                Assert.IsTrue(exc.InnerException is MsalException);
                Assert.AreEqual(MsalError.UserInteractionRequired, ((MsalException)exc.InnerException).ErrorCode);
            }


            webUi            = new MockWebUI();
            webUi.MockResult = new AuthorizationResult(AuthorizationStatus.ErrorHttp,
                                                       TestConstants.DefaultAuthorityHomeTenant + "?error=invalid_request&error_description=some error description");

            handler = new AcquireTokenInteractiveHandler(data,
                                                         TestConstants.ScopeForAnotherResource.ToArray(), new Uri("some://uri"), new PlatformParameters(),
                                                         (string)null, UiOptions.ForceLogin, "extra=qp", webUi);
            handler.PreRunAsync().Wait();

            try
            {
                handler.PreTokenRequest().Wait();
                Assert.Fail("MsalException should have been thrown here");
            }
            catch (Exception exc)
            {
                Assert.IsTrue(exc.InnerException is MsalException);
                Assert.AreEqual("invalid_request", ((MsalException)exc.InnerException).ErrorCode);
                Assert.AreEqual("some error description", ((MsalException)exc.InnerException).Message);
            }
        }
Ejemplo n.º 6
0
        public static string AcquireAccessCode(AuthenticationContext context, string resource, string clientId, Uri redirectUri, UserIdentifier userId)
        {
            var handler = new AcquireTokenInteractiveHandler(context.Authenticator, context.TokenCache, resource, clientId, redirectUri, PromptBehavior.Auto, userId, null,
                                                             context.CreateWebAuthenticationDialog(PromptBehavior.Auto), true);

            handler.CallState = null;
            context.Authenticator.AuthorizationUri = context.Authority + "oauth2/authorize";
            handler.AcquireAuthorization();
            return(handler.authorizationResult.Code);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Gets URL of the authorize endpoint including the query parameters.
        /// </summary>
        /// <param name="scope"></param>
        /// <param name="redirectUri"></param>
        /// <param name="loginHint"></param>
        /// <param name="extraQueryParameters"></param>
        /// <param name="additionalScope"></param>
        /// <param name="authority"></param>
        /// <param name="policy"></param>
        /// <returns>URL of the authorize endpoint including the query parameters.</returns>
        public async Task <Uri> GetAuthorizationRequestUrlAsync(string[] scope, string redirectUri, string loginHint, string extraQueryParameters, string[] additionalScope, string authority, string policy)
        {
            Authenticator authenticator = new Authenticator(authority, this.ValidateAuthority, this.CorrelationId);
            HandlerData   data          = this.GetHandlerData(authenticator, scope, policy, this.UserTokenCache);

            data.ClientKey = new ClientKey(this.ClientId);
            var handler =
                new AcquireTokenInteractiveHandler(data, additionalScope,
                                                   new Uri(redirectUri), null, loginHint, null, extraQueryParameters, null);

            return(await handler.CreateAuthorizationUriAsync(this.CorrelationId).ConfigureAwait(false));
        }
        private async Task <AuthenticationResult> AcquireTokenCommonAsync(Authenticator authenticator, string[] scope, string[] additionalScope, Uri redirectUri, User user, UiOptions uiOptions, string extraQueryParameters, string policy)
        {
            if (this.PlatformParameters == null)
            {
                this.PlatformParameters = PlatformPlugin.DefaultPlatformParameters;
            }

            var handler =
                new AcquireTokenInteractiveHandler(
                    this.GetHandlerData(authenticator, scope, policy, this.UserTokenCache), additionalScope, redirectUri,
                    this.PlatformParameters, user, uiOptions, extraQueryParameters,
                    this.CreateWebAuthenticationDialog(this.PlatformParameters));

            return(await handler.RunAsync().ConfigureAwait(false));
        }
Ejemplo n.º 9
0
        public void ActAsCurrentUserNoSsoHeaderForLoginHintOnlyTest()
        {
            //this test validates that no SSO header is added when developer passes only login hint and UiOption.ActAsCurrentUser
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false, Guid.NewGuid());
            TokenCache    cache         = new TokenCache();
            TokenCacheKey key           = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                                            TestConstants.DefaultScope, TestConstants.DefaultClientId,
                                                            TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                                                            TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();

            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                                                 new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3599)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId      = TestConstants.DefaultUniqueId,
                HomeObjectId  = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken    = "someRT";
            cache.tokenCacheDictionary[key] = ex;

            MockWebUI webUi = new MockWebUI();

            webUi.MockResult = new AuthorizationResult(AuthorizationStatus.Success,
                                                       TestConstants.DefaultAuthorityHomeTenant + "?code=some-code");

            HandlerData data = new HandlerData()
            {
                Authenticator        = authenticator,
                ClientKey            = new ClientKey(TestConstants.DefaultClientId),
                Policy               = TestConstants.DefaultPolicy,
                RestrictToSingleUser = TestConstants.DefaultRestrictToSingleUser,
                Scope      = TestConstants.DefaultScope.ToArray(),
                TokenCache = cache
            };

            AcquireTokenInteractiveHandler handler = new AcquireTokenInteractiveHandler(data,
                                                                                        TestConstants.ScopeForAnotherResource.ToArray(),
                                                                                        new Uri("some://uri"), new PlatformParameters(),
                                                                                        ex.Result.User, UiOptions.ActAsCurrentUser, "extra=qp", webUi);

            handler.PreRunAsync().Wait();
            handler.PreTokenRequest().Wait();
        }
Ejemplo n.º 10
0
        public void NoCacheLookup()
        {
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false, Guid.NewGuid());
            TokenCache    cache         = new TokenCache();
            TokenCacheKey key           = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                                            TestConstants.DefaultScope, TestConstants.DefaultClientId,
                                                            TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                                                            TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();

            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                                                 new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3599)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId      = TestConstants.DefaultUniqueId,
                HomeObjectId  = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken    = "someRT";
            cache.tokenCacheDictionary[key] = ex;

            IWebUI ui = Substitute.For <IWebUI>();
            AuthorizationResult ar = new AuthorizationResult(AuthorizationStatus.Success,
                                                             TestConstants.DefaultAuthorityHomeTenant + "?code=some-code");

            ui.AcquireAuthorizationAsync(Arg.Any <Uri>(), Arg.Any <Uri>(), Arg.Any <IDictionary <string, string> >(),
                                         Arg.Any <CallState>())
            .Returns(ar);

            MockHttpMessageHandler mockHandler = new MockHttpMessageHandler();

            mockHandler.Method      = HttpMethod.Post;
            mockHandler.QueryParams = new Dictionary <string, string>()
            {
                { "p", "some-policy" }
            };

            mockHandler.ResponseMessage           = MockHelpers.CreateSuccessTokenResponseMessage();
            HttpMessageHandlerFactory.MockHandler = mockHandler;

            HandlerData data = new HandlerData()
            {
                Authenticator        = authenticator,
                ClientKey            = new ClientKey(TestConstants.DefaultClientId),
                Policy               = "some-policy",
                RestrictToSingleUser = TestConstants.DefaultRestrictToSingleUser,
                Scope      = TestConstants.DefaultScope.ToArray(),
                TokenCache = cache
            };

            AcquireTokenInteractiveHandler handler = new AcquireTokenInteractiveHandler(data,
                                                                                        TestConstants.ScopeForAnotherResource.ToArray(),
                                                                                        new Uri("some://uri"), new PlatformParameters(), TestConstants.DefaultDisplayableId,
                                                                                        UiOptions.SelectAccount, "extra=qp", ui);
            Task <AuthenticationResult> task = handler.RunAsync();

            task.Wait();
            AuthenticationResult result = task.Result;

            Assert.IsNotNull(result);
            Assert.AreEqual(2, cache.Count);
            Assert.AreEqual(result.Token, "some-access-token");

            //both cache entry authorities are TestConstants.DefaultAuthorityHomeTenant
            foreach (var item in cache.ReadItems(TestConstants.DefaultClientId))
            {
                Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, item.Authority);
            }
        }
 //[Description("Test to verify forms auth parameters.")]
 public async Task IncludeFormsAuthParamsTest()
 {
     Verify.IsFalse(await AcquireTokenInteractiveHandler.IncludeFormsAuthParamsAsync(null));
 }
 public void IncludeFormsAuthParamsTest()
 {
     Assert.IsFalse(AcquireTokenInteractiveHandler.IncludeFormsAuthParams());
 }