我嘗試在 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。我說得對嗎?如果我是,它為什么會這樣?
uj5u.com熱心網友回復:
錯誤非常明顯。
添加ValidateAntiForgeryToken方法時,您需要隨請求發送防偽令牌。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/316240.html
上一篇:我正在嘗試使用postgresql創建檢查登錄程序,如果密碼已經存在,那么它應該回傳1else0。SQL查詢如下
