public LoginViewModel(LoginInputModel other)
 {
     Username = other.Username;
     Password = other.Password;
     RememberLogin = other.RememberLogin;
     SignInId = other.SignInId;
 }
Пример #2
0
        public LoginViewModel Execute(LoginInputModel inputModel)
        {
            var party = new OpenIdRelyingParty();
            var response = party.GetResponse();
            var viewModel = new LoginViewModel();

            if (response != null && response.Status == AuthenticationStatus.Authenticated)
            {
                _authenticationContext.ThisUserHasBeenAuthenticated(response.ClaimedIdentifier, false);
                viewModel.LoginSuccessful = true;
            }

            return viewModel;
        }
        public ActionResult Save(LoginInputModel loginInputModel)
        {
            var loginToUpdate = new Login();
            loginToUpdate.CreatedDateTime = loginInputModel.CreatedDateTime;
            loginToUpdate.CreatedBy = loginInputModel.CreatedBy;
            loginToUpdate.Password = loginInputModel.Password;
            loginToUpdate.IsAdmin = loginInputModel.IsAdmin;
            loginToUpdate.Id = loginInputModel.Id;
            loginToUpdate.Email = new Email { Address = (string)Session["email"] };

            var mapper = new AutoDataContractMapper();
            var loginData = new LoginData();
            mapper.Map(loginToUpdate, loginData);

            var data = HttpHelper.Put(string.Format(serviceBaseUri + "/Login/{0}", loginInputModel.Id), loginData);
            var savedLogin = new Login();
            mapper.Map(data, savedLogin);
            return PartialView(GetUser());
        }
Пример #4
0
        public void Invoke()
        {
            innerBehavior.Invoke();

            var loginResult = request.Get<LoginResultModel>();
            if(loginResult.Success)
            {
                string url = registry.UrlFor<AdminInputModel>();
                writer.RedirectToUrl(url);
            }
            else
            {
                var inputModel = new LoginInputModel();
                request.SetObject(inputModel);

                IActionBehavior partial = factory.BuildPartial(inputModel.GetType());
                partial.InvokePartial();
            }
        }
Пример #5
0
        public ActionResult Login(LoginInputModel model)
        {
            if (ModelState.IsValid)
            {
                if (WebSecurity.IsAccountLockedOut(model.Name, 6, 3600))
                {
                    ModelState.AddModelError("Password",
                       "Вы пытались ввести пароль слишком много раз. Вам придеться подождать час, прежде чем попытаться войти снова.");
                }

                if (WebSecurity.Login(model.Name, model.Password, true))
                {
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Вы ввели неправильный логин или пароль!");
                }
            }

            return View(model);
        }
Пример #6
0
        public override async Task OnGetAsync()
        {
            LoginInput = new LoginInputModel();

            var context = await Interaction.GetAuthorizationContextAsync(ReturnUrl);

            if (context != null)
            {
                LoginInput.UserNameOrEmailAddress = context.LoginHint;

                //TODO: Reference AspNetCore MultiTenancy module and use options to get the tenant key!
                var tenant = context.Parameters[TenantResolverConsts.DefaultTenantKey];
                if (!string.IsNullOrEmpty(tenant))
                {
                    CurrentTenant.Change(Guid.Parse(tenant));
                    Response.Cookies.Append(TenantResolverConsts.DefaultTenantKey, tenant);
                }
            }

            if (context?.IdP != null)
            {
                LoginInput.UserNameOrEmailAddress = context.LoginHint;
                ExternalProviders = new[] { new ExternalProviderModel {
                                                AuthenticationScheme = context.IdP
                                            } };
                return;
            }

            var schemes = await _schemeProvider.GetAllSchemesAsync();

            var providers = schemes
                            .Where(x => x.DisplayName != null || x.Name.Equals(_accountOptions.WindowsAuthenticationSchemeName, StringComparison.OrdinalIgnoreCase))
                            .Select(x => new ExternalProviderModel
            {
                DisplayName          = x.DisplayName,
                AuthenticationScheme = x.Name
            })
                            .ToList();

            EnableLocalLogin = true; //TODO: We can get default from a setting?
            if (context?.ClientId != null)
            {
                var client = await ClientStore.FindEnabledClientByIdAsync(context.ClientId);

                if (client != null)
                {
                    EnableLocalLogin = client.EnableLocalLogin;

                    if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
                    {
                        providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
                    }
                }
            }

            ExternalProviders = providers.ToArray();

            if (IsExternalLoginOnly)
            {
                //return await ExternalLogin(vm.ExternalLoginScheme, returnUrl);
                throw new NotImplementedException();
            }
        }
