我在登录时使用了声明。但它告诉我这个错误
提供的ClaimsIdentity中没有
http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier
类型的声明。
如何解决这个问题?
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;
}
}
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);
}
更新
答案 0 :(得分:5)
ClaimTypes.NameIdentifier
中有Application_Start
但ClaimTypes.Name
Login
您需要更改其中一个,以便它们符合预期。
protected void Application_Start() {
//...other code omitted for brevity
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
}
您还应该确保不会重复声明,因为这会破坏您视图中的AntiForgeryToken
电话。
如此处MVC5 AntiForgeryToken Claims/“Sequence contains more than one element”
所述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);
}