在 ASP.NET Core 3.1 中,可以使用 Cookie 认证来实现用户登录认证。如果需要在认证循环中跳转到登录页面,可以按照以下步骤进行操作。
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
});
这里使用了默认的 Cookie 认证方案,并配置了登录路径为 "/Account/Login",访问被拒绝路径为 "/Account/AccessDenied"。
[HttpPost]
public async Task Login(string username, string password)
{
// 执行用户认证逻辑,验证用户名和密码
if (isValidUser) // 如果用户认证成功
{
var claims = new List
{
new Claim(ClaimTypes.Name, username)
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return RedirectToAction("Index", "Home");
}
else // 如果用户认证失败
{
return View();
}
}
在登录请求中,首先验证用户名和密码是否正确。如果认证成功,创建用户的身份认证信息,并使用 HttpContext.SignInAsync 方法将用户信息写入到 Cookie 中。然后跳转到首页。
app.UseAuthentication();
app.UseAuthorization();
这里使用了 UseAuthentication 和 UseAuthorization 方法来启用认证授权中间件。
通过以上步骤配置之后,如果用户访问需要认证的页面,会自动跳转到登录页面。用户登录成功后,会将认证信息写入到 Cookie 中,并跳转回原来请求的页面。