提供的ClaimsIdentity上没有类型为'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier'的声明

Kia*_*ush 1 c# asp.net-mvc claims-based-identity asp.net-identity-2

我在登录时使用Claim。但它告诉我这个错误

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier提供的ClaimsIdentity中没有类型的声明。

如何解决呢?

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        //AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Email;
        AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
    }
}
Run Code Online (Sandbox Code Playgroud)

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{

    if (!ModelState.IsValid)
    {
        return View(model);
    }

    var identity =new  ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, model.Email) }, DefaultAuthenticationTypes.ApplicationCookie,
        ClaimTypes.Name, ClaimTypes.Role);
    identity.AddClaim(new Claim(ClaimTypes.Name, model.Email));
    identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
    identity.AddClaim(new Claim(ClaimTypes.Sid, "123"));
    AuthenticationManager.SignIn(new AuthenticationProperties
    {
        IsPersistent = model.RememberMe
    }, identity);
    return RedirectToLocal(returnUrl);
}
Run Code Online (Sandbox Code Playgroud)

更新资料

在此处输入图片说明

Nko*_*osi 7

你有ClaimTypes.NameIdentifierApplication_Start,但用ClaimTypes.Name在你的Login

您需要更改一个或另一个,以便它们与预期的匹配。

protected void Application_Start() {
    //...other code omitted for brevity
    AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
}
Run Code Online (Sandbox Code Playgroud)

您还应该确保您没有重复索偿,因为这会打断AntiForgeryToken您视图中的通话。

如此处所述,MVC5 AntiForgeryToken声明/“序列包含多个元素”

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) {

    if (!ModelState.IsValid) {
        return View(model);
    }

    var identity = new  ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);
    identity.AddClaim(new Claim(ClaimTypes.Name, model.Email));
    identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
    identity.AddClaim(new Claim(ClaimTypes.Sid, "123"));
    AuthenticationManager.SignIn(new AuthenticationProperties {
        IsPersistent = model.RememberMe
    }, identity);
    return RedirectToLocal(returnUrl);
}
Run Code Online (Sandbox Code Playgroud)