Identity 2.0: Creating custom ClaimsIdentity eg: User.Identity.GetUserById<int>(int id) for Per Request Validation

纵饮孤独 提交于 2019-11-28 09:29:47

The IIdentity object in MVC is going to be the issued token that corresponds to the identity of the user. This differs from whatever object or method you use on the back-end that represents the user (say a User class). If you want to use the user's identity to get a custom value then you need to put it into their claims object (ie the identity token) when they sign in (or at some other point in time).

You can add a claim at any time by giving the user an identity.

AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim("PhoneNumber", "123-456-7890"));
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);

When you have that claim inserted into their token you can retrieve it using an extension method like this...

public static string GetPhoneNumber(this IIdentity identity)
{
    return ((ClaimsIdentity)identity).FindFirstValue("PhoneNumber");
}

Razor

@using MyProject.Web.Extensions

<img src="@User.Identity.GetPhoneNumber()" />
yardpenalty

I actually found the solution using the answer to this SO question by LukeP but as Shoe notes, this is pre-MVC5 and we could simply put in a Claim instead.

I made the following alterations:

    interface IDomainPrincipal : IPrincipal
    {
        int Id { get; set; }
        string UserName { get; set; }
        string AvatarUrl { get; set; }
    }

    public class DomainPrincipal : IDomainPrincipal
    {
        public IIdentity Identity { get; private set; }
        public bool IsInRole(string role) { return false; }

        public DomainPrincipal(string email)
        {
            this.Identity = new GenericIdentity(email);
        }

        public int Id { get; set; }
        public string UserName { get; set; }
        public string AvatarUrl { get; set; }
    }

Then I used @User.Id, @User.UserName, @User.AvatarUrl in my @Razor Views respectively

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