Пример #7
0
        public async Task <ActionResult <LoginResultModel> > CreateToken([FromBody] LoginInputModel model)
        {
            var user = await _context.Users
                       .FirstOrDefaultAsync(u => u.UserName == model.Username);

            bool isCredentialsValid = await _userManager.CheckPasswordAsync(user, model.Password);

            if (isCredentialsValid)
            {
                var result = new LoginResultModel();

                var roles = await _userManager.GetRolesAsync(user);

                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    new Claim(ClaimTypes.Email, model.Username)
                };

                var accessTokenClaims = new List <Claim>(claims)
                {
                    new Claim("type", "login")
                };

                var refreshTokenClaims = new List <Claim>(claims)
                {
                    new Claim("type", "refresh")
                };

                foreach (var role in roles)
                {
                    claims.Add(new Claim(ClaimTypes.Role, role));
                }

                string secret      = _configuration.GetSection("Jwt")["Secret"];
                var    key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
                var    credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                string hostUrl = _httpContextAccessor.HttpContext.Request.Host.Value;

                var accessToken = new JwtSecurityToken(
                    issuer: hostUrl,
                    audience: hostUrl,
                    claims: accessTokenClaims,
                    expires: DateTime.Now.AddDays(1),
                    signingCredentials: credentials
                    );

                var refreshToken = new JwtSecurityToken(
                    issuer: hostUrl,
                    audience: hostUrl,
                    claims: refreshTokenClaims,
                    expires: DateTime.Now.AddDays(7),
                    signingCredentials: credentials
                    );

                return(new LoginResultModel()
                {
                    RefreshToken = new JwtSecurityTokenHandler().WriteToken(refreshToken),
                    AccessToken = new JwtSecurityTokenHandler().WriteToken(accessToken),
                    User = new UserOutputModel()
                    {
                        Email = user.Email,
                        UserName = user.UserName,
                        Id = user.Id
                    }
                });
            }
            return(BadRequest(new
            {
                Message = "Could not verify credentials"
            }));
        }
Пример #8
0
 public UserDto AuthenticateUser(LoginInputModel login)
 {
     return(_userRepository.AuthenticateUser(login));
 }
Пример #9
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // the user clicked the "cancel" button
            if (button != "login")
            {
                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    if (await _clientStore.IsPkceClientAsync(context.ClientId))
                    {
                        // if the client is PKCE then we assume it's native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(View("Redirect", new RedirectViewModel {
                            RedirectUrl = model.ReturnUrl
                        }));
                    }

                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                var result = await _loginService.Login(model);

                if (result.Succeeded)
                {
                    // request for a local page
                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }

                    if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect(
                                   $"/connect/authorize/callback?client_id=portalAngularClient&redirect_uri={_settings.Value.Urls.PortalRedirect}&response_type=id_token token&scope=openid+email+profile+re_api+ag_api+ao_api+ma_api+am_api+pm_api+co_api+cu_api+pe_api+ad_api&nonce={Guid.NewGuid().ToString().Substring(0, 5)}"));
                    }

                    // user might have clicked on a malicious link - should be logged
                    throw new Exception("invalid return URL");
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Пример #10
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            if (button != "login")
            {
                var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

                if (context != null)
                {
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);


                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                if (await _customUserStore.ValidateCredentials(new Core.Model.User.UserLoginModel {
                    UserName = model.Username, UserPwd = model.Password
                }))
                {
                    var user = await _customUserStore.GetByUserName(model.Username);

                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.UserId.ToString(), user.UserName));


                    AuthenticationProperties props = null;
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    }
                    ;

                    await HttpContext.SignInAsync(user.UserId.ToString(), user.UserName, props);


                    return(Redirect(model.ReturnUrl));

                    #region liyouming 屏蔽 不复核实际要求
                    //if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                    //{
                    //    return Redirect(model.ReturnUrl);
                    //}

                    //return Redirect("~/");
                    #endregion
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "登录失败"));

                ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
            }


            var vm = await _account.BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Пример #11
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            if (ModelState.IsValid)
            {
                SqlUserModel sqlUser;
                _legacySqlLoginAdapter.AddCredentials(model.Username, model.Password);
                if (await _userManager.FindByNameAsync(model.Username) == null)
                {
                    if (_legacySqlLoginAdapter.CheckUser())
                    {
                        sqlUser = _legacySqlLoginAdapter.LoginWithUser();
                        if (sqlUser != null)
                        {
                            var appUser = new ApplicationUser {
                                Email              = sqlUser.Email,
                                UserName           = sqlUser.Username,
                                EmailConfirmed     = true,
                                NormalizedEmail    = sqlUser.Email.ToUpper(),
                                NormalizedUserName = sqlUser.Username.ToUpper()
                            };
                            var user = await _userManager.CreateAsync(appUser);

                            await _userManager.AddLoginAsync(appUser,
                                                             new UserLoginInfo("legacySql", "legacySql", "legacySqlProvider"));

                            await _signInManager.SignInAsync(appUser, new AuthenticationProperties(), "legacySql");

                            await _userManager.AddClaimsAsync(appUser, sqlUser.Claims);

                            await _events.RaiseAsync(new UserLoginSuccessEvent(appUser.UserName, appUser.Id,
                                                                               appUser.UserName, clientId : context?.ClientId));

                            if (context != null)
                            {
                                if (await _clientStore.IsPkceClientAsync(context.ClientId))
                                {
                                    // if the client is PKCE then we assume it's native, so this change in how to
                                    // return the response is for better UX for the end user.
                                    return(View("Redirect", new RedirectViewModel {
                                        RedirectUrl = model.ReturnUrl
                                    }));
                                }

                                // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                                return(Redirect(model.ReturnUrl));
                            }

                            // request for a local page
                            if (Url.IsLocalUrl(model.ReturnUrl))
                            {
                                return(Redirect(model.ReturnUrl));
                            }
                            if (string.IsNullOrEmpty(model.ReturnUrl))
                            {
                                return(Redirect("~/"));
                            }
                            throw new Exception("invalid return URL");
                        }
                    }
                }

                var sqlLogin = _legacySqlLoginAdapter.LoginWithUser();
                if (sqlLogin != null)
                {
                    var user = await _userManager.FindByNameAsync(model.Username);

                    await _signInManager.SignInAsync(user, null, "legacySql");

                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName,
                                                                       clientId : context?.ClientId));

                    if (context != null)
                    {
                        if (await _clientStore.IsPkceClientAsync(context.ClientId))
                        {
                            // if the client is PKCE then we assume it's native, so this change in how to
                            // return the response is for better UX for the end user.
                            return(View("Redirect", new RedirectViewModel {
                                RedirectUrl = model.ReturnUrl
                            }));
                        }

                        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                        return(Redirect(model.ReturnUrl));
                    }

                    // request for a local page
                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect("~/"));
                    }
                    throw new Exception("invalid return URL");
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials",
                                                                   clientId : context?.ClientId));

                ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Пример #12
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // the user clicked the "cancel" button
            if (button != "login")
            {
                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    if (await _clientStore.IsPkceClientAsync(context.ClientId))
                    {
                        // if the client is PKCE then we assume it's native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(View("Redirect", new RedirectViewModel {
                            RedirectUrl = model.ReturnUrl
                        }));
                    }

                    return(Redirect(model.ReturnUrl));
                }

                // since we don't have a valid context, then we just go back to the home page
                return(Redirect("~/"));
            }

