MVC脚手架中的MVC防伪令牌错误

4
我收到了以下错误:
{"在提供的ClaimsIdentity中未提供类型为 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' 或 'http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider' 的声明。要使用基于声明的身份验证启用防伪令牌支持,请验证已配置的声明提供程序是否在生成的ClaimsIdentity实例上提供了这两个声明。如果已配置的声明提供程序使用不同的声明类型作为唯一标识符,可以通过设置静态属性AntiForgeryConfig.UniqueClaimTypeIdentifier来进行配置。}
我尝试过Anti-forgery token issue (MVC 5),但没有成功。
错误发生在:
@Html.AntiForgeryToken()

通用的Startup.cs文件

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

管理员控制器登录方法

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

任何想法都非常受欢迎。

尝试移除 AuthConfig.ConfigureAuth(app); 然后看看会发生什么。 - Scott Selby
@ScottSelby 移除它会导致所有已授权的页面显示未经授权的错误。 - TobusBoulton
你能展示一下 "ConfigureAuth" 方法吗?我在 VS2013 中创建了一个新的基本项目,添加了标准的 OWIN ConfigureAuth,包括 "app.UseCookieAuthentication(...)" 并添加了你的帖子逻辑登录,一切都很好。我使用的包有:"Microsoft.Owin.Security"、"Microsoft.Owin" 和 "Microsoft.Owin.Security.Cookies"。 - Adrian Tarnowski
1个回答

4

为了让防伪令牌正常工作,你需要在你的ClaimsIdentity中包含这两个声明:

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

我已添加了这两个声明,但是我收到了以下错误信息。System.Web.Mvc.HttpAntiForgeryException: '提供的防伪标记是针对与当前用户不同的基于声明的用户的。' 如果我同时添加 DefaultNameClaimTypeAntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimsIdentity.DefaultNameClaimType;,也会发生这种情况。 - DevEng

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接