Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 allows easy access IdentityUser properties relational to the User.Identity object but I am not sure how to go about it. I want to create several custom extensions similar to User.Identity.GetUserName(), User.Identity.GetUserById(), etc... instead of using this ViewContextExtension method. My Authentication type is currently the default type DefaultAuthenticationTypes.ApplicationCookie from VS2013 MVC5 template. As Shoe stated, I need this claim to be inserted after the user signs in.

My questions is:

How and where do you create a custom claim that has an out parameter of this IIdentity under IPrincipal?

This would allow me to access User properties via CookieAuthentication in a View for entities in a DDD setting where I have multiple DbContexts in a single app using Identity 2.0. I will eventually use WebAPI, but for now I want to keep it as simple as possible. I have found this SO Q&A but it is geared towards Web Forms using Tickets. Not sure the difference between tickets and tokens either?

This is the current approach that uses ViewContext from a base controller:

View:

    @using Microsoft.AspNet.Identity
    @using Globals.Helpers
    @using Identity //custom Identity for Domain
    @using Microsoft.AspNet.Identity.Owin
    
    @if (Request.IsAuthenticated)
    {
          var url = @ViewContext.BaseController().GetAvatarUrlById(User.Identity.GetUserId<int>());
  
        //...
    }

BaseController.cs

        public string GetAvatarUrlById(int id)
        {

            var user = UserManager.FindById(id);

            return "../../" + user.ImageUrl;
        }

Extensions.cs

    public static class ViewContextExtension
    {
        public static BaseController BaseController(this ViewContext view)
        {
            var baseController = (BaseController)view.Controller;
            return baseController;
        }
    }

What I am looking for is but where & how?

View:

<img src="@User.Identity.GetAvatarUrl()" alt="User.Identity.GetAvatarUrl()" />

SOLUTION

I simply edited the Extension.cs file and used inheritance for the Base controller which is used for the _LoginPartial.cshtml & edited the ViewContextExtension class:

    #region ViewContextExt
    public static class ViewContextExtension
    {
        public static BaseController BaseController(this ViewContext view)
        {
            var baseController = (BaseController)view.Controller;
            return baseController;
        }

        public static string GetAvatarUrl(this IIdentity identity)
        {
            return ((ClaimsIdentity)identity).Claims.First(c => c.Type == "AvatarUrl").Value;
        }
    }
}
# endregion
like image 739
yardpenalty.com Avatar asked Dec 29 '14 03:12

yardpenalty.com


People also ask

What is the use of ClaimsIdentity?

A claim is represented by the Claim class. The claims contained in a ClaimsIdentity describe the entity that the corresponding identity represents, and can be used to make authorization and authentication decisions.

What is ClaimsIdentity in ASP.NET Core?

In . NET Core, the ClaimsIdentity class represents a user in your application. It helps describe who they are and helps manage the list of claims which describe what they can do.


1 Answers

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()" />
like image 69
James Sampica Avatar answered Oct 21 '22 19:10

James Sampica