#if !DEBUG
            // Google reCAPTCHA
            var reCaptcha = await _reCaptchaService.ValidateAsync(model.Token);

            if (!reCaptcha.success)
            {
                ModelState.AddModelError("", "There was an error validating reCAPTCHA. Please try again!");
            }
#endif

            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberLogin, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    var user = await _userManager.FindByNameAsync(model.Username);

                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName));

                    if (context != null)
                    {
                        if (await _clientStore.IsPkceClientAsync(context.ClientId))
                        {
                            // if the client is PKCE then we assume it's native, so this change in how to
                            // return the response is for better UX for the end user.
                            return(View("Redirect", new RedirectViewModel {
                                RedirectUrl = model.ReturnUrl
                            }));
                        }

                        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                        return(Redirect(model.ReturnUrl));
                    }

                    // request for a local page
                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }

                    if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect("~/"));
                    }

                    // user might have clicked on a malicious link - should be logged
                    throw new Exception("invalid return URL");
                }

                // TODO: Check why login has failed

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Пример #13
0
        public async Task <IActionResult> Index(LoginInputModel model)
        {
            if (ModelState.IsValid)
            {
                var cookies = CookieAuthenticationDefaults.AuthenticationScheme;
                //or
                var c = OAuthDefaults.DisplayName;

                var user = _infoDbContext.users.FirstOrDefault(_ => _.Email == model.Email && _.PassWord == Utils.MD5(model.Password));

                if (user != null)
                {
                    AuthenticationProperties props = null;
                    if (model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,                                                             //持久化
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration) //过期时间
                        };
                    }
                    ;
                    var claims = new List <Claim> {
                        //Subject:颁发者处最终用户的唯一标识符
                        new Claim(JwtClaimTypes.Subject, user.Id.ToString()),
                        //Id:仅仅是标识符
                        new Claim(JwtClaimTypes.Id, user.Id.ToString()),
                        new Claim(JwtClaimTypes.Name, user.UserName)
                    };
                    var claimIdentity   = new ClaimsIdentity(claims, cookies);
                    var claimsPrincipal = new ClaimsPrincipal(claimIdentity);
                    await HttpContext.SignInAsync(cookies, claimsPrincipal, props);

                    // var refererUrl = Request.Headers["Referer"].ToString();
                    var returnUrl = Request.Query["ReturnUrl"].ToString();
                    returnUrl = string.IsNullOrWhiteSpace(returnUrl) ? "/" : returnUrl;
                    return(Redirect(returnUrl));
                }
                else
                {
                    //ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
                    ModelState.AddModelError(string.Empty, "用户名或密码错误!");
                }

                #region in mem
                //if (model.Email == "*****@*****.**" && model.Password == "123")
                //{
                //    AuthenticationProperties props = null;
                //    if (model.RememberLogin)
                //    {
                //        props = new AuthenticationProperties
                //        {
                //            IsPersistent = true, //持久化
                //            ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration) //过期时间
                //        };
                //    };
                //    var claims = new List<Claim> {
                //    //Subject:颁发者处最终用户的唯一标识符
                //    new Claim(JwtClaimTypes.Subject,"1000"),
                //    //Id:仅仅是标识符
                //    new Claim(JwtClaimTypes.Id,"1000"),
                //    new Claim(JwtClaimTypes.Name,"nsky")
                // };
                //    var claimIdentity = new ClaimsIdentity(claims, cookies);
                //    var claimsPrincipal = new ClaimsPrincipal(claimIdentity);
                //    await HttpContext.SignInAsync(cookies, claimsPrincipal, props);
                //}
                #endregion
            }
            //模型验证失败,跳转到当前页面,会显示错误信息
            return(View());
        }
