예제 #1
0
        public async Task <ActionResult> Login(LoginViewModel loginViewModel, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                ViewBag.returnUrl = returnUrl;
                var user = _testUserStore.FindByUsername(loginViewModel.UserName);
                if (user == null)
                {
                    ModelState.AddModelError(nameof(user.Username), "用户名不存在");
                }
                else
                {
                    bool result = _testUserStore.ValidateCredentials(loginViewModel.UserName, loginViewModel.Password);
                    if (result)
                    {
                        var props = new AuthenticationProperties()
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(30)
                        };
                        await HttpContext.SignInAsync(user.SubjectId, user.Username, props);

                        return(RedirectToRoute(returnUrl));
                    }
                    ModelState.AddModelError(nameof(user.Password), "密码错误");
                }
            }
            return(View());
        }
예제 #2
0
        public async Task <ActionResult> Login(LoginInputModel model)
        {
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            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));

                    // only set explicit expiration here if user chooses "remember me".
                    // otherwise we rely upon expiration configured in cookie middleware.
                    var props = new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(30))
                    };

                    // issue authentication cookie with subject ID and username
                    await HttpContext.SignInAsync(user.SubjectId, 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("", "Invalid username or password");
            }

            await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "SOMETHING WENT WRONG"));

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

            return(View(vm));
        }
예제 #3
0
        public async Task <IActionResult> Login(LoginViewModel Input, string returnUrl)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            ViewBag.ReturnUrl = returnUrl;
            if (ModelState.IsValid)
            {
                var user = _testUserStore.FindByUsername(Input.UserName);
                if (user == null)
                {
                    ModelState.AddModelError(nameof(Input.UserName), "user name not exists");
                }
                else
                {
                    if (!_testUserStore.ValidateCredentials(Input.UserName, Input.Password))
                    {
                        ModelState.AddModelError(nameof(Input.Password), "invalid password");
                    }
                    else
                    {
                        var props = new AuthenticationProperties()
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(30)
                        };
                        await HttpContext.SignInAsync(user.SubjectId, user.Username, props);

                        return(RedirectToLocal(returnUrl));
                    }
                }

                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                //var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: true);
                //if (result.Succeeded)
                //{
                //    _logger.LogInformation("User logged in.");
                //    return LocalRedirect(returnUrl);
                //}
                //if (result.RequiresTwoFactor)
                //{
                //    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                //}
                //if (result.IsLockedOut)
                //{
                //    _logger.LogWarning("User account locked out.");
                //    return RedirectToPage("./Lockout");
                //}
                //else
                //{
                //    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                //    return Page();
                //}
            }
            return(View());
        }
예제 #4
0
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            if (ModelState.IsValid)
            {
                // validate username/password against in-memory store
                if (_users.ValidateCredentials(model.UserName, model.Password))
                {
                    var user = _users.FindByUsername(model.UserName);


                    //(保存)认证信息字典
                    AuthenticationProperties props = new AuthenticationProperties
                    {
                        IsPersistent = true,                                               //认证信息是否跨域有效
                        ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(30)) //凭据有效时间
                    };

                    await Microsoft.AspNetCore.Http.AuthenticationManagerExtensions.SignInAsync(
                        HttpContext, user.SubjectId, user.Username, props);

                    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 = returnUrl
                            }));
                        }

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

                    // request for a local page
                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }
                    else if (string.IsNullOrEmpty(returnUrl))
                    {
                        return(Redirect("~/"));
                    }
                    else
                    {
                        // user might have clicked on a malicious link - should be logged
                        throw new Exception("invalid return URL");
                    }
                }
                ModelState.AddModelError(string.Empty, "errir");
            }
            return(View(model));
        }
 public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
 {
     if (_users.ValidateCredentials(context.UserName, context.Password))
     {
         context.Result = new GrantValidationResult(_users.FindByUsername(context.UserName).SubjectId, "password", null, "local", null);
         return(Task.FromResult(context.Result));
     }
     context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "The username and password do not match", null);
     return(Task.FromResult(context.Result));
 }
