ASP.NET Core 3.1默认身份验证的工作原理是基于Cookie的认证。当用户登录时,ASP.NET Core会生成一个身份验证Cookie,并将其发送给用户的浏览器。浏览器会在每次请求中自动发送该Cookie,以便服务器能够验证用户的身份。
以下是一个基本的示例,演示如何在ASP.NET Core 3.1中使用默认身份验证:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login"; // 登录页面的路径
options.AccessDeniedPath = "/Account/AccessDenied"; // 拒绝访问页面的路径
});
// ...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseAuthentication(); // 启用身份验证中间件
app.UseAuthorization(); // 启用授权中间件
// ...
}
[Authorize]
属性进行标记:[Authorize]
public class HomeController : Controller
{
// ...
}
public class AccountController : Controller
{
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
public async Task Login(LoginModel model)
{
// 验证用户凭据
if (IsValidUser(model.Username, model.Password))
{
var claims = new List
{
new Claim(ClaimTypes.Name, model.Username), // 用户名作为Claim
// 可以添加其他需要的Claim
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError(string.Empty, "Invalid username or password");
return View(model);
}
[HttpPost]
public async Task Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Login");
}
private bool IsValidUser(string username, string password)
{
// 验证用户凭据的逻辑
// 返回true表示用户凭据有效,否则无效
}
}
在上述代码中,登录操作方法验证用户凭据后,生成一个包含用户信息的ClaimsPrincipal对象,并使用HttpContext.SignInAsync
方法将其存储到Cookie中。注销操作方法使用HttpContext.SignOutAsync
方法清除Cookie并将用户重定向到登录页面。
请注意,上述示例是一个基本示例,实际应用中可能需要更复杂的身份验证逻辑和用户存储方式。