Пример #14
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // check if we are in the context of an authorization request
            var context = await this.interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // the user clicked the "cancel" button
            if (button != "login")
            {
                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await this.interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    if (await this.clientStore.IsPkceClientAsync(context.ClientId))
                    {
                        // if the client is PKCE then we assume it's native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(View("Redirect", new RedirectViewModel {
                            RedirectUrl = model.ReturnUrl
                        }));

                        // The client is native, so this change in how to
                        // return the response is for better UX for the end user.
                        //// return this.LoadingPage("Redirect", model.ReturnUrl);
                    }

                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                // validate username/password against Ldap
                var user = this.userStore.ValidateCredentials(model.Username, model.Password);

                if (user != default(IAppUser))
                {
                    // Raise UserLoginSuccessEvent
                    await this.events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username));

                    // only set explicit expiration here if user chooses "remember me".
                    // otherwise we rely upon expiration configured in cookie middleware.
                    AuthenticationProperties props = null;
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        // See https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-3.1#persistent-cookies
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    }
                    ;

                    // Response with authentication cookie
                    await this.HttpContext.SignInAsync(user.SubjectId, user.Username, props);

                    if (context != null)
                    {
                        if (await this.clientStore.IsPkceClientAsync(context?.ClientId))
                        {
                            // if the client is PKCE then we assume it's native, so this change in how to
                            // return the response is for better UX for the end user.
                            return(View("Redirect", new RedirectViewModel {
                                RedirectUrl = model.ReturnUrl
                            }));

                            // The client is native, so this change in how to
                            // return the response is for better UX for the end user.
                            ////return this.LoadingPage("Redirect", model.ReturnUrl);
                        }

                        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                        return(Redirect(model.ReturnUrl));
                    }

                    // request for a local page
                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    else if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect("~/"));
                    }
                    else
                    {
                        // user might have clicked on a malicious link - should be logged
                        throw new Exception("Invalid return URL");
                    }
                }
                else
                {
                    await this.events.RaiseAsync(new UserLoginFailureEvent(model.Username, "Invalid credentials", clientId : context?.ClientId));

                    ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
                }
            }

            // something went wrong, show form with error
            var vm = await this.buildLoginViewModelAsync(model);

            return(View(vm));
        }
Пример #15
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            if (button != "login")
            {
                // the user clicked the "cancel" button
                var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                // validate username/password against in-memory store
                if (_userRepository.ValidateCredentials(model.Username, model.Password))
                {
                    var user = _userRepository.FindByUsername(model.Username);
                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.UserName, user.SubjectId));

                    // only set explicit expiration here if user chooses "remember me".
                    // otherwise we rely upon expiration configured in cookie middleware.
                    AuthenticationProperties props = null;
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    }
                    ;

                    // issue authentication cookie with subject ID and username
                    await HttpContext.SignInAsync(user.SubjectId, user.UserName, props);

                    // make sure the returnUrl is still valid, and if so redirect back to authorize endpoint or a local page
                    // the IsLocalUrl check is only necessary if you want to support additional local pages, otherwise IsValidReturnUrl is more strict
                    if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }

                    return(Redirect("~/"));
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
 public LoginViewModel(LoginInputModel other)
 {
     Username  = other.Username;
     Password  = other.Password;
     ReturnUrl = other.ReturnUrl;
 }
Пример #17
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // the user clicked the "cancel" button
            if (button != "login")
            {
                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    if (await _clientStore.IsPkceClientAsync(context.ClientId))
                    {
                        // if the client is PKCE then we assume it's native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(View("Redirect", new RedirectViewModel {
                            RedirectUrl = model.ReturnUrl
                        }));
                    }

                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberLogin, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    var user = await _userManager.FindByNameAsync(model.Username);

                    await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, await StoreRememberClient(user));

                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id.ToString(), user.UserName));

                    //if (context != null)
                    //{
                    //    if (await _clientStore.IsPkceClientAsync(context.ClientId))
                    //    {
                    //        // if the client is PKCE then we assume it's native, so this change in how to
                    //        // return the response is for better UX for the end user.
                    //        return View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl });
                    //    }

                    //    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    //    return Redirect(model.ReturnUrl);
                    //}

                    return(RedirectToAction("PickRole", new { returnUrl = model.ReturnUrl }));
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
 public ActionResult Login(LoginInputModel model)
 {
     return(View(model));
 }
