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

时间:2017-03-27 16:10:26

标签: asp.net-core-mvc

我正在滚动自己的身份验证系统,只使用我需要的位。我的解决方案基于this github repo。我已经审核了类似的问题,但它们似乎不适合我的情况。我也读过this post about Authentication and JWT,但我不确定这是否相关。我输了。

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

我的Auth控制器按预期工作。这是我的登录操作,它使用[ValidateAntiForgeryToken];但是,整个Controller设置为[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);
    }

到目前为止,非常好。

我收到错误的地方(400 Bad Request)。在Create(Post)方法中:

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

实际上,该方法永远不会因此错误而触发:

  

Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException:the

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

如果删除[ValidateAntiForgeryToken],我就不会收到错误消息。但是,如果我删除[Authorize(Roles =&#34; Admin&#34;)]属性,我仍会收到错误。

我想我已经搞砸了一些平凡的细节&#34;什么的,但不知道在哪里。

1 个答案:

答案 0 :(得分:2)

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

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