提供的防伪令牌适用于与当前用户不同的基于声明的用户

Bus*_*ter 5 asp.net-core-mvc

我正在滚动我自己的身份验证系统,并且只使用我需要的位。我的解决方案基于此 github repo。我已经审查过类似的问题,但它们似乎不适合我的情况。我还阅读了这篇关于 Authentication 和 JWT 的文章,但我不确定这是否相关。我迷路了。

我的 Startup.cs:

app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme = "Cookies",
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            LoginPath = new PathString("/auth/login")
        });

        app.UseClaimsTransformation(context =>
        {
            if (context.Principal.Identity.IsAuthenticated)
            {
                context.Principal.Identities.First().AddClaim(new Claim("now", DateTime.Now.ToString()));
            }

            return Task.FromResult(context.Principal);
        });
Run Code Online (Sandbox Code Playgroud)

我的身份验证控制器按预期工作。这是我使用 [ValidateAntiForgeryToken] 的登录操作;然而,整个控制器被设置为[AllowAnonymous]:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginViewModel viewModel, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;

        if (ModelState.IsValid)
        {
            var result = await _userManager.LoginUserAsync(viewModel.UserName, viewModel.Password, viewModel.RememberMe);
            if (result.Success)
            {
                // TODO: Log successful login

                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, result.User.FullName),
                    new Claim(ClaimTypes.Email, result.User.Email)
                };

                foreach(var role in result.User.Roles)
                {
                    claims.Add(new Claim(ClaimTypes.Role, role.Name));
                }

                var identity = new ClaimsIdentity(claims, "password");
                var principal = new ClaimsPrincipal(identity);

                await HttpContext.Authentication.SignInAsync("Cookies", principal);

                return LocalRedirect(returnUrl);
            }
            else
            {
                AddModelErrors(result);
                return View(viewModel);
            }
        }

        // Doh!
        return View(viewModel);
    }
Run Code Online (Sandbox Code Playgroud)

到目前为止,一切都很好。

这是我收到错误的地方(400 错误请求)。在创建(发布)方法中:

[Authorize(Roles = "Admin")]
public class UserAdministrationController : Controller
{
    private readonly IUserManager _userManager;
    private readonly IUserAdminViewModelFactory _userAdminViewModelFactory;

    public UserAdministrationController(
        IUserManager userManager,
        IUserAdminViewModelFactory userAdminViewModelFactory
        )
    {
        _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager));
        _userAdminViewModelFactory = userAdminViewModelFactory ?? throw new ArgumentNullException(nameof(userAdminViewModelFactory));
    }


    [HttpGet]
    public IActionResult Index()
    {
        var userViewModels = _userAdminViewModelFactory.CreateUserViewModelList();
        return View(userViewModels);
    }

    [HttpGet]
    public IActionResult Create()
    {
        var createUserViewModel = _userAdminViewModelFactory.CreateUserViewModel();
        return View(createUserViewModel);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(CreateUserViewModel viewModel)
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

实际上,由于这个错误,该方法永远不会触发:

Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException:
提供的防伪令牌适用于与当前用户不同的基于声明的用户。在 Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery.ValidateTokens(HttpContext httpContext, AntiforgeryTokenSet antiforgeryTokenSet) 在 Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery.d__9.MoveNext()

如果删除 [ValidateAntiForgeryToken],我不会收到错误;但是,如果删除 [Authorize(Roles = "Admin")] 属性,我仍然收到错误。

我想我“搞砸了一些平凡的细节”之类的,但不确定在哪里。

小智 3

尝试在构建防伪令牌之前设置用户,因为防伪令牌是使用用户声明构建的。

...
await HttpContext.Authentication.SignInAsync("Cookies", principal);
HttpContext.User = principal;
...
Run Code Online (Sandbox Code Playgroud)