Пример #19
0
        public async Task <IActionResult> Login(LoginInputModel model)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            if (ModelState.IsValid)
            {
                AuthenticationProperties props        = null;
                IdentityServerUser       isuser       = null;
                UserLoginSuccessEvent    successEvent = null;
                bool   isValid = false;
                string errMsg  = null;

                // 测试用户
                var testUser = OAuthConfig.GetTestUsers().Find(t => t.Username == model.Username && t.Password == model.Password);
                if (testUser != null)
                {
                    successEvent = new UserLoginSuccessEvent(testUser.Username, testUser.SubjectId, testUser.Username, clientId: context?.Client.ClientId);
                    // issue authentication cookie with subject ID and username
                    isuser = new IdentityServerUser(testUser.SubjectId)
                    {
                        DisplayName      = testUser.Username,
                        AdditionalClaims =
                        {
                            new Claim(UserClaimEnum.UserId.ToString(),   testUser.SubjectId),
                            new Claim(UserClaimEnum.UserName.ToString(), testUser.Username)
                        }
                    };
                    isValid = true;
                }
                else
                {
                    //E登账号
                    var edUser = _edApiService.GetEdUser(model.Username, model.Password, out string msg);
                    errMsg = msg;
                    if (edUser != null)
                    {
                        successEvent = new UserLoginSuccessEvent(edUser.LoginName, edUser.ID.ToString(), edUser.EmployeeName, clientId: context?.Client.ClientId);
                        // issue authentication cookie with subject ID and username
                        isuser = new IdentityServerUser(edUser.ID.ToString())
                        {
                            DisplayName      = edUser.EmployeeName,
                            AdditionalClaims =
                            {
                                new Claim(UserClaimEnum.UserId.ToString(),   edUser.ID.ToString()),
                                new Claim(UserClaimEnum.UserName.ToString(), edUser.EmployeeName.ToString())
                            }
                        };
                        isValid = true;
                    }
                }

                if (isValid)
                {
                    //身份认证通过
                    await _events.RaiseAsync(successEvent);

                    // only set explicit expiration here if user chooses "remember me".
                    // otherwise we rely upon expiration configured in cookie middleware.
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    }
                    ;
                    await HttpContext.SignInAsync(isuser, props);

                    if (context != null)
                    {
                        if (context.IsNativeClient())
                        {
                            // The client is native, so this change in how to
                            // return the response is for better UX for the end user.
                            return(this.LoadingPage("Redirect", model.ReturnUrl));
                        }
                        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                        return(Redirect(model.ReturnUrl));
                    }
                    // request for a local page
                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    else if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect("~/"));
                    }
                    else
                    {
                        // user might have clicked on a malicious link - should be logged
                        throw new Exception("无效的返回URL");
                    }
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "无效的证书", clientId : context?.Client.ClientId));

                ModelState.AddModelError(string.Empty, errMsg ?? AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Пример #20
0
 public async Task <ApiResponse> Login(LoginInputModel parameters)
 {
     return(ModelState.IsValid ? await _accountManager.Login(parameters) : new ApiResponse(Status400BadRequest, L["InvalidData"]));
 }
Пример #21
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            _logger.LogInformation("Login. Email: {Email}, Remember login: {RememberLogin}.",
                                   model.Email, model.RememberLogin);

            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // the user clicked the "cancel" button
            if (button != "login")
            {
                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    if (context.IsNativeClient())
                    {
                        // The client is native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(this.LoadingPage("Redirect", model.ReturnUrl));
                    }

                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                var user = await _userRepository.GetUserByEmailAsync(model.Email.ToLower());

                var isHavePassword = !string.IsNullOrEmpty(user.HashPassword) && !string.IsNullOrEmpty(user.Salt);

                if (!user.IsEmpty() && isHavePassword)
                {
                    _logger.LogInformation("Login. Found user by mail: id {Id}, name {Name}, Surname {Surname}, mail {Mail}.",
                                           user.Id, user.Name, user.Surname, user.Mail);

                    //Validate found user
                    if (_userService.ValidateCredentials(user, model.Password))
                    {
                        _logger.LogInformation("Login. Validate Credentials was success. User: id {Id}, name {Name}, " +
                                               "Surname {Surname}, mail {Mail}.", user.Id, user.Name, user.Surname, user.Mail);

                        await _events.RaiseAsync(new UserLoginSuccessEvent(user.Name, user.Id.ToString(), user.Name));

                        // only set explicit expiration here if user chooses "remember me".
                        // otherwise we rely upon expiration configured in cookie middleware.
                        AuthenticationProperties props = null;
                        if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                        {
                            props = new AuthenticationProperties
                            {
                                IsPersistent = true,
                                ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                            };
                        }
                        ;

                        // issue authentication cookie with subject ID and username
                        var isuser = new IdentityServerUser(user.Id.ToString())
                        {
                            DisplayName = user.Name
                        };

                        await HttpContext.SignInAsync(isuser, props);

                        if (context != null)
                        {
                            if (context.IsNativeClient())
                            {
                                // The client is native, so this change in how to
                                // return the response is for better UX for the end user.
                                return(this.LoadingPage("Redirect", model.ReturnUrl));
                            }

                            // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                            return(Redirect(model.ReturnUrl));
                        }

                        // request for a local page
                        if (Url.IsLocalUrl(model.ReturnUrl))
                        {
                            return(Redirect(model.ReturnUrl));
                        }
                        else if (string.IsNullOrEmpty(model.ReturnUrl))
                        {
                            return(Redirect("~/"));
                        }
                        else
                        {
                            // user might have clicked on a malicious link - should be logged
                            throw new Exception("invalid return URL");
                        }
                    }
                    else
                    {
                        _logger.LogWarning("Login. Validate Credentials was failed. User: id {Id}, name {Name}, " +
                                           "Surname {Surname}, mail {Mail}.", user.Id, user.Name, user.Surname, user.Mail);
                    }
                    _logger.LogWarning("Login. User with email {email} not exist.", model.Email.ToLower());
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Email, "invalid credentials", clientId : context?.Client.ClientId));

                ModelState.AddModelError(string.Empty, _localizer["Invalid_email_or_password"].Value);
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Пример #22
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            if (button != "login")
            {
                // the user clicked the "cancel" button
                var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            var returnUrl = model.ReturnUrl;

            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.RememberLogin, lockoutOnFailure : _stsConfig.EnableAccountLockout);

                if (result.Succeeded)
                {
                    _logger.LogInformation(1, "User logged in.");
                    var user = await _userManager.FindByNameAsync(model.Email);

                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id.ToString(), user.UserName));

                    // make sure the returnUrl is still valid, and if so redirect back to authorize endpoint or a local page
                    // the IsLocalUrl check is only necessary if you want to support additional local pages, otherwise IsValidReturnUrl is more strict
                    if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }

                    return(Redirect("~/"));
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToAction(nameof(VerifyCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberLogin }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning(2, "User account locked out.");
                    return(View("Lockout"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, _sharedLocalizer["INVALID_LOGIN_ATTEMPT"]);
                    return(View(await BuildLoginViewModelAsync(model)));
                }
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Пример #23
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // the user clicked the "cancel" button
            if (button != "login")
            {
                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    if (context.IsNativeClient())
                    {
                        // The client is native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(this.LoadingPage("Redirect", model.ReturnUrl));
                    }

                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                // validate username/password against in-memory store
                if (_users.ValidateCredentials(model.Username, model.Password))
                {
                    var user = _users.FindByUsername(model.Username);
                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username, clientId : context?.Client.ClientId));

                    // only set explicit expiration here if user chooses "remember me".
                    // otherwise we rely upon expiration configured in cookie middleware.
                    AuthenticationProperties props = null;
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    }
                    ;

                    // issue authentication cookie with subject ID and username
                    var isuser = new IdentityServerUser(user.SubjectId)
                    {
                        DisplayName = user.Username
                    };

                    await HttpContext.SignInAsync(isuser, props);

                    if (context != null)
                    {
                        if (context.IsNativeClient())
                        {
                            // The client is native, so this change in how to
                            // return the response is for better UX for the end user.
                            return(this.LoadingPage("Redirect", model.ReturnUrl));
                        }

                        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                        return(Redirect(model.ReturnUrl));
                    }

                    // request for a local page
                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    else if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect("~/"));
                    }
                    else
                    {
                        // user might have clicked on a malicious link - should be logged
                        throw new Exception("invalid return URL");
                    }
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials", clientId : context?.Client.ClientId));

                ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Пример #24
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // the user clicked the "cancel" button
            if (button != "login")
            {
                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    if (context.IsNativeClient())
                    {
                        // The client is native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(this.LoadingPage("Redirect", model.ReturnUrl));
                    }

                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password,
                                                                      model.RememberLogin, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    var user = await _userManager.FindByNameAsync(model.Username);

                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName,
                                                                       clientId : context?.Client.ClientId));

                    if (context != null)
                    {
                        if (context.IsNativeClient())
                        {
                            // The client is native, so this change in how to
                            // return the response is for better UX for the end user.
                            return(this.LoadingPage("Redirect", model.ReturnUrl));
                        }

                        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                        return(Redirect(model.ReturnUrl));
                    }

                    // request for a local page
                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    else if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect("~/"));
                    }
                    else
                    {
                        // user might have clicked on a malicious link - should be logged
                        throw new Exception("invalid return URL");
                    }
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials",
                                                                   clientId : context?.Client.ClientId));

                ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Пример #25
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // 检查我们是否在授权请求的上下文中
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // 用户点击了“取消”按钮
            if (button != "login")
            {
                if (context != null)
                {
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    if (await _clientStore.IsPkceClientAsync(context.ClientId))
                    {
                        return(View("Redirect", new RedirectViewModel {
                            RedirectUrl = model.ReturnUrl
                        }));
                    }
                    return(Redirect("~/"));
                }
                else
                {
                    return(Redirect("~/"));
                }
            }
            if (ModelState.IsValid)
            {
                if (model.UserType == "1")
                {
                    var user = _repository.Find("select * from Users where Mobile = @mobile and Status = 0", new { mobile = model.Username });
                    if (user != null)
                    {
                        var encodepassword = Cryptographer.EncodePassword(model.Password, 1, user.Encrypt);
                        if (encodepassword.Equals(user.Password))
                        {
                            await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id.ToString(), user.Mobile));

                            AuthenticationProperties props = null;
                            if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                            {
                                props = new AuthenticationProperties
                                {
                                    IsPersistent = true,
                                    ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                                };
                            }
                            await HttpContext.SignInAsync(user.Id.ToString(), user.Mobile, props);

                            if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                            {
                                return(Redirect(model.ReturnUrl));
                            }
                            return(Redirect("~/"));
                        }
                    }
                    await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "无效用户名或密码"));

                    ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
                }
                else
                {
                    var user = _repository.Find("select * from Consultant where Mobile = @mobile and Status = 0", new { mobile = model.Username });
                }
            }
            return(View());
        }
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> Login(LoginInputModel model, string button, string returnUrl = null)
        {
            if (button != "login")
            {
                // the user clicked the "cancel" button
                var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

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

                if (result.Succeeded)
                {
                    var user = await _userManager.FindByNameAsync(model.Username);

                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName));

                    // only set explicit expiration here if user chooses "remember me".
                    // otherwise we rely upon expiration configured in cookie middleware.
                    AuthenticationProperties props = null;
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    }
                    ;
                    // issue authentication cookie with subject ID and username
                    await HttpContext.SignInAsync(user.Id, user.UserName, props);

                    // make sure the returnUrl is still valid, and if so redirect back to authorize endpoint or a local page
                    if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }

                    return(Redirect("~/"));
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberLogin }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToAction(nameof(Lockout)));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    //return View(model);
                }
            }

            // something went wrong, show form with error
            var loginViewModel = await accountService.BuildLoginViewModelAsync(model);

            return(View(loginViewModel));
        }
        public async Task <IActionResult> Login(LoginInputModel model)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            if (ModelState.IsValid)
            {
                // validate username/password
                var user = await _userManager.FindByNameAsync(model.Username);

                if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
                {
                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.FullName));

                    // only set explicit expiration here if user chooses "remember me".
                    // otherwise we rely upon expiration configured in cookie middleware.
                    AuthenticationProperties props = null;
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    }
                    ;

                    // issue authentication cookie with subject ID and username
                    await HttpContext.SignInAsync(user.Id, user.UserName, props);

                    if (context != null)
                    {
                        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                        return(Redirect(model.ReturnUrl));
                    }

                    // request for a local page
                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    else if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect("~/"));
                    }
                    else
                    {
                        // user might have clicked on a malicious link - should be logged
                        throw new Exception("invalid return URL");
                    }
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = new LoginViewModel
            {
                Username      = model.Username,
                RememberLogin = model.RememberLogin
            };

            return(View(vm));;
        }
