没有身份密码的Cookie身份验证

时间:2017-03-24 07:33:14

标签: c# asp.net-core cookies

我正在使用我自己的自定义用户表在Visual Studio 2017 asp.net核心中使用默认的单个用户帐户模板。 LoginModel表格为PasswordLogin表格为AccountController。我一直关注 [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); } CREATE TABLE #DataTable (id int , EffectiveDate datetime, Enddate Datetime ) INSERT [dbo].#DataTable ([id], [EffectiveDate], [Enddate]) VALUES (1, CAST(N'2017-01-01 00:00:00.000' AS DateTime), CAST(N'2017-01-11 00:00:00.000' AS DateTime)) GO INSERT [dbo].#DataTable ([id], [EffectiveDate], [Enddate]) VALUES (1, CAST(N'2017-01-02 00:00:00.000' AS DateTime), CAST(N'2017-01-05 00:00:00.000' AS DateTime)) GO INSERT [dbo].#DataTable ([id], [EffectiveDate], [Enddate]) VALUES (1, CAST(N'2017-01-03 00:00:00.000' AS DateTime), CAST(N'2017-01-12 00:00:00.000' AS DateTime)) GO INSERT [dbo].#DataTable ([id], [EffectiveDate], [Enddate]) VALUES (1, CAST(N'2017-01-06 00:00:00.000' AS DateTime), CAST(N'2017-01-09 00:00:00.000' AS DateTime)) GO INSERT [dbo].#DataTable ([id], [EffectiveDate], [Enddate]) VALUES (1, CAST(N'2017-01-13 00:00:00.000' AS DateTime), CAST(N'2017-01-19 00:00:00.000' AS DateTime)) GO INSERT [dbo].#DataTable ([id], [EffectiveDate], [Enddate]) VALUES (2, CAST(N'2017-02-01 00:00:00.000' AS DateTime), CAST(N'2017-02-11 00:00:00.000' AS DateTime)) GO INSERT [dbo].#DataTable ([id], [EffectiveDate], [Enddate]) VALUES (2, CAST(N'2017-02-06 00:00:00.000' AS DateTime), CAST(N'2017-02-16 00:00:00.000' AS DateTime)) GO 中的{{1}}。

{{1}}

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

1 个答案:

答案 0 :(得分:0)

密码或其散列版本应传递给服务器登录控制器操作(通过安全的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 };
}