コード例 #1
0
ファイル: AccountController.cs プロジェクト: cmpickle/catinc
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            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(model.Email, model.Password, model.RememberMe, lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return(RedirectToLocal(returnUrl));
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToAction(nameof(Lockout)));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(View(model));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #2
0
ファイル: UserService.cs プロジェクト: popraducj/Galaxy.Auth
        public async Task <ActionResponse> ChangePasswordAsync(string username, string newPassword, string oldPassword)
        {
            var user = await _userManager.FindByNameAsync(username);

            if (user == null || !user.EmailConfirmed)
            {
                return(ActionResponse.UnauthorizedAccess());
            }
            var signIn = await _signInManager.PasswordSignInAsync(username, oldPassword, false, false);

            if (!signIn.Succeeded)
            {
                return(ActionResponse.UnauthorizedAccess());
            }

            var resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);

            var result = await _userManager.ResetPasswordAsync(user, resetToken, newPassword);

            if (result.Succeeded)
            {
                return(new ActionResponse());
            }
            _logger.LogCritical(
                $"Change password failed for user: {username}. Errors: {JsonConvert.SerializeObject(result.Errors)}");
            return(ToActionResponse(result.Errors));
        }
コード例 #3
0
        //[ValidateAntiForgeryToken]
        public async Task <string> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return("");
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout : true);

            var formater = new JsonResult();
            var data     = _iUserRepository.GetUserByEmail(model.UserName);
            var creditApplicationJson = JsonConvert.SerializeObject(data);

            switch (result)
            {
            case SignInStatus.Success:
                return(creditApplicationJson);

            case SignInStatus.LockedOut:
                return(null);

            case SignInStatus.RequiresVerification:
                return(null);

            case SignInStatus.Failure:
                ModelState.AddModelError("", Resources.InvalidCredentials);
                return(null);

            default:
                throw new InvalidEnumArgumentException("result", (int)result, typeof(SignInStatus));
            }
        }
コード例 #4
0
        public async Task <IHttpActionResult> Login(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout : true);

            var data = _userRepository.GetUserByEmail(model.UserName);

            switch (result)
            {
            case SignInStatus.Success:
                return(Ok(data));

            case SignInStatus.LockedOut:
                return(BadRequest());

            case SignInStatus.RequiresVerification:
                return(BadRequest());

            case SignInStatus.Failure:
                return(BadRequest(Resources.InvalidCredentials));

            default:
                throw new InvalidEnumArgumentException("result", (int)result, typeof(SignInStatus));
            }
        }
コード例 #5
0
        //[ValidateAntiForgeryToken]
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout : true);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(View("AccountNotConfirmed", model));

            case SignInStatus.Failure:
                ModelState.AddModelError("", Resources.InvalidCredentials);
                return(View(model));

            default:
                throw new InvalidEnumArgumentException("result", (int)result, typeof(SignInStatus));
            }
        }
コード例 #6
0
ファイル: AccountController.cs プロジェクト: namofun/ccs
        public async Task <IActionResult> Login(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // 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(model.Username, model.Password, isPersistent : false, lockoutOnFailure : false);

            if (result.Succeeded)
            {
                return(Redirect("/"));
            }
            else if (result.RequiresTwoFactor)
            {
                return(RedirectToAction(nameof(LoginWith2fa)));
            }
            else if (result.IsLockedOut)
            {
                return(RedirectToAction(nameof(Lockout)));
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return(View(model));
            }
        }
コード例 #7
0
        public IEnumerable Handle(PasswordSignInCommand c)
        {
            _signInManager.PasswordSignInAsync(c.Email, c.Password, c.RememberMe, lockoutOnFailure: false).ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    c.Message = t.Exception?.Message;
                }
                else if (t.IsCanceled)
                {
                    c.Message = $"{c.GetType().Name}:Operation was cancelled";
                }
                else
                {
                    c.Succeeded         = t.Result.Succeeded;
                    c.RequiresTwoFactor = t.Result.RequiresTwoFactor;
                    c.IsLockedOut       = t.Result.IsLockedOut;
                    c.IsNotAllowed      = t.Result.IsNotAllowed;
                }
            });

            c.HasError = !string.IsNullOrEmpty(c.Message);

            yield return(c);
        }