Пример #28
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // the user clicked the "cancel" button
            if (button != "login")
            {
                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    if (await _clientStore.IsPkceClientAsync(context.ClientId))
                    {
                        // if the client is PKCE then we assume it's native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(View("Redirect", new RedirectViewModel {
                            RedirectUrl = model.ReturnUrl
                        }));
                    }

                    return(Redirect(model.ReturnUrl));
                }

                // since we don't have a valid context, then we just go back to the home page
                return(Redirect("~/"));
            }

            if (ModelState.IsValid)
            {
                var user = await _userResolver.GetUserAsync(model.Username);

                if (user != default(TUser))
                {
                    var result = await _signInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememberLogin, lockoutOnFailure : true);

                    if (result.Succeeded)
                    {
                        await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id.ToString(), user.UserName));

                        if (context != null)
                        {
                            if (await _clientStore.IsPkceClientAsync(context.ClientId))
                            {
                                // if the client is PKCE then we assume it's native, so this change in how to
                                // return the response is for better UX for the end user.
                                return(View("Redirect", new RedirectViewModel {
                                    RedirectUrl = model.ReturnUrl
                                }));
                            }

                            // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                            return(Redirect(model.ReturnUrl));
                        }

                        // request for a local page
                        if (Url.IsLocalUrl(model.ReturnUrl))
                        {
                            return(Redirect(model.ReturnUrl));
                        }

                        if (string.IsNullOrEmpty(model.ReturnUrl))
                        {
                            return(Redirect("~/"));
                        }

                        // user might have clicked on a malicious link - should be logged
                        throw new Exception("invalid return URL");
                    }

                    if (result.RequiresTwoFactor)
                    {
                        return(RedirectToAction(nameof(LoginWith2fa), new { model.ReturnUrl, RememberMe = model.RememberLogin }));
                    }

                    if (result.IsLockedOut)
                    {
                        return(View("Lockout"));
                    }
                }
                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Пример #29
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            if (button != "login")
            {
                // the user clicked the "cancel" button
                var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberLogin, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    var user = await _userManager.FindByNameAsync(model.Username);

                    if (user.EmailConfirmed)
                    {
                        await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName));

                        if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                        {
                            return(Redirect(model.ReturnUrl));
                        }

                        return(Redirect("~/"));
                    }
                    else
                    {
                        return(Redirect("~/Account/SendConfirmEmail?Email=" + user.UserName));
                    }
                }
                if (result.IsLockedOut)
                {
                    ModelState.AddModelError("", "登录被锁定,请您5分钟后再登录!");
                }
                if (result.IsNotAllowed)
                {
                    ModelState.AddModelError("", "登录被锁定,请您5分钟后再登录!");
                }
                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                ModelState.AddModelError("", "账号密码错误!");
            }
            var vm = await BuildLoginViewModelAsync(model);

            // If we got this far, something failed, redisplay form
            return(View(vm));
        }
