c# - 脚手架上的 MVC 防伪 token 错误

标签 c# asp.net-mvc asp.net-identity owin claims-based-identity

我收到以下错误:

{"A claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' or 'http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider' was not present on the provided ClaimsIdentity. To enable anti-forgery token support with claims-based authentication, please verify that the configured claims provider is providing both of these claims on the ClaimsIdentity instances it generates. If the configured claims provider instead uses a different claim type as a unique identifier, it can be configured by setting the static property AntiForgeryConfig.UniqueClaimTypeIdentifier."}

我试过了Anti-forgery token issue (MVC 5)没有成功。

发生错误

@Html.AntiForgeryToken()

通用 Startup.cs

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        AuthConfig.ConfigureAuth(app);
    }
}

管理 Controller 登录方法

[HttpPost]
public ActionResult Login(Models.AdminUserLogin LoginModel)
{
    if (ModelState.IsValid)
    {
        if (isUserValid(LoginModel.EmailAddr, LoginModel.Password))
        {
            List<Claim> claims = new List<Claim>
            {
                new Claim(ClaimTypes.Email, LoginModel.EmailAddr),
               //some other claims
            };

            ClaimsIdentity identity = new ClaimsIdentity(claims, AuthConfig.DefaultAuthType);
            IAuthenticationManager authManager = Request.GetOwinContext().Authentication;
            authManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);

            return RedirectToAction("Manage");
        }
        else
        {
            ModelState.AddModelError("", "Username and/or password incorrect");
        }
    }
    return View(LoginModel);
}

任何想法将不胜感激。

最佳答案

您需要在 ClaimsIdentity 中同时声明这两个声明才能防伪造 token :

List<Claim> claims = new List<Claim>
{
    // adding following 2 claim just for supporting default antiforgery provider
    new Claim(ClaimTypes.NameIdentifier, LoginModel.EmailAddr),
    new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),

    // your other claimes
    new Claim(ClaimTypes.Email, LoginModel.EmailAddr),
    //some other claims
};

关于c# - 脚手架上的 MVC 防伪 token 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32110852/

相关文章:

c# - 在浏览器关闭中杀死 session 值

c# - 已发布的控制台应用程序上没有 .NET Core 2.0 应用程序设置

javascript - 如何使用 Ajax 将参数传递给模态表单

asp.net-mvc - 如何使用 FluentValidation 在客户端验证日期?

c# - 将图像从 Controller 传递到 View

c# - mvc 5 检查用户角色

c# - 在 TPL 中返回一个空的静态任务是一种不好的做法吗?

c# - Required 属性是否适用于传递给 Asp.Net mvc 中的 Actionresult 时从模型中排除的属性

c# - 如何扩展 Microsoft.AspNet.Identity.IUser<TKey>

c# - IdentityServer3 的 ASP.NET 身份插件 UI (IdentityManager) 在部署到 Azure (WebApp) 后不起作用