C# 防伪令牌发行(MVC 5)
我对防伪令牌有问题:( 我创建了自己的用户类,该类工作正常,但现在每当我转到/Account/Register页面时,我都会收到一个错误。错误是: 类型的索赔 '' 或 '' 提供的索赔实体上不存在。以启用防伪 令牌支持基于声明的身份验证,请验证 已配置的声明提供程序正在服务器上提供这两个声明 它生成的ClaimsIdentity实例。如果配置的声明 提供程序使用不同的声明类型作为唯一标识符, 可以通过设置static属性来配置它 AntiForgeryConfig.UniqueClaimTypeIdentifier 我发现这篇文章: 因此,我将我的应用程序\u Start方法更改为:C# 防伪令牌发行(MVC 5),c#,asp.net-mvc,authentication,claims-based-identity,C#,Asp.net Mvc,Authentication,Claims Based Identity,我对防伪令牌有问题:( 我创建了自己的用户类,该类工作正常,但现在每当我转到/Account/Register页面时,我都会收到一个错误。错误是: 类型的索赔 '' 或 '' 提供的索赔实体上不存在。以启用防伪 令牌支持基于声明的身份验证,请验证 已配置的声明提供程序正在服务器上提供这两个声明 它生成的ClaimsIdentity实例。如果配置的声明 提供程序使用不同的声明类型作为唯一标识符, 可以通过设置static属性来配置它 AntiForgeryConfig.UniqueClaimTyp
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Email;
}
但当我这么做的时候,我得到了这个错误:
类型的索赔
''
在所提供的索赔中不存在
以前有人遇到过这个问题吗?如果有,你知道怎么解决吗
提前欢呼,3倍 更新1 这是我的自定义用户类:
public class Profile : User, IProfile
{
public Profile()
: base()
{
this.LastLoginDate = DateTime.UtcNow;
this.DateCreated = DateTime.UtcNow;
}
public Profile(string userName)
: base(userName)
{
this.CreatedBy = this.Id;
this.LastLoginDate = DateTime.UtcNow;
this.DateCreated = DateTime.UtcNow;
this.IsApproved = true;
}
[NotMapped]
public HttpPostedFileBase File { get; set; }
[Required]
public string CompanyId { get; set; }
[Required]
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
public DateTime LastLoginDate { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredTitle")]
public string Title { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredFirstName")]
public string Forename { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredLastName")]
public string Surname { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredEmail")]
public string Email { get; set; }
public string JobTitle { get; set; }
public string Telephone { get; set; }
public string Mobile { get; set; }
public string Photo { get; set; }
public string LinkedIn { get; set; }
public string Twitter { get; set; }
public string Facebook { get; set; }
public string Google { get; set; }
public string Bio { get; set; }
public string CompanyName { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredCredentialId")]
public string CredentialId { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredSecurityCode")]
public bool IsLockedOut { get; set; }
public bool IsApproved { get; set; }
[Display(Name = "Can only edit own assets")]
public bool CanEditOwn { get; set; }
[Display(Name = "Can edit assets")]
public bool CanEdit { get; set; }
[Display(Name = "Can download assets")]
public bool CanDownload { get; set; }
[Display(Name = "Require approval to upload assets")]
public bool RequiresApproval { get; set; }
[Display(Name = "Can approve assets")]
public bool CanApprove { get; set; }
[Display(Name = "Can synchronise assets")]
public bool CanSync { get; set; }
public bool AgreedTerms { get; set; }
public bool Deleted { get; set; }
}
public class ProfileContext : IdentityStoreContext
{
public ProfileContext(DbContext db)
: base(db)
{
this.Users = new UserStore<Profile>(this.DbContext);
}
}
public class ProfileDbContext : IdentityDbContext<Profile, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
}
而User类是Microsoft.AspNet.Identity.EntityFramework.User类。
我的AccountController如下所示:
public interface IProfile
{
string Id { get; set; }
string CompanyId { get; set; }
string UserName { get; set; }
string Email { get; set; }
string CredentialId { get; set; }
}
[Authorize]
public class AccountController : Controller
{
public IdentityStoreManager IdentityStore { get; private set; }
public IdentityAuthenticationManager AuthenticationManager { get; private set; }
public AccountController()
{
this.IdentityStore = new IdentityStoreManager(new ProfileContext(new ProfileDbContext()));
this.AuthenticationManager = new IdentityAuthenticationManager(this.IdentityStore);
}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
try
{
// Create a profile, password, and link the local login before signing in the user
var companyId = Guid.NewGuid().ToString();
var user = new Profile(model.UserName)
{
CompanyId = companyId,
Title = model.Title,
Forename = model.Forename,
Surname = model.Surname,
Email = model.Email,
CompanyName = model.CompanyName,
CredentialId = model.CredentialId
};
if (await IdentityStore.CreateLocalUser(user, model.Password))
{
//Create our company
var company = new Skipstone.Web.Models.Company()
{
Id = companyId,
CreatedBy = user.Id,
ModifiedBy = user.Id,
Name = model.CompanyName
};
using (var service = new CompanyService())
{
service.Save(company);
}
await AuthenticationManager.SignIn(HttpContext, user.Id, isPersistent: false);
return RedirectToAction("Setup", new { id = companyId });
}
else
{
ModelState.AddModelError("", "Failed to register user name: " + model.UserName);
}
}
catch (IdentityException e)
{
ModelState.AddModelError("", e.Message);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/Setup
public ActionResult Setup(string id)
{
var userId = User.Identity.GetUserId();
using (var service = new CompanyService())
{
var company = service.Get(id);
var profile = new Profile()
{
Id = userId,
CompanyId = id
};
service.Setup(profile);
return View(company);
}
}
}
[授权]
公共类AccountController:控制器
{
public IdentityStoreManager IdentityStore{get;private set;}
公共标识AuthenticationManager AuthenticationManager{get;private set;}
公共账户控制员()
{
this.IdentityStore=newidentitystoremanager(newprofilecontext(newprofiledbcontext());
this.AuthenticationManager=新的IdentityAuthenticationManager(this.IdentityStore);
}
//
//获取:/Account/注册
[异名]
公众行动结果登记册()
{
返回视图();
}
//
//职位:/Account/Register
[HttpPost]
[异名]
公共异步任务寄存器(RegisterViewModel模型)
{
if(ModelState.IsValid)
{
尝试
{
//在登录用户之前,创建配置文件、密码和本地登录链接
var companyId=Guid.NewGuid().ToString();
var user=新配置文件(model.UserName)
{
CompanyId=CompanyId,
Title=model.Title,
Forename=model.Forename,
姓氏=模特。姓氏,
Email=model.Email,
CompanyName=model.CompanyName,
CredentialId=model.CredentialId
};
if(等待IdentityStore.CreateLocalUser(用户、模型、密码))
{
//创建我们的公司
var company=new Skipstone.Web.Models.company()
{
Id=公司Id,
CreatedBy=user.Id,
ModifiedBy=user.Id,
Name=model.CompanyName
};
使用(var service=new CompanyService())
{
服务.储蓄(公司);
}
等待AuthenticationManager.SignIn(HttpContext,user.Id,isPersistent:false);
返回RedirectToAction(“Setup”,new{id=companyId});
}
其他的
{
ModelState.AddModelError(“,”注册用户名失败:“+model.UserName”);
}
}
捕获(标识异常e)
{
AddModelError(“,e.Message”);
}
}
//如果我们走到这一步,有些东西失败了,重新显示形式
返回视图(模型);
}
//
//POST:/帐户/设置
公共操作结果设置(字符串id)
{
var userId=User.Identity.GetUserId();
使用(var service=new CompanyService())
{
var company=service.Get(id);
var profile=new profile()
{
Id=用户Id,
CompanyId=id
};
服务设置(配置文件);
返回视图(公司);
}
}
}
它以前用[ValidateAntiForgeryToken]属性修饰,但这就是它停止工作的地方
我希望这是足够的代码:)尝试设置(在global.cs中):
你知道你在索赔中得到了什么索赔吗?如果没有:
[ValidateAntiForgeryToken]
属性索赔
,并检查索赔AntiForgeryConfig.UniqueClaimTypeIdentifier
设置为该索赔类型[ValidateAntiForgeryToken]
属性请尝试在“匿名”窗口中打开链接,或从该域(即本地主机)中清除cookie。编辑:如果现在对这个问题有了更深入的了解,您可以忽略下面的答案 设置反ForgeryConfig.UniqueClaimTypeIdentifier=ClaimTypes.NameIdentifier代码>在Global.asax.cs的应用程序_Start()中为我修复了它。即使我有索赔
http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier
set,我得到了与原始问题相同的错误。但如上所述指出它不知何故是有效的
从MVC4开始,防伪令牌不使用
User.Identity.Name
作为唯一标识符。相反,它会查找错误消息中给出的两个声明
更新说明:不需要这样做
当用户登录时,您可以将丢失的索赔添加到您的索赔实体中,
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
string userId = TODO;
var identity = System.Web.HttpContext.Current.User.Identity as ClaimsIdentity;
identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", userId));
identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", userId));
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimsIdentity.DefaultNameClaimType;
using System.Web.Helpers;
using System.Security.Claims;
protected void Application_Start()
{
.......
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimsIdentity.DefaultNameClaimType;
}
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Email;