Пример #30
0
 public async Task <LoginViewModel> Login([FromBody] LoginInputModel model)
 {
     return(await this.AccountService.LogIn(model));
 }
Пример #31
0
 public LoginViewModel()
 {
     InputModel = new LoginInputModel();
 }
 public User ReadUserFromLoginInput(LoginInputModel model)
 {
     return(_ctx.Users.FirstOrDefault(u => u.Username == model.Username));
 }
Пример #33
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            if (button != "login")
            {
                // the user clicked the "cancel" button
                var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                UserViewModel userIdentity;
                if (model.IsUsernameEmail())
                {
                    userIdentity = await _userAppService.FindByEmailAsync(model.Username);
                }
                else
                {
                    userIdentity = await _userAppService.FindByNameAsync(model.Username);
                }

                if (userIdentity == null)
                {
                    await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                    ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
                }

                if (userIdentity != null)
                {
                    var result = await _signInManager.PasswordSignInAsync(userIdentity.UserName, model.Password, model.RememberLogin, lockoutOnFailure : true);

                    if (result.Succeeded)
                    {
                        await _events.RaiseAsync(new UserLoginSuccessEvent(userIdentity.UserName, userIdentity.Id.ToString(), userIdentity.UserName));

                        // make sure the returnUrl is still valid, and if so redirect back to authorize endpoint or a local page
                        // the IsLocalUrl check is only necessary if you want to support additional local pages, otherwise IsValidReturnUrl is more strict
                        if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                        {
                            return(Redirect(model.ReturnUrl));
                        }

                        return(Redirect("~/"));
                    }
                    else
                    {
                        await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                        ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
                    }
                }
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Пример #34
0
 public MessageToSend post_my_route(LoginInputModel input)
 {
     //Send message using routing rules in TransportRegistry
     return new MessageToSend();
 }
Пример #35
0
        public async Task Login_GivenUnsuccesfulLogin_ViewResultReturned()
        {
            using var accountController = new AccountController(fakeUserManager, fakeSignInManager, mockIdentityServerInteractionService, mockClientStore, mockAuthenticationSchemeProvider,
                                                                mockEventService, urlTestEncoder, mockConfiguration);

            var urlHelper = Substitute.For <IUrlHelper>();

            urlHelper.IsLocalUrl(Arg.Any <string>()).Returns(false);
            accountController.Url = urlHelper;

            var inputModel = new LoginInputModel()
            {
                Username      = "******",
                Password      = "******",
                RememberLogin = false,
                ReturnUrl     = string.Empty
            };

            fakeSignInManager.SetSignInSuccessful(false);
            fakeUserManager.SetUserModel(userModel);

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                          .AddEnvironmentVariables();

            var config = builder.Build();

            config.GetSection("TwoFactorAuthentication")["OrganizationEnforced"] = "false";
            config.GetSection("TwoFactorAuthentication")["AuthenticatorEnabled"] = "false";
            mockConfiguration.GetSection("TwoFactorAuthentication").Returns(config.GetSection("TwoFactorAuthentication"));

            // Act
            var actionResult = await accountController.Login(inputModel, "login");

            // Assert
            var viewResult = actionResult as ViewResult;

            Assert.NotNull(viewResult);

            var model = viewResult.Model as LoginViewModel;

            Assert.NotNull(model);

            Assert.True(accountController.ModelState.ErrorCount > 0, $"Modelstate must have errors.");

            bool errorFound = false;

            foreach (var modelState in accountController.ModelState.Values)
            {
                foreach (var error in modelState.Errors)
                {
                    if (error.ErrorMessage == AccountOptions.InvalidCredentialsErrorMessage)
                    {
                        errorFound = true;
                    }
                }
            }

            Assert.True(errorFound, $"Account locked out should return error message '{AccountOptions.InvalidCredentialsErrorMessage}'.");
        }
Пример #36
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // Check if we are in the context of an authorization request.
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // The user clicked the 'cancel' button.
            if (button != "login")
            {
                if (context != null)
                {
                    // If the user cancels, send a result back into IdentityServer as if they denied the consent (even if this client does not require consent).
                    // This will send back an access denied OIDC error response to the client.
                    await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied);

                    // We can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null.
                    if (context.IsNativeClient())
                    {
                        // The client is native, so this change in how to return the response is for better UX for the end user.
                        return(this.LoadingPage("Redirect", model.ReturnUrl));
                    }
                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // Since we don't have a valid context, then we just go back to the home page.
                    return(Redirect("~/"));
                }
            }
            if (ModelState.IsValid)
            {
                // Validate username/password against database.
                var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, AccountOptions.AllowRememberLogin&& model.RememberLogin, lockoutOnFailure : true);

                User user = null;
                if (result.Succeeded)
                {
                    user = await _userManager.FindByNameAsync(model.UserName);

                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName));

                    _logger.LogInformation("User '{UserName}' and email {Email} was successfully logged in.", user.UserName, user.Email);
                    if (context != null)
                    {
                        if (context.IsNativeClient())
                        {
                            // The client is native, so this change in how to return the response is for better UX for the end user.
                            return(this.LoadingPage("Redirect", model.ReturnUrl));
                        }
                        // We can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null.
                        return(Redirect(model.ReturnUrl));
                    }
                    // Request for a local page.
                    if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    else if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect("~/"));
                    }
                    else
                    {
                        // User might have clicked on a malicious link - should be logged.
                        _logger.LogError("User '{UserName}' might have clicked a malicious link during login: {ReturnUrl}.", UserName, model.ReturnUrl);
                        throw new Exception("Invalid return URL.");
                    }
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User '{UserName}' was locked out after {WrongLoginsNumber} unsuccessful login attempts.", UserName, user?.AccessFailedCount);
                    await _events.RaiseAsync(new UserLoginFailureEvent(model.UserName, "User locked out."));

                    ModelState.AddModelError(string.Empty, "Your account is temporarily locked. Please contact system administrator.");
                }
                else
                {
                    _logger.LogWarning("User '{UserName}' entered invalid credentials during login.", UserName);
                    await _events.RaiseAsync(new UserLoginFailureEvent(model.UserName, "Invalid credentials."));

                    ModelState.AddModelError(string.Empty, "Please check your credentials.");
                }
            }
            // Something went wrong, show form with error.
            var viewModel = await _accountService.BuildLoginViewModelAsync(model);

            return(View(viewModel));
        }
Пример #37
0
 public LoginViewModel Execute(
     LoginInputModel inputModel
     )
 {
     return new LoginViewModel();
 }