在ASP.NET Core中,用戶身份驗證和授權可以通過Authentication和Authorization中間件來實現。以下是實現用戶身份驗證和授權的步驟:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
});
app.UseAuthentication();
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
});
[Authorize(Policy = "RequireAdminRole")]
public IActionResult AdminAction()
{
// Only users with Admin role can access this action
}
通過以上步驟,您就可以在ASP.NET Core中實現用戶身份驗證和授權功能。您可以根據具體需求來定制身份驗證和授權的邏輯,以確保應用程序的安全性和穩定性。