Esempio n. 1
0
        public void SignInCommand_Run_MapsReturnUrl()
        {
            var defaultDestination = Options.FromConfiguration.IdentityProviders.Default.SingleSignOnServiceUrl;

            var httpRequest = new HttpRequestData("GET", new Uri("http://localhost/signin?ReturnUrl=%2FReturn.aspx"));

            var actual = new SignInCommand().Run(httpRequest, Options.FromConfiguration);

            actual.RequestState.ReturnUrl.Should().Be("/Return.aspx");
        }
Esempio n. 2
0
        public async Task <ActionResult <CommandResult> > SignIn([FromBody] SignInCommand command)
        {
            var resp = await _userHandler.Handler(command);

            if (resp.Success)
            {
                return(StatusCode(200, resp));
            }

            return(resp.Content == null?StatusCode(404, resp) : BadRequest(resp));
        }
Esempio n. 3
0
        public void SignInCommand_Run_RedirectToDsWorksWithoutSpecifiedReturnPath()
        {
            var options = StubFactory.CreateOptions();

            var request = new HttpRequestData("GET",
                                              new Uri("http://sp.example.com/Saml2/SignIn"));

            Action a = () => SignInCommand.Run(null, null, request, options, null);

            a.ShouldNotThrow();
        }
        public async Task <IActionResult> SignIn(SignInCommand signIn)
        {
            SignInResponse response = await _mediator.Send(signIn);

            if (response.Token != null)
            {
                return(Ok(new { userId = response.UserId, token = response.Token }));
            }

            return(BadRequest(new { isLockedOut = response.IsLockedOut }));
        }
Esempio n. 5
0
        public async Task <IActionResult> SignInAsync([FromBody] SignInCommand command)
        {
            var authenticateDto = await _mediator.Send(command);

            if (authenticateDto == null)
            {
                return(BadRequest(new { error = "Email/Password incorrect." }));
            }

            return(Ok(authenticateDto));
        }
Esempio n. 6
0
        public async Task ShouldSignInIfLoginPasswordOk()
        {
            var authentication        = new Authentication("username", "passwordpassword", "token");
            var authenticationGateway = new InMemoryAuthenticationGateway(authentication);
            var command   = new SignInCommand("username", "password");
            var presenter = new SignInTestPresenter();
            var handler   = new SignInCommandHandler(authenticationGateway, presenter, new FakeHashPassword());

            await handler.Handle(command);

            Assert.Equal("token", presenter.GetToken());
        }
Esempio n. 7
0
        public void SignInCommand_Run_PublicOrigin()
        {
            var options = StubFactory.CreateOptionsPublicOrigin(new Uri("https://my.public.origin:8443"));
            var idp     = options.IdentityProviders.Default;

            var request = new HttpRequestData("GET",
                                              new Uri("http://sp.example.com?idp=" + Uri.EscapeDataString(idp.EntityId.Id)));

            var subject = new SignInCommand().Run(request, Options.FromConfiguration);

            subject.Location.Host.Should().Be(new Uri("https://idp.example.com").Host);
        }
Esempio n. 8
0
        public async Task <ActionResult> SignIn()
        {
            var signInCommand = new SignInCommand
            {
                UserId           = User.FindFirst(ClaimTypes.NameIdentifier)?.Value,
                AccessToken      = Request.Headers["Authorization"],
                UserInfoEndpoint = User.FindAll("aud").Last()?.Value
            };
            await Mediator.Send(signInCommand);

            return(NoContent());
        }
