在ASP .NET Core中,我们可以使用身份验证中间件来管理身份验证Cookie。以下是使用Forms身份验证Cookie的基本示例:
public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Account/Login"; options.AccessDeniedPath = "/Error/AccessDenied"; }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseAuthentication(); // ... }
public async Task
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError("", "Invalid email or password.");
return View(model);
}
[Authorize] public IActionResult Profile() { // ... }
通过这种方式,ASP .NET Core应用程序可以使用Forms身份验证Cookie来管理用户身份验证和访问控制。