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

后端 未结 2 1233
我在风中等你
我在风中等你 2020-12-09 22:57

See this similar question: Need access more user properties in User.Identity

I would like to create custom authentication methods to use with my Razor Views that allo

2条回答
  •  执念已碎
    2020-12-09 23:25

    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
    
    
    

提交回复
热议问题