コード例 #8
0
        public async Task <TokenResult> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            LoginEventNotification loginEvent;
            var signInResult = await _signInManager.PasswordSignInAsync(request.Email, request.Password, false, true);

            if (!signInResult.Succeeded)
            {
                loginEvent = new LoginEventNotification
                {
                    Username    = request.Email,
                    Description = signInResult.Errors[0],
                    IsSuccess   = false,
                    IpAddress   = _currentUserService.IpAddress,
                    Timestamp   = DateTime.UtcNow
                };

                await _mediator.Publish(loginEvent, cancellationToken);

                throw new UnauthorizedException(signInResult.Errors[0]);
            }

            loginEvent = new LoginEventNotification
            {
                Username    = request.Email,
                Description = "Login was successful",
                IsSuccess   = true,
                IpAddress   = _currentUserService.IpAddress,
                Timestamp   = DateTime.UtcNow
            };

            await _mediator.Publish(loginEvent, cancellationToken);

            return(await _securityTokenManager.GenerateClaimsTokenAsync(request.Email, cancellationToken));
        }
コード例 #9
0
ファイル: AuthTokenManager.cs プロジェクト: lulzzz/UserAdmin
        /// <summary>
        /// Validate the core properties of the request.
        /// </summary>
        /// <param name="authRequest"></param>
        /// <returns></returns>
        public async Task <InvokeResult <AuthResponse> > AccessTokenGrantAsync(AuthRequest authRequest)
        {
            var requestValidationResult = _authRequestValidators.ValidateAuthRequest(authRequest);

            if (!requestValidationResult.Successful)
            {
                return(InvokeResult <AuthResponse> .FromInvokeResult(requestValidationResult));
            }

            var accessTokenRequestValidationResult = _authRequestValidators.ValidateAccessTokenGrant(authRequest);

            if (!accessTokenRequestValidationResult.Successful)
            {
                return(InvokeResult <AuthResponse> .FromInvokeResult(accessTokenRequestValidationResult));
            }

            var signInRequest = await _signInManager.PasswordSignInAsync(authRequest.UserName, authRequest.Password, true, false);

            if (!signInRequest.Successful)
            {
                return(InvokeResult <AuthResponse> .FromInvokeResult(signInRequest));
            }

            _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Message, "AuthTokenManager_AccessTokenGrantAsync", "UserLoggedIn", new KeyValuePair <string, string>("email", authRequest.UserName));

            var appUser = await _userManager.FindByNameAsync(authRequest.UserName);

            if (appUser == null)
            {
                /* Should really never, ever happen, but well...let's track it */
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "AuthTokenManager_AccessTokenGrantAsync", UserAdminErrorCodes.AuthCouldNotFindUserAccount.Message, new KeyValuePair <string, string>("email", authRequest.UserName));
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.AuthCouldNotFindUserAccount.ToErrorMessage()));
            }

            if (String.IsNullOrEmpty(authRequest.AppInstanceId))
            {
                /* This generally happens for the first time the app is logged in on a new device, if it is logged in again future times it will resend the app id */
                var appInstanceResult = await _appInstanceManager.CreateForUserAsync(appUser.Id, authRequest);

                authRequest.AppInstanceId = appInstanceResult.Result.RowKey;
            }
            else
            {
                var updateLastLoginResult = (await _appInstanceManager.UpdateLastLoginAsync(appUser.Id, authRequest));
                if (updateLastLoginResult.Successful)
                {
                    authRequest.AppInstanceId = updateLastLoginResult.Result.RowKey;
                }
                else
                {
                    return(InvokeResult <AuthResponse> .FromInvokeResult(updateLastLoginResult.ToInvokeResult()));
                }
            }

            var refreshTokenResponse = await _refreshTokenManager.GenerateRefreshTokenAsync(authRequest.AppId, authRequest.AppInstanceId, appUser.Id);

            return(_tokenHelper.GenerateAuthResponse(appUser, authRequest, refreshTokenResponse));
        }