Esempio n. 9
0
        public void SignInCommand_Run_With_Idp2_ReturnsAuthnRequestForSecondIdp()
        {
            var secondIdp         = IdentityProvider.ActiveIdentityProviders.Skip(1).First();
            var secondDestination = secondIdp.AssertionConsumerServiceUrl;
            var secondEntityId    = secondIdp.EntityId;

            var request = new HttpRequestData("GET", new Uri("http://sp.example.com?idp=" +
                                                             HttpUtility.UrlEncode(secondEntityId.Id)));
            var subject = new SignInCommand().Run(request);

            subject.Location.Host.Should().Be(secondDestination.Host);
        }
        public SignInWithEmailAndPasswordPageViewModel(INavigationService navigationService, IPageDialogService pageDialogService) : base(navigationService)
        {
            _pageDialogService = pageDialogService;

            Title = "Sign In ";

            SignInCommand = new[] {
                Email.Select(s => string.IsNullOrEmpty(s)),
                Password.Select(s => string.IsNullOrEmpty(s))
            }.CombineLatest(x => x.All(y => !y))
            .ToAsyncReactiveCommand();

            SignInCommand.Subscribe(async() =>
            {
                try
                {
                    var result = await CrossFirebaseAuth.Current
                                 .Instance
                                 .SignInWithEmailAndPasswordAsync(Email.Value, Password.Value);

                    await NavigationService.GoBackAsync(result.User);
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e);

                    await _pageDialogService.DisplayAlertAsync("Failure", e.Message, "OK");
                }
            });

            ResetPasswordCommand = new[] {
                Email.Select(s => string.IsNullOrEmpty(s)),
            }.CombineLatest(x => x.All(y => !y))
            .ToAsyncReactiveCommand();

            ResetPasswordCommand.Subscribe(async() =>
            {
                try
                {
                    await CrossFirebaseAuth.Current
                    .Instance
                    .SendPasswordResetEmailAsync(Email.Value);

                    await _pageDialogService.DisplayAlertAsync(null, "Email has been sent.", "OK");
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e);

                    await _pageDialogService.DisplayAlertAsync("Failure", e.Message, "OK");
                }
            });
        }
Esempio n. 11
0
        public void SignInCommand_Run_With_Idp2_ReturnsAuthnRequestForSecondIdp()
        {
            var secondIdp = IdentityProvider.ActiveIdentityProviders.Skip(1).First();
            var secondDestination = secondIdp.AssertionConsumerServiceUrl;
            var secondEntityId = secondIdp.EntityId;

            var request = new HttpRequestData("GET", new Uri("http://sp.example.com?idp=" +
            HttpUtility.UrlEncode(secondEntityId.Id)));
            var subject = new SignInCommand().Run(request);

            subject.Location.Host.Should().Be(secondDestination.Host);
        }
