ASP .NET 中的角色身份验证以 HTTP400 响应结束
Roles auth in ASP .NET ends up with a HTTP400 response
我尝试在 ASP .NET Core 中进行简单的角色身份验证。制作方法如下:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginModel model)
{
if (ModelState.IsValid)
{
User user = await _db.Users.Include(u => u.Role).FirstOrDefaultAsync(u => u.Code == model.Code && u.Password == model.Password);
if (user != null)
{
await Authenticate(user);
return RedirectToAction("Cabinet", "Cabinet");
}
ModelState.AddModelError("", "Incorrect login or password");
}
return View(model);
}
private async Task Authenticate(User user)
{
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, user.Code),
new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role?.Name)
};
ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(id));
}
当我在 CabinetController
:
中有这样的方法时,它工作得很好
[Authorize(Roles = "admin,user")]
[HttpGet]
public async Task<IActionResult> Cabinet()
{
//some actions here
}
但是当我添加 [ValidateAntiForgeryToken]
时,我的方法如下所示:
[Authorize(Roles = "admin,user")]
[ValidateAntiForgeryToken]
[HttpGet]
public async Task<IActionResult> Cabinet()
{
//some actions here
}
身份验证成功后,我得到 HTTP 400。我认为 RedirectToAction("Cabinet", "Cabinet");
会抛出错误 400。我说得对吗?如果我是,为什么它会这样?
错误很明显。
在方法上添加ValidateAntiForgeryToken
时,需要将防伪令牌与请求一起发送。
我尝试在 ASP .NET Core 中进行简单的角色身份验证。制作方法如下:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginModel model)
{
if (ModelState.IsValid)
{
User user = await _db.Users.Include(u => u.Role).FirstOrDefaultAsync(u => u.Code == model.Code && u.Password == model.Password);
if (user != null)
{
await Authenticate(user);
return RedirectToAction("Cabinet", "Cabinet");
}
ModelState.AddModelError("", "Incorrect login or password");
}
return View(model);
}
private async Task Authenticate(User user)
{
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, user.Code),
new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role?.Name)
};
ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(id));
}
当我在 CabinetController
:
[Authorize(Roles = "admin,user")]
[HttpGet]
public async Task<IActionResult> Cabinet()
{
//some actions here
}
但是当我添加 [ValidateAntiForgeryToken]
时,我的方法如下所示:
[Authorize(Roles = "admin,user")]
[ValidateAntiForgeryToken]
[HttpGet]
public async Task<IActionResult> Cabinet()
{
//some actions here
}
身份验证成功后,我得到 HTTP 400。我认为 RedirectToAction("Cabinet", "Cabinet");
会抛出错误 400。我说得对吗?如果我是,为什么它会这样?
错误很明显。
在方法上添加ValidateAntiForgeryToken
时,需要将防伪令牌与请求一起发送。