How to Add another Propertys to User.Identity From table AspNetUsers in identity 2.2.1

心已入冬 提交于 2019-12-04 06:41:13

You have 2 option (at least). First, set your additional property as a claim when user logs in then read the property from the claim each time you need. Second, each time you need the property read it from the storage (DB). While I recommend the claim based approach, which is faster, I will show you both way by using extension methods.

First Approach:

Put your own claim in the GenerateUserIdentityAsync method like this:

public class ApplicationUser : IdentityUser
{
    // some code here

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        userIdentity.AddClaim(new Claim("ProfilePicture", this.ProfilePicture));
        return userIdentity;
    }
}

Then write a extension method to easily read the claim like this:

public static class IdentityHelper
{
    public static string GetProfilePicture(this IIdentity identity)
    {
        var claimIdent = identity as ClaimsIdentity;
        return claimIdent != null
            && claimIdent.HasClaim(c => c.Type == "ProfilePicture")
            ? claimIdent.FindFirst("ProfilePicture").Value
            : string.Empty;
    }
}

Now you could easily use your extension method like this:

var pic = User.Identity.GetProfilePicture();

Second Approach:

If you prefer fresh data instead of cashed one in the claim, you could write another extension method to get the property from user manager:

public static class IdentityHelper
{
    public static string GetFreshProfilePicture(this IIdentity identity)
    {
        var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
        return userManager.FindById(identity.GetUserId()).ProfilePicture;
    }
}

Now simply use like this:

var pic = User.Identity.GetFreshProfilePicture();

Also don't forget to add relevant namespaces:

using System.Security.Claims;
using System.Security.Principal;
using System.Web;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!