Esempio n. 12
0
        public void OneSetUp()
        {
            viewProjectsCommand           = new ViewProjectsCommand();
            addEmployeeCommand            = new AddEmployeeCommand();
            changePasswordCommand         = new ChangePasswordCommand();
            editPersonalDataCommand       = new EditPersonalDataCommand();
            sendRequestCompanyViewCommand = new SendRequestCompanyViewCommand();
            viewWorkersCommand            = new ViewWorkersCommand();
            workingHoursCommand           = new WorkingHoursCommand();
            logOutCommand                  = new LogOutCommand();
            signInCommand                  = new SignInCommand();
            defineUserStoriesCommand       = new DefineUserStoriesCommand();
            createProjectCommand           = new CreateProjectCommand();
            showCompaniesCommand           = new ShowCompaniesCommand();
            sendRequestProjectViewCommand  = new SendRequestProjectViewCommand();
            markProjectFinishedCommand     = new MarkProjectFinishedCommand();
            loadedCommand                  = new LoadedCommand();
            editPositionCommand            = new EditPositionCommand();
            clientDialogViewModelUnderTest = new ClientDialogViewModel();

            clientDialogViewModelUnderTest.AddEmployeeCommand       = addEmployeeCommand;
            clientDialogViewModelUnderTest.ChangePasswordCommand    = changePasswordCommand;
            clientDialogViewModelUnderTest.CreateProjectCommand     = createProjectCommand;
            clientDialogViewModelUnderTest.DefineUserStoriesCommand = defineUserStoriesCommand;
            clientDialogViewModelUnderTest.EditPersonalDataCommand  = editPersonalDataCommand;
            clientDialogViewModelUnderTest.EditPositionCommand      = editPositionCommand;
            clientDialogViewModelUnderTest.ErrorMessage             = "";
            clientDialogViewModelUnderTest.LoadedCommand            = loadedCommand;
            clientDialogViewModelUnderTest.LogInUser     = new LogInUser();
            clientDialogViewModelUnderTest.LogOutCommand = logOutCommand;
            clientDialogViewModelUnderTest.MarkProjectFinishedCommand    = markProjectFinishedCommand;
            clientDialogViewModelUnderTest.SendRequestCompanyViewCommand = sendRequestCompanyViewCommand;
            clientDialogViewModelUnderTest.SendRequestProjectViewCommand = sendRequestProjectViewCommand;
            clientDialogViewModelUnderTest.ShowCompaniesCommand          = showCompaniesCommand;
            clientDialogViewModelUnderTest.SignInCommand       = signInCommand;
            clientDialogViewModelUnderTest.ViewProjectsCommand = viewProjectsCommand;
            clientDialogViewModelUnderTest.ViewWorkersCommand  = viewWorkersCommand;
            clientDialogViewModelUnderTest.Resources           = new ObservableCollection <Employee>();
            clientDialogViewModelUnderTest.PrResources         = new ObservableCollection <Project>();
            clientDialogViewModelUnderTest.EmpResource         = new ObservableCollection <Employee>();
            clientDialogViewModelUnderTest.OcResources         = new ObservableCollection <OutsourcingCompany>();
            clientDialogViewModelUnderTest.UsResources         = new ObservableCollection <UserStory>();


            LogInUser nov = clientDialogViewModelUnderTest.LogInUser;
            string    str = clientDialogViewModelUnderTest.ErrorMessage;
            ObservableCollection <Employee>           res1 = clientDialogViewModelUnderTest.Resources;
            ObservableCollection <Project>            res2 = clientDialogViewModelUnderTest.PrResources;
            ObservableCollection <Employee>           res3 = clientDialogViewModelUnderTest.EmpResource;
            ObservableCollection <OutsourcingCompany> res4 = clientDialogViewModelUnderTest.OcResources;
            ObservableCollection <UserStory>          res5 = clientDialogViewModelUnderTest.UsResources;
        }
        public void Should_not_have_error(string username, string password)
        {
            var command = new SignInCommand()
            {
                Password   = password,
                RememberMe = false,
                UserName   = username
            };
            var validator = CreateValidator();

            validator.ShouldNotHaveValidationErrorFor(x => x.UserName, command);
            validator.ShouldNotHaveValidationErrorFor(x => x.Password, command);
        }
Esempio n. 14
0
        public void SignInCommand_Run_With_Idp2_ReturnsAuthnRequestForSecondIdp()
        {
            var secondIdp         = Options.FromConfiguration.IdentityProviders[1];
            var secondDestination = secondIdp.SingleSignOnServiceUrl;
            var secondEntityId    = secondIdp.EntityId;

            var request = new HttpRequestData("GET",
                                              new Uri("http://sp.example.com?idp=" + Uri.EscapeDataString(secondEntityId.Id)));

            var subject = new SignInCommand().Run(request, Options.FromConfiguration);

            subject.Location.Host.Should().Be(secondDestination.Host);
        }
Esempio n. 15
0
        public void SignInCommand_Run_With_Idp2_ReturnsAuthnRequestForSecondIdp()
        {
            var secondIdp         = IdentityProvider.ConfiguredIdentityProviders.Skip(1).First().Value;
            var secondDestination = secondIdp.DestinationUri;
            var secondIssuer      = secondIdp.Issuer;

            var requestSubstitute = Substitute.For <HttpRequestBase>();

            requestSubstitute["idp"].Returns(HttpUtility.UrlEncode(secondIssuer));
            var subject = new SignInCommand().Run(requestSubstitute);

            subject.Location.Host.Should().Be(secondDestination.Host);
        }
