【问题标题】:Cookie Authentication without Identity Password无需身份密码的 Cookie 身份验证
【发布时间】:2019-05-19 03:26:20
【问题描述】:

我在 Visual Studio 2017 asp.net 核心中使用默认的个人用户帐户模板和我自己的自定义用户表。 User 表有一个PasswordLoginModel 有一个Password。我一直在关注here,为AccountController 中的Login

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public virtual async Task<IActionResult> Login(LoginModel model,
        string returnUrl)
    {
        if (ModelState.IsValid)
        {
            var user = _context.Users.FirstOrDefault(u => u.Email == model.Email);
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Email, user.Email)
            };
            var identity = new ClaimsIdentity(claims);
            var principal = new ClaimsPrincipal(identity);
            await _httpContext.Authentication.SignInAsync
                (CookieAuthenticationDefaults.AuthenticationScheme,
                principal, new AuthenticationProperties
                {
                    IsPersistent = model.RememberMe,
                    ExpiresUtc = DateTime.UtcNow.AddYears(1)
                });
            return RedirectToRoute("HomePage");
        }
        return View(model);
    }

当我运行代码时,如果我输入错误的电子邮件会抛出错误,但我可以输入任何我想要的密码并且它会成功。我如何输入密码以确保它是正确的密码?

【问题讨论】:

    标签: c# asp.net-core cookies


    【解决方案1】:

    密码或其散列版本应传递给服务器登录控制器操作(通过安全的 HTTPS 通道),然后由您根据您的数据库、AD 或任何您现有的系统进行验证,然后再执行SignInAsync。带有硬编码密码的虚拟示例是:

    [HttpPost("login")]
    [AllowAnonymous]
    public async Task<ContentResult> Login(string username, string password)
    {
        if(username!="ADMIN" || password!="123")
            return new ContentResult { Content = "" };
    
        ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(
            new List<Claim>{
                new Claim(ClaimTypes.Name, username)
            },
            "cookies/ADMIN"));
    
        await HttpContext.Authentication.SignInAsync(AdminAuthSchemeName, principal);
    
        return new ContentResult { Content = username };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多