예제 #6
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            var context = await interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            if (ModelState.IsValid)
            {
                if (users.ValidateCredentials(model.Username, model.Password))
                {
                    var user = users.FindByUsername(model.Username);
                    await events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username));

                    AuthenticationProperties props = null;
                    if (model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.AddDays(1)
                        };
                    }

                    await HttpContext.SignInAsync(user.SubjectId, user.Username, props);

                    if (context != null)
                    {
                        if (await clientStore.IsPkceClientAsync(context.ClientId))
                        {
                            return(View("Redirect", new RedirectViewModel {
                                RedirectUrl = model.ReturnUrl
                            }));
                        }
                        return(Redirect(model.ReturnUrl));
                    }

                    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"));

                ModelState.AddModelError("", "Invalid username or password");
            }

            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
        //[HttpPost]
        public async Task <IActionResult> DOSLogin([FromBody] LoginInputModel model)
        {
            Uri returnUri = new Uri(model.ReturnUrl);

            var context = await _interaction.GetAuthorizationContextAsync(returnUri.PathAndQuery);

            if (_users.ValidateCredentials(model.Username, model.Password))
            {
                var user = _users.FindByUsername(model.Username);

                if (user != null && context != null)
                {
                    await HttpContext.SignInAsync(user.SubjectId, user.Username);

                    return(new JsonResult(new { RedirectUrl = returnUri.OriginalString }));
                }
            }

            return(Unauthorized());
        }
예제 #8
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 (_users.ValidateCredentials(model.Username, model.Password))
                {
                    var user = _users.FindByUsername(model.Username);
                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username));

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

                    await HttpContext.SignInAsync(user.SubjectId, user.Username, props);

                    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);
            }
            var vm = BuildLoginViewModelAsync(model);

            return(View(vm));
        }
    /// <summary>
    /// Validates the resource owner password credential
    /// </summary>
    /// <param name="context">The context.</param>
    /// <returns></returns>
    public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
    {
        if (_users.ValidateCredentials(context.UserName, context.Password))
        {
            var user = _users.FindByUsername(context.UserName);
            context.Result = new GrantValidationResult(
                user.SubjectId ?? throw new ArgumentException("Subject ID not set", nameof(user.SubjectId)),
                OidcConstants.AuthenticationMethods.Password, _clock.UtcNow.UtcDateTime,
                user.Claims);
        }

        return(Task.CompletedTask);
    }
예제 #10
0
        public async Task <IActionResult> Login(LoginViewModel loginViewModel, string returnUrl)
        {
            //if (ModelState.IsValid)
            //{
            //    ViewData["ReturnUrl"] = returnUrl;
            //    var user = await _userManager.FindByEmailAsync(loginViewModel.Email);
            //    if (user == null)
            //    {
            //        ModelState.AddModelError(nameof(loginViewModel.Email), "Email not exists");
            //    }
            //    else
            //    {
            //        await _signInManager.SignInAsync(user, new AuthenticationProperties { IsPersistent = true });
            //        return RedirectToLoacl(returnUrl);
            //    }
            //}

            if (ModelState.IsValid)
            {
                ViewData["ReturnUrl"] = returnUrl;
                var user = _users.FindByUsername(loginViewModel.UserName);
                if (user == null)
                {
                    ModelState.AddModelError(nameof(loginViewModel.UserName), "UserName not Exist");
                }
                else
                {
                    if (_users.ValidateCredentials(loginViewModel.UserName, loginViewModel.Password))
                    {
                        var props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(30))
                        };

                        await Microsoft.AspNetCore.Http.AuthenticationManagerExtensions.SignInAsync(
                            HttpContext,
                            user.SubjectId,
                            user.Username,
                            props
                            );

                        return(RedirectToLoacl(returnUrl));
                    }

                    ModelState.AddModelError(nameof(loginViewModel.Password), "Wrong Password");
                }
            }

            return(View());
        }