Esempio n. 16
0
        public async Task <SignInResult> SignIn([FromBody] SignInCommand command)
        {
            var user = await _mediator.Send(command, HttpContext.RequestAborted);

            var properties = new AuthenticationProperties()
            {
                AllowRefresh = true,
                IsPersistent = command.RememberMe,
                IssuedUtc    = DateTimeOffset.UtcNow
            };

            return(SignIn(user.ToPrincipal(), properties, IdentityServerConstants.DefaultCookieAuthenticationScheme));
        }
Esempio n. 17
0
        public static async Task AuthToOwner(this HttpClient client)
        {
            var userObj = new SignInCommand
            {
                Logon    = "*****@*****.**",
                Password = "******"
            };
            var user = JsonConvert.SerializeObject(userObj);

            var response = await client.PostAsync("api/Account/SignIn",
                                                  new StringContent(user, Encoding.UTF8, "application/json"));

            client.DefaultRequestHeaders.Add("Cookie", response.Headers.GetValues("Set-Cookie").ToArray()[0]);
        }
Esempio n. 18
0
        public MainWindowVm()
        {
            SignInCommand              = new SignInCommand();
            SignOutCommand             = new SignOutCommand();
            AddAnimalCommand           = new AddAnimalCommand();
            EditAnimalCommand          = new EditAnimalCommand();
            DeleteAnimalCommand        = new DeleteAnimalCommand();
            CallVaccineCommand         = new CallVaccineCommand();
            CallTreatmentCommand       = new CallTreatmentCommand();
            CompleteCallCommand        = new CompleteCallCommand();
            ShowVaccinationCardCommand = new ShowVaccinationCardCommand();
            SignInCommand.Execute(this);

            Update();
        }
Esempio n. 19
0
        public async Task ShouldNotGetTokenIfAuthenticationFailed()
        {
            var authentication        = new Authentication("user", "pass", "token");
            var authenticationGateway = new InMemoryAuthenticationGateway(authentication);
            var command   = new SignInCommand("username", "password");
            var presenter = new SignInTestPresenter();
            var handler   = new SignInCommandHandler(authenticationGateway, presenter, new FakeHashPassword());

            await handler.Handle(command);

            Assert.Collection(presenter.GetErrors(), x =>
            {
                Assert.Equal("Identification failed", x);
            });
        }
Esempio n. 20
0
        private void CheckSettingsButton_Click(object sender, System.EventArgs e)
        {
            var signinCommand = new SignInCommand()
            {
                Login    = Settings.UserName,
                Password = Settings.UserPassword
            };

            var bytes = signinCommand.JsonSerializeToBytes();

            var command1 = bytes.JsonDeserialize <SignInCommand>();



            // try    sendCommandToServer (signin)
        }
Esempio n. 21
0
        public async Task <ServiceResponse <AuthenticationResult> > Handle(SignInCommand request, CancellationToken cancellationToken)
        {
            var user = await _userRepository.GetByEmailAsync(request.Email);

            if (user == null || !VerifyHPassword(user, request.Password))
            {
                return(ServiceResponse <AuthenticationResult> .Error());
            }

            var token = _jwtGenerator.GetToken(user);

            return(ServiceResponse <AuthenticationResult> .Success(new AuthenticationResult
            {
                AccessToken = token
            }));
        }