コード例 #10
0
        public async Task LogIn_Valid_Ok()
        {
            signInManager.PasswordSignInAsync("", "", false, false).ReturnsForAnyArgs(SignInResult.Success);
            var request = new LoginRequest();

            var result = await testObj.LogIn(request);

            ControllerUtility.AssertStatusCode(result, HttpStatusCode.OK);
        }
コード例 #11
0
        public void LogIn_WrongPassword_BadRequestException()
        {
            signInManager.PasswordSignInAsync("", "", false, false).ReturnsForAnyArgs(SignInResult.Failed);
            const string email = "*****@*****.**";

            DbContextUtility.AddNew <ApplicationUser>(dbContext, u => u.Email = email);
            var request = new LoginRequest {
                Email = email
            };

            Assert.ThrowsAsync <BadRequestException>(() => testObj.LogIn(request));
        }
コード例 #12
0
        public async Task <string> LogIn(LoginRequest request)
        {
            var user = await dbContext.Users.FirstOrDefaultAsync(u => u.Email == request.Email);

            var result = await signInManager.PasswordSignInAsync(user?.UserName, request.Password, request.RememberMe, false);

            if (result.Succeeded)
            {
                var token = tokenHelper.CreateUserToken(configuration.GetSecurityKey(), DateTime.Now.AddMinutes(30), request.Email);
                return(token);
            }

            throw new BadRequestException();
        }
コード例 #13
0
        public async Task <IActionResult> Login(LoginViewModel model)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Home"));
            }
            if (ModelState.IsValid)
            {
                var succeed = await _signInManager.PasswordSignInAsync(model.id, model.Password, model.RememberMe);

                if (succeed)
                {
                    return(RedirectToAction("Index", "Home"));
                }
                ModelState.AddModelError(string.Empty, "Sai tài khoản hoặc mật khẩu");
            }
            return(View());
        }
コード例 #14
0
        async Task IAuthenticationService.Login(string userName, string password)
        {
            var result = await signinManager.PasswordSignInAsync(userName, password, true, false);

            if (result != SignInStatus.Success)
            {
                string message = "Failed to login.";
                if (result == SignInStatus.Failure)
                {
                    message = "Bad user name or password combination.";
                }
                else if (result == SignInStatus.LockedOut)
                {
                    message = "Account has been locked.";
                }
                throw new LoginException(message);
            }
        }
コード例 #15
0
        public async Task <User> LoginAsync(string email, string password)
        {
            var user = await _userManager.FindByEmailAsync(email);

            if (user == null)
            {
                throw new UnauthorizedAccessException();
            }

            var result = await _signInManager.PasswordSignInAsync(user.UserName, password, false, false);

            if (result.Succeeded)
            {
                return(user);
            }

            _logger.LogWarning($"Authentication failed for username {user.UserName}");
            throw new UnauthorizedAccessException();
        }
コード例 #16
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(LoginData.Username, LoginData.Password);

                if (result.RequiresTwoFactor)
                {
                    return(RedirectToPage("LoginWith2fa"));
                }
                if (result.Succeeded)
                {
                    return(RedirectToPage("Index"));
                }
            }

            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return(Page());
        }
コード例 #17
0
        public async Task <bool> AuthAsync(LoginViewModel model)
        {
            var user = await GetUserAsync(model.Email).ConfigureAwait(false);

            var isEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user).ConfigureAwait(false);

            if (!isEmailConfirmed)
            {
                throw new EmailNotConfirmedException();
            }

            var result = await _signInManager
                         .PasswordSignInAsync(user, model.Password, model.RememberMe, false)
                         .ConfigureAwait(false);

            if (result.IsLockedOut)
            {
                throw new UserLockedOutException();
            }

            return(result.Succeeded);
        }
