身份核心获取名称&其他领域

时间:2018-03-11 16:07:52

标签: asp.net-core .net-core asp.net-core-mvc asp.net-identity identity

我注意到使用Identity核心,我可以通过以下方式获取名称字段:

HttpContext.User.Identity.Name

我不明白如何设置此值以及如何向其中添加其他字段,例如MyCustomField或Address或Id。我一直在寻找开源https://github.com/aspnet/Identity但是,我似乎无法弄明白。理想情况下,我想在身份项目之外和我自己的内部。

有人可以向我解释一下这是如何工作的,以及我将如何添加更多字段?

编辑:

如果我想添加地址,我会写下面的代码:

public static class IdentityExtensions
{
     public static string GetAddress(this IIdentity identity)
     {
         return ((ClaimsIdentity) identity).FindFirst("Address").Value;
     }
 }

现在上面的代码允许我从声明中提取地址值,但我不明白的是如何将值保存在那里。

如果我使用EF,那么我会在GenerateUserIdentityAsync方法下执行此操作。但是,我不是,我正在使用短小精悍,所以我试图了解这是如何工作的。在什么时候我会从数据库中读取信息并将其添加到声明中(我知道这会在登录时发生,但代码中会发生这种情况,如何填写当前名称)?

1 个答案:

答案 0 :(得分:2)

我通过以下方式完成了这项工作:

1 - 在数据库中名为[staff_id]的[AspNetUsers]表中添加了一个新列。

2 - 创建了一个继承自IdentityUser

的ApplicationUser类
public class ApplicationUser : IdentityUser
{
 public ApplicationUser(){ }
 public int staff_id { get; set; }
}

3 - 创建了一个AppClaimsPrincipalFactory类,它继承了UserClaimsPrincipalFactory并覆盖了CreateAsync方法。

public class AppClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
{
    public AppClaimsPrincipalFactory(UserManager<ApplicationUser> userManager,
                                     RoleManager<IdentityRole> roleManager,
                                     IOptions<IdentityOptions> optionsAccessor
                                    ): base(userManager, roleManager, optionsAccessor){  }
    public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
    {
        var principal = await base.CreateAsync(user);

        ((ClaimsIdentity)principal.Identity).AddClaims(new[] {
            new Claim("staff_id",user.staff_id.ToString())
        });

        return principal;
    }
}

4 - 修改了Startup.cs ConfigureServices方法,添加代码以使用我的本地AppClaimsPrincipalFactory类在登录时自定义用户

//add Entity Framework 
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnectionString")));

//add Identity framework, specify which DbContext to use
services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<MyDbContext>()
                .AddDefaultTokenProviders();

//add local AppClaimsPrincipalFactory class to customize user
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, AppClaimsPrincipalFactory>();

5 - 最后我按如下方式访问声明,可能有更好的方法,但这是我访问经过身份验证的用户的staff_id的方式。

int iStaffId;
if(!Int32.TryParse(User.FindFirst("staff_id").Value, out iStaffId))
{
 //throw an error because the staff_id claim should be present in iStaffId
}

我发现有用的其他一些资源如下。祝好运。

How to extend ASP.NET Core Identity user

ASP.NET Core Identity 3.0 : Modifying the Identity Database

Configure the ASP.NET Core Identity primary key data type

相关问题