Esempio n. 22
0
 public IActionResult SignIn([FromBody] SignInCommand signInCommand)
 {
     try
     {
         var userToken = _signInService.SignIn(signInCommand);
         return(Ok(userToken));
     }
     catch (UnauthorizedAccessException)
     {
         return(StatusCode(401));
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Esempio n. 23
0
        public async Task <ActionResult> SignIn(SignInCommand signIn)
        {
            try
            {
                await _mediator.Send(signIn);

                return(Json(new
                {
                    redirectToUrl = @Url.Action("Index", "ContentConsumption")
                }));
            }
            catch (Exception exception)
            {
                return(BadRequest(new { message = exception.Message }));
            }
        }
Esempio n. 24
0
        public async Task SignInUser_WhenGivenCredentialsAreNotValid_ReturnFailure()
        {
            using (var sut = new SystemUnderTest(UsersFactory.CreateUser("*****@*****.**")))
            {
                await sut.CreateAsync(
                    new User(Guid.NewGuid(), "*****@*****.**", false, new [] { Role.AddExam }, "zaq1@WSX", "pass-salt", DateTime.Now)
                    );

                var command = new SignInCommand("*****@*****.**", "bad-password");

                var url    = $"{Url}/sign-in";
                var result = sut.HttpPost(url, command);

                result.IsSuccess.Should().BeFalse();
                result.Message.Should().BeEquivalentTo("Given email or password are not valid.");
            }
        }
Esempio n. 25
0
        public IActionResult SignIn([FromBody] SignInInput input)
        {
            SignInResponse     response;
            SignInResponseData responseData;

            var command = new SignInCommand(input.UserName, input.Password);
            var result  = RabbitMq.Publish <SignInCommand, Result <SignInResult> >(command);

            if (!result.IsSucceeded)
            {
                return(BadRequest(new ApiResponse(result.Error.Code, result.Error.Description)));
            }

            responseData = new SignInResponseData(result.Data.AccessToken, result.Data.RefreshToken);
            response     = new SignInResponse("OK", "Success", responseData);
            return(Ok(response));
        }
Esempio n. 26
0
        public async Task SignInUser_WhenGivenCredentialsAreNotValid_ReturnFailure()
        {
            using (var sut = new SystemUnderTest())
            {
                await sut.UsersRepository.AddAsync(
                    new User(Guid.NewGuid(), "*****@*****.**", false, Enumerable.Empty <Role>(), "zaq1@WSX", "pass-salt", DateTime.Now)
                    );

                var command = new SignInCommand("*****@*****.**", "bad-password");
                var handler = new SignInCommandHandler(sut.UsersRepository, sut.PasswordService, sut.TokenService);

                var result = await handler.HandleAsync(command);

                result.IsSuccess.Should().BeFalse();
                result.Message.Should().BeEquivalentTo("Given email or password are not valid.");
            }
        }
        public void SignInCommand_Run_MapsReturnUrl()
        {
            var defaultDestination = Options.FromConfiguration.IdentityProviders.Default.SingleSignOnServiceUrl;

            var httpRequest = new HttpRequestData("GET", new Uri("http://localhost/signin?ReturnUrl=%2FReturn.aspx"));

            var subject = new SignInCommand().Run(httpRequest, Options.FromConfiguration);

            var idp        = Options.FromConfiguration.IdentityProviders.Default;
            var relayState = HttpUtility.ParseQueryString(subject.Location.Query)["RelayState"];

            StoredRequestState storedAuthnData;

            PendingAuthnRequests.TryRemove(relayState, out storedAuthnData);

            storedAuthnData.ReturnUrl.Should().Be("http://localhost/Return.aspx");
        }
Esempio n. 28
0
        protected override async Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode == 401)
            {
                var challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

                if (challenge != null)
                {
                    EntityId idp;
                    string   strIdp;
                    if (challenge.Properties.Dictionary.TryGetValue("idp", out strIdp))
                    {
                        idp = new EntityId(strIdp);
                    }
                    else
                    {
                        object objIdp = null;
                        Context.Environment.TryGetValue("saml2.idp", out objIdp);
                        idp = objIdp as EntityId;
                    }
                    var redirectUri = challenge.Properties.RedirectUri;
                    // Don't serialize the RedirectUri twice.
                    challenge.Properties.RedirectUri = null;

                    if (redirectUri == null)
                    {
                        redirectUri = Context.Request.Uri.ToString();
                    }

                    var result = SignInCommand.Run(
                        idp,
                        redirectUri,
                        await Context.ToHttpRequestData(Options.DataProtector.Unprotect),
                        Options,
                        challenge.Properties.Dictionary);

                    if (!result.HandledResult)
                    {
                        result.Apply(
                            Context,
                            Options.DataProtector,
                            Options.Notifications.EmitSameSiteNone(Request.GetUserAgent()));
                    }
                }
            }
        }