예제 #11
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            var context = await interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            if (ModelState.IsValid)
            {
                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));

                    var isuser = new IdentityServerUser(user.SubjectId)
                    {
                        DisplayName = user.Username
                    };

                    await HttpContext.SignInAsync(isuser);

                    if (context != null)
                    {
                        if (context.IsNativeClient())
                        {
                            return(this.LoadingPage("Redirect", model.ReturnUrl));
                        }

                        return(Redirect(model.ReturnUrl));
                    }

                    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?.Client.ClientId));

                ModelState.AddModelError(string.Empty, "Invalid username or password");
            }

            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
        public async Task <IActionResult> Login(LoginInputModel model)
        {
            if (ModelState.IsValid)
            {
                // validate username/password against in-memory store
                if (_users.ValidateCredentials(model.Username, model.Password))
                {
                    AuthenticationProperties props = null;
                    // only set explicit expiration here if persistent.
                    // otherwise we reply upon expiration configured in cookie middleware.
                    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 user = _users.FindByUsername(model.Username);
                    //get the client id from the auth context
                    var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

                    await _userLoginManager.UserLogin("test", user.SubjectId, user.Claims.ToList(), context?.ClientId);

                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username));

                    await HttpContext.Authentication.SignInAsync(user.SubjectId, user.Username, props);

                    // make sure the returnUrl is still valid, and if yes - redirect back to authorize endpoint or a local page
                    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 _accountService.BuildLoginViewModelAsync(model);

            return(View(vm));
        }
예제 #13
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                //var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: true);
                var testUser = _testUserStore.FindByUsername(Input.UserName);
                if (testUser == null)
                {
                    ModelState.AddModelError(nameof(Input.UserName), "user not exists");
                }
                var result = _testUserStore.ValidateCredentials(Input.UserName, Input.Password);

                if (result)
                {
                    _logger.LogInformation("User logged in.");
                    var props = new Microsoft.AspNetCore.Authentication.AuthenticationProperties()
                    {
                        IsPersistent = true,
                        ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(30)
                    };
                    await HttpContext.SignInAsync(testUser.SubjectId, props);

                    return(LocalRedirect(returnUrl));

                    //return Redirect(returnUrl);
                }
                //if (result.RequiresTwoFactor)
                //{
                //    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                //}
                //if (result.IsLockedOut)
                //{
                //    _logger.LogWarning("User account locked out.");
                //    return RedirectToPage("./Lockout");
                //}
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(Page());
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
예제 #14
0
        public async Task <IActionResult> Login([FromBody] LoginInputModel model)
        {
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            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?.ClientId));

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

                    if (context != null)
                    {
                        return(Redirect(model.ReturnUrl));
                    }

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

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

                ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
            }
            return(Ok());
        }
        public async Task <IActionResult> Login([FromForm] LoginViewModel viewModel)
        {
            if (!_userStore.ValidateCredentials(viewModel.Username, viewModel.Password))
            {
                ModelState.AddModelError("", "Invalid username or password");
                viewModel.Password = string.Empty;
                return(View("/AuthServer/Views/Login.cshtml", viewModel));
            }

            // Use an IdentityServer-compatible ClaimsPrincipal
            var principal = IdentityServerPrincipal.Create(viewModel.Username, viewModel.Username);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

            return(Redirect(viewModel.ReturnUrl));
        }
예제 #16
0
 public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
 {
     if (_userService.ValidateCredentials(context.UserName, context.Password))
     {
         TestUser user = _userService.FindByUsername(context.UserName);
         context.Result = new GrantValidationResult(
             subject: user.SubjectId,
             authenticationMethod: "custom"
             //claims: user.Claims
             );
     }
     else
     {
         context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid custom credential");
     }
 }
예제 #17
0
        public async Task <IActionResult> Index(LoginViewModel vm)
        {
            var validCredentials = _userStore.ValidateCredentials(vm.Username, vm.Password);

            if (!validCredentials)
            {
                ModelState.AddModelError("InvalidCredentials", "Invalid Credentials");
                return(View(vm));
            }

            var user = _userStore.FindByUsername(vm.Username);

            await HttpContext.SignInAsync(user.SubjectId, vm.Username);

            return(Redirect(vm.ReturnUrl));
        }