コード例 #18
0
        //[ValidateAntiForgeryToken]
        public async Task <bool> Post([FromBody] User user)
        {
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            ApplicationUser signedUser = await _userManager.FindByNameAsync(user.Name);

            var result = await _singInManager.PasswordSignInAsync(user.Name, user.Password, false, false);

            switch (result)
            {
            case SignInStatus.Success:
                return(true);
                //case SignInStatus.LockedOut:
                //    return View("Lockout");
                //case SignInStatus.RequiresVerification:
                //    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                //case SignInStatus.Failure:
                //default:
                //    ModelState.AddModelError("", "Invalid login attempt.");
                //    return View(model);
            }
            return(false);
        }
コード例 #19
0
        public async Task <IActionResult> Login(LoginDetailsVM loginDetails)
        {
            try
            {
                var _result = await signInManager.PasswordSignInAsync(loginDetails.Username, loginDetails.Password);

                if (_result.Succeeded)
                {
                    return(Json(new
                    {
                        Success = true,
                        Redirect = "/Dashboard/Index"
                    }));
                }
                else
                {
                    throw new Exception(_result.Message);
                }
            }
            catch (Exception ex)
            {
                return(ErrorView(ex));
            }
        }
コード例 #20
0
        public async Task <IActionResult> LoginSubmit()
        {
            await signInManager.PasswordSignInAsync("test", "test", false);

            return(Redirect("/"));
        }
コード例 #21
0
 public async Task <SignInResult> PasswordSignInAsync(User user, string password)
 {
     return(await _signInManager.PasswordSignInAsync(user, password));
 }
コード例 #22
0
ファイル: AdminService.cs プロジェクト: mlbenoit/aspdotnet
        public async Task <ServiceResult <bool> > LoginAsync(AdminLoginRequest request)
        {
            if (request == null ||
                string.IsNullOrWhiteSpace(request.Email) ||
                string.IsNullOrWhiteSpace(request.Password))
            {
                return(new ServiceResult <bool>(HttpStatusCode.BadRequest));
            }

            SignInResult result = await _signInManager.PasswordSignInAsync(request.Email,
                                                                           request.Password, isPersistent : false, lockoutOnFailure : false);

            if (!result.Succeeded)
            {
                return(new ServiceResult <bool>(HttpStatusCode.Unauthorized));
            }

            UserEntity userEntity = await _userManager.FindByEmailAsync(request.Email);

            if (userEntity == null)
            {
                // This situation may arise when the  user is deleted in another thread
                return(new ServiceResult <bool>(HttpStatusCode.Unauthorized));
            }

            List <Claim> claims = new List <Claim>
            {
                new Claim(ClaimTypes.Email, request.Email),
                new Claim("FullName", $"{userEntity.FirstName} {userEntity.LastName}"),
                new Claim(ClaimTypes.Role, "Administrator"),
            };

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims,
                                                               CookieAuthenticationDefaults.AuthenticationScheme);

            AuthenticationProperties authProperties = new AuthenticationProperties
            {
                //AllowRefresh = <bool>,
                // Refreshing the authentication session should be allowed.

                //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
                // The time at which the authentication ticket expires. A
                // value set here overrides the ExpireTimeSpan option of
                // CookieAuthenticationOptions set with AddCookie.

                //IsPersistent = true,
                // Whether the authentication session is persisted across
                // multiple requests. When used with cookies, controls
                // whether the cookie's lifetime is absolute (matching the
                // lifetime of the authentication ticket) or session-based.

                //IssuedUtc = <DateTimeOffset>,
                // The time at which the authentication ticket was issued.

                //RedirectUri = <string>
                // The full path or absolute URI to be used as an http
                // redirect response value.
            };

            await _httpContextAccessor.HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties);

            //_logger.LogInformation("user {Email} logged in at {Time}." user.Email, DateTime.UtcNow);
            return(new ServiceResult <bool>(true));
        }
コード例 #23
0
        public string Login(string username, string password)
        {
            var _login = signInManager.PasswordSignInAsync(username, password);

            return((_login) ? "" : "WRONG LOGIN ACCOUNT");
        }
コード例 #24
0
        public async Task <IActionResult> SignIn(LoginDetailsVM data)
        {
            var _signinResult = await signInManager.PasswordSignInAsync(data.Username, data.Password);

            return(Json(_signinResult));
        }