Esempio n. 29
0
        public void SignInCommand_Run_Calls_Notifications()
        {
            var options   = StubFactory.CreateOptions();
            var idp       = options.IdentityProviders.Default;
            var relayData = new Dictionary <string, string>();

            options.SPOptions.DiscoveryServiceUrl = null;

            var request = new HttpRequestData("GET",
                                              new Uri("http://sp.example.com"));

            var selectedIdpCalled = false;

            options.Notifications.SelectIdentityProvider =
                (ei, r) =>
            {
                ei.Should().BeSameAs(idp.EntityId);
                r.Should().BeSameAs(relayData);
                selectedIdpCalled = true;
                return(null);
            };

            var authnRequestCreatedCalled = false;

            options.Notifications.AuthenticationRequestCreated = (a, i, r) =>
            {
                a.Should().NotBeNull();
                i.Should().BeSameAs(idp);
                r.Should().BeSameAs(relayData);
                authnRequestCreatedCalled = true;
            };

            CommandResult notifiedCommandResult = null;

            options.Notifications.SignInCommandResultCreated = (cr, r) =>
            {
                notifiedCommandResult = cr;
                r.Should().BeSameAs(relayData);
            };

            SignInCommand.Run(idp.EntityId, null, request, options, relayData)
            .Should().BeSameAs(notifiedCommandResult);

            authnRequestCreatedCalled.Should().BeTrue("the AuthenticationRequestCreated notification should have been called");
            selectedIdpCalled.Should().BeTrue("the SelectIdentityProvider notification should have been called.");
        }
Esempio n. 30
0
        public void SignIn_WrongData_Fail(string _email, string _password)
        {
            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            var signInCommand = new SignInCommand
            {
                email    = _email,
                password = _password
            };

            var handler = new SignInCommandHandler();
            var result  = (SignInInfoDto)handler.Handle(signInCommand);

            DatabaseQueryProcessor.Erase();
            Assert.IsFalse(result.isSuccess);
        }
        public async Task <IActionResult> LoginAsync(LoginViewModel login, CancellationToken cancellationToken)
        {
            if (!ModelState.IsValid)
            {
                return(View("Index", login));
            }

            var command = new SignInCommand(login.Username, login.Password, login.RememberMe);
            var success = await _mediator.Send(command, cancellationToken);

            if (!success)
            {
                ModelState.AddModelError("password", "Your username or password is incorrect");
                return(View("Index", login));
            }

            return(RedirectToActionPermanent("Index", "Home"));
        }
Esempio n. 32
0
        public void SignInCommand_Run_MapsReturnUrl()
        {
            var defaultDestination = IdentityProvider.ActiveIdentityProviders.First()
                .AssertionConsumerServiceUrl;

            var httpRequest = new HttpRequestData("GET", new Uri("http://localhost/signin?ReturnUrl=/Return.aspx"));

            var subject = new SignInCommand().Run(httpRequest);

            var idp = IdentityProvider.ActiveIdentityProviders.First();

            var authnRequest = idp.CreateAuthenticateRequest(null);

            var requestId = AuthnRequestHelper.GetRequestId(subject.Location);

            StoredRequestState storedAuthnData;
            PendingAuthnRequests.TryRemove(new System.IdentityModel.Tokens.Saml2Id(requestId), out storedAuthnData);

            storedAuthnData.ReturnUri.Should().Be("http://localhost/Return.aspx");
        }