예제 #18
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)
            {
                // 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));

                    // only set explicit expiration here if user chooses "remember me".
                    // otherwise we rely upon expiration configured in cookie middleware.
                    AuthenticationProperties props = null;

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

                    if (context != null)
                    {
                        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                        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 = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
예제 #19
0
        public async Task <IActionResult> Login(LoginInputModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (!InteractionService.IsValidReturnUrl(model.ReturnUrl))
            {
                throw new InvalidOperationException($"The url of '{model.ReturnUrl}' is not a valid return url.");
            }

            if (ModelState.IsValid)
            {
                if (TestUserStore.ValidateCredentials(model.Username, model.Password))
                {
                    var expiry = DateTimeOffset.UtcNow.Add(AuthorizationOptions.RefreshTokenLifetime);
                    var props  = model.RememberLogin ?
                                 new AuthenticationProperties {
                        ExpiresUtc = expiry, IsPersistent = true
                    } :
                    null;

                    var user = TestUserStore.FindByUsername(model.Username);
                    await HttpContext.Authentication.SignInAsync(user.SubjectId, user.Username, props);

                    return(Redirect(model.ReturnUrl));
                }

                ModelState.AddModelError(string.Empty, "Invalid username or password");
            }

            var authorizationContext = await InteractionService.GetAuthorizationContextAsync(model.ReturnUrl);

            var externalProviders = await GetProvidersAsync(authorizationContext);

            var viewModel = new LoginViewModel
            {
                Username          = model.Username,
                Password          = model.Password,
                RememberLogin     = model.RememberLogin,
                ReturnUrl         = model.ReturnUrl,
                ExternalProviders = externalProviders
            };

            return(View(nameof(Login), viewModel));
        }
예제 #20
0
        public async Task <IActionResult> Login(LoginInputModel model)
        {
            if (ModelState.IsValid)
            {
                if (_users.ValidateCredentials(model.Username, model.Password))
                {
                    var user = _users.FindByUsername(model.Username);

                    await HttpContext.Authentication.SignInAsync(user.SubjectId, user.Username);

                    if (_interaction.IsValidReturnUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                }
            }
            return(Redirect("~/"));
        }
예제 #21
0
        public async Task <IActionResult> Login(LoginInputModel model)
        {
            if (ModelState.IsValid)
            {
                // validate username/password against in-memory stores
                var usuarioOk = _users.ValidateCredentials(model.Username, model.Password);

                if (usuarioOk)
                {
                    AuthenticationProperties props = null;
                    // only set explicit expiration here if persistent.
                    // otherwise we reply upon expiration configured in cookie middleware.
                    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 user = _users.FindByUsername(model.Username);
                    await HttpContext.Authentication.SignInAsync(user.SubjectId, user.Username, props);

                    // make sure the returnUrl is still valid, and if yes - redirect back to authorize endpoint
                    if (_interaction.IsValidReturnUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }

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

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

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

            return(View(vm));
        }
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            if (context.UserName == "monster" && context.Password == "123456")
            {
                context.Result = new GrantValidationResult(
                    "1",
                    OidcConstants.AuthenticationMethods.Password, _clock.UtcNow.UtcDateTime,
                    new Claim[0]);
            }
            else
            {
                //验证失败
                context.Result =
                    new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid custom credential");
            }

            return(Task.CompletedTask);

            //此处使用context.UserName, context.Password 用户名和密码来与数据库的数据做校验
            if (_users.ValidateCredentials(context.UserName, context.Password))
            {
                var user = _users.FindByUsername(context.UserName);

                //验证通过返回结果
                //subjectId 为用户唯一标识 一般为用户id
                //authenticationMethod 描述自定义授权类型的认证方法
                //authTime 授权时间
                //claims 需要返回的用户身份信息单元 此处应该根据我们从数据库读取到的用户信息 添加Claims 如果是从数据库中读取角色信息,那么我们应该在此处添加
                context.Result = new GrantValidationResult(
                    user.SubjectId ?? throw new ArgumentException("Subject ID not set", nameof(user.SubjectId)),
                    OidcConstants.AuthenticationMethods.Password, _clock.UtcNow.UtcDateTime,
                    user.Claims);
            }
            else
            {
                //验证失败
                context.Result =
                    new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid custom credential");
            }

            return(Task.CompletedTask);
        }
예제 #23
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            if (button == "cancel")
            {
                return(Redirect(model.ReturnUrl));
            }

            if (ModelState.IsValid)
            {
                if (_users.ValidateCredentials(model.Username, model.Password))
                {
                    var user = _users.FindByUsername(model.Username);

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

                    var isuser = new IdentityServerUser(user.SubjectId)
                    {
                        DisplayName = user.Username
                    };

                    await HttpContext.SignInAsync(isuser, props);

                    return(Redirect(model.ReturnUrl));
                }

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

            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
예제 #24
0
        public IActionResult Login(string username, string password, string ReturnUrl = "")
        {
            //User user = UserMock.FindUser(username, password);//这里写自己的认证逻辑

            //var claimIdentity = new ClaimsIdentity("Cookie");
            //claimIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
            //claimIdentity.AddClaim(new Claim(ClaimTypes.Name, user.Name));
            //claimIdentity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
            //claimIdentity.AddClaim(new Claim(ClaimTypes.Role, user.Role));
            //var claimsPrincipal = new ClaimsPrincipal(claimIdentity);
            //// 在Startup注册AddAuthentication时,指定了默认的Scheme,在这里便可以不再指定Scheme。
            //base.HttpContext.SignInAsync(claimsPrincipal).Wait(); //SignInAsync 登入

            //if (!string.IsNullOrEmpty(ReturnUrl)) return Redirect(ReturnUrl);

            TestUser user = _users.FindByUsername(username);

            if (user == null)
            {
                ModelState.AddModelError(nameof(username), "username is not exist");
            }
            else
            {
                if (_users.ValidateCredentials(username, password))
                {
                    var props = new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(30))
                    };

                    //HttpContext.SignInAsync(user.SubjectId, user.Username, props);
                    Microsoft.AspNetCore.Http.AuthenticationManagerExtensions.SignInAsync(base.HttpContext, user.SubjectId, user.Username, props);
                    return(Redirect(ReturnUrl));
                }

                ModelState.AddModelError(nameof(password), "wrong password");
            }

            return(View());
        }
예제 #25
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)
            {
                // 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));

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

                    var isuser = new IdentityServerUser(user.SubjectId)
                    {
                        DisplayName = user.Username
                    };

                    await HttpContext.SignInAsync(isuser, props);

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

                ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
            }
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            List <TestUser> userList = new List <TestUser>()
            {
                new TestUser()
                {
                    SubjectId = "1", Password = "******", Username = "******"
                }
            };
            TestUserStore userStore = new TestUserStore(userList);

            //此处使用context.UserName, context.Password 用户名和密码来与数据库的数据做校验
            if (userStore.ValidateCredentials(context.UserName, context.Password))
            {
                var user         = userStore.FindByUsername(context.UserName);
                var resultClaims = new List <Claim>
                {
                    new Claim("测试1", "测试1"),
                    new Claim("测试2", "测试2"),
                    new Claim("测试3", "测试3"),
                    new Claim("测试4", "测试4")
                };
                resultClaims.AddRange(user.Claims);
                //验证通过返回结果
                //subjectId 为用户唯一标识 一般为用户id
                //authenticationMethod 描述自定义授权类型的认证方法
                //authTime 授权时间
                //claims 需要返回的用户身份信息单元 此处应该根据我们从数据库读取到的用户信息 添加Claims 如果是从数据库中读取角色信息,那么我们应该在此处添加
                context.Result = new GrantValidationResult(
                    user.SubjectId ?? throw new ArgumentException("Subject ID not set", nameof(user.SubjectId)),
                    OidcConstants.AuthenticationMethods.Password, _clock.UtcNow.UtcDateTime,
                    resultClaims);
            }
            else
            {
                //验证失败
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid custom credential");
            }
            return(Task.CompletedTask);
        }
예제 #27
0
        public async Task <IActionResult> Login(LoginFormModel form)
        {
            if (ModelState.IsValid == false)
            {
                return(View(new LoginViewModel(form)
                {
                    ExternalLoginList = await GetExternalLoginViewModels(form.ResumeUrl)
                }));
            }

            if (_userStore.ValidateCredentials(form.UserName, form.Password))
            {
                var user       = _userStore.FindByUsername(form.UserName);
                var properties = new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc   = DateTimeOffset.UtcNow.AddHours(1)
                };
                var isuser = new IdentityServerUser(user.SubjectId)
                {
                    DisplayName = user.Username
                };
                await HttpContext.SignInAsync(isuser, properties);

                if (_idsInteraction.IsValidReturnUrl(form.ResumeUrl) || Url.IsLocalUrl(form.ResumeUrl))
                {
                    return(Redirect(form.ResumeUrl));
                }

                return(Redirect("~/"));
            }
            else
            {
                ViewBag.Error = "invalid username or password.";
                return(View(new LoginViewModel(form)
                {
                    ExternalLoginList = await GetExternalLoginViewModels(form.ResumeUrl)
                }));
            }
        }
        public async Task <IActionResult> Login(LoginViewModel loginViewModel, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                ViewData["returnUrl"] = returnUrl;

                //var user = await _userManager.FindByEmailAsync(loginViewModel.Email);
                var user = _users.FindByUsername(loginViewModel.UserName);

                if (user == null)
                {
                    ModelState.AddModelError(nameof(loginViewModel.UserName), "UserName not exists");
                }
                else
                {
                    if (_users.ValidateCredentials(loginViewModel.UserName, loginViewModel.Password))
                    {
                        // issue authentication cookie with subject ID and username
                        var isuser = new IdentityServerUser(user.SubjectId)
                        {
                            DisplayName = user.Username,
                        };
                        //是否记住
                        var prop = new AuthenticationProperties()
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(30))
                        };
                        // 也可以用这个 HttpContext.SignInAsync();
                        await AuthenticationManagerExtensions.SignInAsync(HttpContext, isuser, prop);
                    }
                }
                //账号密码先不做验证,需要可以自己写
                //await _signInManager.SignInAsync(user, new AuthenticationProperties { IsPersistent = true });

                return(RedirectToLocal(returnUrl));
            }

            return(View());
        }
