23 身份验证与授权之实现Cookie身份验证
在上一篇中,我们探讨了“身份验证”的概念,了解了用户身份的确认过程。而在本篇中,我们将深入学习如何在ASP.NET Core应用程序中实现基于Cookie的身份验证。通过这个过程,我们将清楚地看到如何通过Cookie存储用户的身份信息,从而为用户的每次请求提供身份验证支持。
什么是Cookie身份验证?
Cookie身份验证
是一种常用的身份验证机制,在该机制下,当用户成功登录后,服务器会生成一个Cookie并将其存储在用户的浏览器中。这个Cookie中通常包含了用户的身份信息,作为用户后续请求时的凭证。每当用户发送请求时,浏览器会将该Cookie附加到请求中,从而让服务器能够识别用户身份。
实现Cookie身份验证的步骤
1. 配置服务
首先,我们需要在Startup.cs
文件中配置身份验证服务。在ConfigureServices
方法中添加以下代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login"; // 未登录时的重定向路径
options.LogoutPath = "/Account/Logout"; // 注销后的重定向路径
options.AccessDeniedPath = "/Account/AccessDenied"; // 权限访问被拒绝后的路径
});
// 其他服务配置...
services.AddControllers_withViews();
}
在上面的代码中,我们通过AddAuthentication
方法添加了Cookie身份验证,并指定了一些基本的配置,如用户未登录时的重定向路径。
2. 创建登录控制器
接下来,我们需要创建一个控制器来处理用户的登录请求。以下是一个简单的AccountController
示例:
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Threading.Tasks;
public class AccountController : Controller
{
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Login(string username, string password)
{
// 此处应添加验证逻辑,比如查询数据库验证用户的用户名和密码
if (username == "admin" && password == "password") // 示例验证
{
var claims = new[]
{
new Claim(ClaimTypes.Name, username)
// 可以添加其他声称
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
IsPersistent = true // 用户注销后是否保持登录状态
};
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity), authProperties);
return RedirectToAction("Index", "Home"); // 登录成功后重定向
}
ModelState.AddModelError("", "Invalid login attempt.");
return View();
}
[HttpPost]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Index", "Home"); // 注销后重定向
}
}
在上面的Login
方法中,我们首先验证用户的凭证。如果验证成功,则创建一个ClaimsIdentity
,并使用HttpContext.SignInAsync
方法将其添加到用户的Cookie中。
3. 创建登录视图
接下来,我们需要创建一个登录页面。可以在Views/Account/Login.cshtml
中创建一个简单的表单:
@model YourNamespace.Models.LoginViewModel
<form asp-action="Login" method="post">
<div>
<label asp-for="Username"></label>
<input asp-for="Username" />
</div>
<div>
<label asp-for="Password"></label>
<input asp-for="Password" type="password" />
</div>
<button type="submit">登录</button>
</form>
4. 使用 [Authorize]
特性进行保护
通过在需要保护的控制器或方法上添加 [Authorize]
特性,我们可以确保这些资源只有经过身份验证的用户才能访问。例如:
[Authorize]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
如果用户未登录,则会自动重定向到登录页面。
小结
到此为止,我们已经走过了实现Cookie身份验证
的基础步骤。用户通过登录页面提交凭证,服务器验证登录信息并创建Cookie,后续请求中Cookie将被用于身份验证。这种机制为我们的应用提供了一种安全的用户状态管理方式。
在下一篇中,我们将继续深入探讨基于角色的授权
,学习如何通过角色来控制用户的访问权限,敬请期待!