Esempio n. 33
0
        public void SignInCommand_Run_ReturnsAuthnRequestForDefaultIdp()
        {
            var defaultDestination = IdentityProvider.ActiveIdentityProviders.First()
                .AssertionConsumerServiceUrl;

            var subject = new SignInCommand().Run(new HttpRequestData("GET", new Uri("http://example.com")));

            var expected = new CommandResult()
            {
                HttpStatusCode = HttpStatusCode.SeeOther,
                Cacheability = HttpCacheability.NoCache,
                Location = new Uri(defaultDestination + "?SAMLRequest=XYZ")
            };

            subject.ShouldBeEquivalentTo(expected, options => options.Excluding(cr => cr.Location));
            subject.Location.Host.Should().Be(defaultDestination.Host);

            var queries = HttpUtility.ParseQueryString(subject.Location.Query);

            queries.Should().HaveCount(1);
            queries.Keys[0].Should().Be("SAMLRequest");
            queries[0].Should().NotBeEmpty();
        }
Esempio n. 34
0
        public void SignInCommand_Run_ReturnsAuthnRequestForDefaultIdp()
        {
            var defaultDestination = IdentityProvider.ConfiguredIdentityProviders.First()
                .Value.DestinationUri;

            var subject = new SignInCommand().Run(Substitute.For<HttpRequestBase>());

            var expected = new CommandResult()
            {
                HttpStatusCode = HttpStatusCode.SeeOther,
                Cacheability = HttpCacheability.NoCache,
                Location = new Uri(defaultDestination + "?SAMLRequest=XYZ")
            };

            subject.ShouldBeEquivalentTo(expected, options => options.Excluding(cr => cr.Location));
            subject.Location.Host.Should().Be(defaultDestination.Host);

            var queries = HttpUtility.ParseQueryString(subject.Location.Query);

            queries.Should().HaveCount(1);
            queries.Keys[0].Should().Be("SAMLRequest");
            queries[0].Should().NotBeEmpty();
        }
Esempio n. 35
0
        public void SignInCommand_Run_MapsReturnUrl()
        {
            var defaultDestination = IdentityProvider.ConfiguredIdentityProviders.First()
                .Value.DestinationUri;

            var httpRequest = Substitute.For<HttpRequestBase>();
            httpRequest["ReturnUrl"].Returns("/Return.aspx");
            httpRequest.Url.Returns(new Uri("http://localhost/signin"));
            var subject = new SignInCommand().Run(httpRequest);

            var idp = IdentityProvider.ConfiguredIdentityProviders.First().Value;

            var authnRequest = idp.CreateAuthenticateRequest(null);

            // Dig out requestId from the signincommand
            string requestId;
            var tmp = Convert.FromBase64String(HttpUtility.UrlDecode(subject.Location.Query.Replace("?SAMLRequest=", "")));
            using (var compressed = new MemoryStream(tmp))
            {
                compressed.Seek(0, SeekOrigin.Begin);
                using (var decompressedStream = new DeflateStream(compressed, CompressionMode.Decompress))
                {
                    using (var deCompressed = new MemoryStream())
                    {
                        decompressedStream.CopyTo(deCompressed);
                        var xmlData = System.Text.Encoding.UTF8.GetString(deCompressed.GetBuffer());
                        var requestXml = XDocument.Parse(xmlData);
                        requestId = requestXml.Document.Root.Attribute(XName.Get("ID")).Value;
                    }
                }
            }

            StoredRequestState storedAuthnData;
            PendingAuthnRequests.TryRemove(new System.IdentityModel.Tokens.Saml2Id(requestId), out storedAuthnData);

            storedAuthnData.ReturnUri.Should().Be("http://localhost/Return.aspx");
        }
Esempio n. 36
0
        public void SignInCommand_Run_With_Idp2_ReturnsAuthnRequestForSecondIdp()
        {
            var secondIdp = IdentityProvider.ConfiguredIdentityProviders.Skip(1).First().Value;
            var secondDestination = secondIdp.DestinationUri;
            var secondIssuer = secondIdp.Issuer;

            var requestSubstitute = Substitute.For<HttpRequestBase>();
            requestSubstitute["idp"].Returns(HttpUtility.UrlEncode(secondIssuer));
            var subject = new SignInCommand().Run(requestSubstitute);

            subject.Location.Host.Should().Be(secondDestination.Host);
        }