我试图找到一个文档或示例,说明如何使用ASP.NET标识在MVC 5中向用户标识添加自定义声明.该示例应显示在OWIN安全管道中插入声明的位置以及如何使用表单身份验证将它们保存在cookie中.
假设您使用的是ASP.NET MVC 5项目模板,则添加声明的正确位置是ApplicationUser.cs
.只是搜索Add custom user claims here
.这将引导您进入该GenerateUserIdentityAsync
方法.这是在ASP.NET Identity系统检索到ApplicationUser对象并需要将其转换为ClaimsIdentity时调用的方法.你会看到这行代码:
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
之后是评论:
// Add custom user claims here
最后,它返回身份:
return userIdentity;
因此,如果您想添加自定义声明,您GenerateUserIdentityAsync
可能会看起来像:
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here userIdentity.AddClaim(new Claim("myCustomClaim", "value of claim")); return userIdentity;
也许以下文章可以提供帮助:
var claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.Name, "Brock")); claims.Add(new Claim(ClaimTypes.Email, "brockallen@gmail.com")); var id = new ClaimsIdentity(claims,DefaultAuthenticationTypes.ApplicationCookie); var ctx = Request.GetOwinContext(); var authenticationManager = ctx.Authentication; authenticationManager.SignIn(id);