예제 #29
0
        public async Task <IActionResult> Login(LoginInputModel model)
        {
            //当登录提交给后台的model为null,则返回错误信息给前台
            if (model == null)
            {
                //这里我只是简单处理了
                return(View());
            }
            //这里同理,当信息不完整的时候,返回错误信息给前台
            if (string.IsNullOrEmpty(model.Username) || string.IsNullOrEmpty(model.Password))
            {
                //这里只是简单处理了
                return(View());
            }

            //model.Username == "123" && model.Password == "123456"
            //if里面的是验证账号密码,可以用自定义的验证,
            //我这里使用的是TestUserStore的的验证方法,
            if (_users.FindByUsername(model.Username) != null && _users.ValidateCredentials(model.Username, model.Password))
            {
                //配置Cookie
                AuthenticationProperties properties = new AuthenticationProperties()
                {
                    IsPersistent = true,
                    ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(30))
                };

                //使用IdentityServer的SignInAsync来进行注册Cookie
                await HttpContext.SignInAsync(model.Username, model.Username);

                //使用IIdentityServerInteractionService的IsValidReturnUrl来验证ReturnUrl是否有问题
                if (_interaction.IsValidReturnUrl(model.ReturnUrl))
                {
                    return(Redirect(model.ReturnUrl));
                }
                return(View());
            }
            return(View());
        }
예제 #30
0
        public string Login()
        {
           var u =  _user.FindByUsername("niq");
            if (u == null)
            {
                return "用户名为空";
            }
            if(_user.ValidateCredentials("niq", "pwd"))
            {
                //Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.SignInAsync(HttpContext,"",)

                var pr = new AuthenticationProperties {
                    IsPersistent = true,
                    ExpiresUtc=DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(30))
                };
                Microsoft.AspNetCore.Http.AuthenticationManagerExtensions.SignInAsync(HttpContext,
                    "900", "niq", pr);
                return "succes11";

            }
            return "succes";
        }