Home > database >  Roles auth in ASP .NET ends up with a HTTP400 response
Roles auth in ASP .NET ends up with a HTTP400 response

Time:10-11

I've tried to make simple roles authentication in ASP .NET Core. Here's how it made:

    [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));
    }

And it works just fine when I have such a method in the CabinetController:

    [Authorize(Roles = "admin,user")]
    [HttpGet]
    public async Task<IActionResult> Cabinet()
    {
        //some actions here
    }

But when I add [ValidateAntiForgeryToken] and my method looks like this:

    [Authorize(Roles = "admin,user")]
    [ValidateAntiForgeryToken]
    [HttpGet]
    public async Task<IActionResult> Cabinet()
    {
        //some actions here
    }

After a successfull authentication I end up with HTTP 400. I think that RedirectToAction("Cabinet", "Cabinet"); throws error 400. Am I right? And if I am, why does it behave like this?

CodePudding user response:

The error is very clear.

You need to send the anti-forgery token with the request when you add ValidateAntiForgeryToken on a method.

  • Related