Пример #1
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");

                    // Castle Authenticate $login.succeeded
                    _castleClient.Authenticate(CreateCastleActionRequest(Castle.Events.LoginSucceeded)).Forget();

                    return(LocalRedirect(returnUrl));
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToPage("./Lockout"));
                }
                else
                {
                    // Castle Track $login.failed
                    _castleClient.Track(CreateCastleActionRequest(Castle.Events.LoginFailed)).Forget();

                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(Page());
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Пример #2
0
        public void Should_not_throw_exception_if_calling_authenticate_with_null_request(CastleClient sut)
        {
            Func <Task> act = async() => await sut.Authenticate(null);

            act.Should().NotThrow();
        }
Пример #3
0
        public void Should_authenticate(ActionRequest request, CastleClient sut)
        {
            Func <Task> act = async() => await sut.Authenticate(request);

            act.Should().NotThrow();
        }
Пример #4
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    var user = await _userManager.FindByEmailAsync(Input.Email);

                    var verdict = await _castle.Authenticate(new ActionRequest()
                    {
                        Event      = Events.LoginSucceeded,
                        UserId     = user?.Id,
                        UserTraits = new Dictionary <string, string>()
                        {
                            ["email"]    = user?.NormalizedEmail,
                            ["username"] = user?.NormalizedUserName,
                        },
                        Context = new RequestContext()
                        {
                            Ip       = Request.HttpContext.Connection.RemoteIpAddress.ToString(),
                            ClientId = Request.Cookies["__cid"],
                            Headers  = Request.Headers.ToDictionary(x => x.Key, y => y.Value.FirstOrDefault()),
                        },
                    });

                    switch (verdict.Action)
                    {
                    case ActionType.Allow:
                        _logger.LogInformation("User with id `{0}` succesfully logged in.", user?.Id);
                        break;

                    case ActionType.Challenge:
                        _logger.LogInformation("User with id `{0}` succesfully logged in, but the verdict is that the account must be challeged", user.Id);
                        return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }));

                    case ActionType.Deny:
                        _logger.LogInformation("User with id `{0}` succesfully logged in, but should be denied access. Their account may be suspect.", user.Id);
                        ModelState.AddModelError(string.Empty, "Invalid login attempt (002).");
                        return(Page());
                    }

                    // Check verdict
                    return(LocalRedirect(returnUrl));
                }


                if (result.RequiresTwoFactor)
                {
                    return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }));
                }

                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToPage("./Lockout"));
                }
                else
                {
                    var user = await _userManager.FindByEmailAsync(Input.Email);

                    _logger.LogInformation("User with id {0} failed to log in.", user?.Id);
                    await _castle.Track(new ActionRequest()
                    {
                        Event      = Events.LoginFailed,
                        UserId     = user?.Id,
                        UserTraits = new Dictionary <string, string>()
                        {
                            ["email"]    = user?.NormalizedEmail,
                            ["username"] = user?.NormalizedUserName,
                        },
                        Context = new RequestContext()
                        {
                            Ip       = Request.HttpContext.Connection.RemoteIpAddress.ToString(),
                            ClientId = Request.Cookies["__cid"],
                            Headers  = Request.Headers.ToDictionary(x => x.Key, y => y.Value.FirstOrDefault()),
                        },
                    });

                    ModelState.AddModelError(string.Empty, "Invalid login attempt (001).");
                    return(Page());
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Пример #5
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new IdentityUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    // We have a registration account here; let's create it.
                    await _castle.Authenticate(new ActionRequest()
                    {
                        Event      = Events.LoginSucceeded,
                        UserId     = user?.Id,
                        UserTraits = new Dictionary <string, string>()
                        {
                            ["email"]         = user?.NormalizedEmail,
                            ["username"]      = user?.NormalizedUserName,
                            ["registered_at"] = DateTime.UtcNow.ToString("o")
                        },
                        Context = new RequestContext()
                        {
                            Ip       = Request.HttpContext.Connection.RemoteIpAddress.ToString(),
                            ClientId = Request.Cookies["__cid"],
                            Headers  = Request.Headers.ToDictionary(x => x.Key, y => y.Value.FirstOrDefault()),
                        },
                    });

                    _logger.LogInformation("User created a new account with password.");
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }