在ASP.NET Core 2.1中,可以使用CookieAuthentication
中间件来实现Cookie持久化。以下是一个示例代码:
Startup.cs
文件的ConfigureServices
方法中添加Cookie认证服务:services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "YourCookieName";
options.Cookie.Expiration = TimeSpan.FromDays(30); // 设置Cookie过期时间
options.Cookie.SameSite = SameSiteMode.None; // 设置SameSite属性
options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // 设置Cookie只通过HTTPS传输
options.LoginPath = "/Account/Login"; // 设置登录页面路径
options.LogoutPath = "/Account/Logout"; // 设置注销页面路径
});
Configure
方法中启用认证中间件:app.UseAuthentication();
[Authorize]
特性来限制访问:[Authorize]
public IActionResult MyProtectedAction()
{
// 只有经过认证的用户才能访问这个Action
return View();
}
SignInAsync
方法来创建并写入Cookie:[HttpPost]
public async Task Login(LoginModel model)
{
// 验证用户登录信息
if (ModelState.IsValid)
{
var claims = new List
{
new Claim(ClaimTypes.Name, model.Username),
// 添加其他需要的用户信息
};
var claimsIdentity = new ClaimsIdentity(claims, "Login");
var authProperties = new AuthenticationProperties
{
IsPersistent = true // 设置为true表示记住用户登录状态,下次访问时自动认证
};
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
return RedirectToAction("Index", "Home");
}
return View(model);
}
SignOutAsync
方法来清除Cookie:public async Task Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Index", "Home");
}
这样,用户在登录后,服务器会生成一个持久化的Cookie,下次访问时会自动认证。