要解决Asp.Net Core未经授权登录的问题,你可以通过以下步骤进行操作:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login"; // 登录页面的路径
options.AccessDeniedPath = "/Account/AccessDenied"; // 未授权访问的路径
});
services.AddAuthorization();
app.UseAuthentication();
app.UseAuthorization();
[AllowAnonymous]
public class AccountController : Controller
{
public IActionResult Login()
{
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task Login(LoginViewModel model, string returnUrl = null)
{
// 验证用户登录信息
// 如果验证成功,使用以下代码进行身份验证:
var claims = new List
{
new Claim(ClaimTypes.Name, model.Username),
// 添加其他所需的声明
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
// 根据需要进行重定向
return RedirectToAction("Index", "Home");
}
public async Task Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
// 根据需要进行重定向
return RedirectToAction("Index", "Home");
}
public IActionResult AccessDenied()
{
return View();
}
}
@model LoginViewModel
这样,当用户访问需要授权的页面时,将会被重定向到登录页面。如果登录成功,用户将被重定向到原始请求的页面;如果登录失败,将会显示一个未授权页面。