ASP.NET vNext Identity: Part 8 – Accessing the Identity

Over the last week I’ve discussed how to get the identity stuff going with a breakdown of what the Starter Project does. I’ve then refactored it into Areas and added logging to the mix. How about extending the Identity? My users have a real name, not an email address, for instance. The purpose of this post is:

  1. Extend my IdentityUser with a new field
  2. Display that field in my Layout

Let’s start with the model. I already have subclassed the IdentityUser model when I was creating the ApplicationDbContext. Extending the model with another field means adding a property to that class. I now have the following in the ApplicationUser class:

    public class ApplicationUser : IdentityUser
        public string DisplayName { get; set; }

I also need to set a value for the field in my admin user when the database is created. This is done in IdentityDbOptions.cs:

            // if the user does not exist, create it.
            logger.Trace(String.Format("CreateAdminUser: Ensuring User {0} exists", options.DefaultAdminUserName));
            var user = await userManager.FindByNameAsync(options.DefaultAdminUserName);
            if (user == null)
                logger.Trace("CreateAdminUser: User does not exist - creating");
                user = new ApplicationUser { UserName = options.DefaultAdminUserName, DisplayName = "Administrator" };
                var userCreationResult = await userManager.CreateAsync(user, options.DefaultAdminPassword);

I can just delete the existing database since I am just using a test database right now. I’d need to look at Entity Framework Migrations if I were doing this to a production application. Migrations allow you to make changes to the structure of your models and then have the back end database updated to reflect the new model.

Now that I have a new field in the model, I want to use it in my layout. Specifically, I want to add a greeting that shows the display name. The method I am using for this is called Transient Service Injection. Step 1 is to create a service injection class. This is just a regular old class whose constructor takes the service provider. In this case I’m creating a UserProfile service:

using System;
using System.Threading.Tasks;
using AspNetIdentity.Models;
using Microsoft.AspNet.Identity;
using Microsoft.Framework.DependencyInjection;

namespace AspNetIdentity.Services
    public class UserProfile
        public UserProfile(IServiceProvider services)
            UserManager = services.GetRequiredService<UserManager<ApplicationUser>>();

        public UserManager<ApplicationUser> UserManager { get; set; }

        public async Task<string> DisplayName(string username)
            ApplicationUser result = await UserManager.FindByNameAsync(username);
            return result.DisplayName;

I use the constructor to obtain a reference to my UserManager. Then, when requested, I asynchronously find the given user by name and return the display name. Next step is to inject this service into the ASP.NET services list. The services list is set up in the ConfigureServices method of Startup.cs:

        public void ConfigureServices(IServiceCollection services)
            // Entity Framework Service backed by SQL Server
                .AddDbContext<ApplicationDbContext>(options =>

            // Configure the identity service based on our configuration
            services.Configure<IdentityDbContextOptions>(options =>
                options.DefaultAdminUserName = Configuration.Get("AdminUser:Username");
                options.DefaultAdminPassword = Configuration.Get("AdminUser:Password");

            // Now add the entity framework backed identity service
            services.AddIdentity<ApplicationUser, IdentityRole>()

            // Configure the Email Service

            // ASP.NET MVC6 Service

            // Add a Transient Service

The addition is the last line of the method. I can now inject that service into any Razor view I care to. For example, my MainSite.cshtml file is my layout page for the site. Maybe I want to include the Display Name in the header:

@inject AspNetIdentity.Services.UserProfile UserProfile
<!DOCTYPE html>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="~/Style/StyleSheet.css">

    <!-- Polyfills -->
    <script src="~/lib/webcomponentsjs/webcomponents.min.js"></script>
    <div class="container">
        <div class="navbar-header">
            <ul class="nav navbar-nav">
                <li>Welcome @await UserProfile.DisplayName(User.Identity.Name)</li>
                <li>@Html.ActionLink("Log Out", "Logout", "Login", new { area = "Account" })</li>
    <section id="body">
    <section id="scripts">
        <script src="~/lib/requirejs/require.js" data-main="Scripts/application"></script>

There are two changes here. Firstly, The @inject statement at the top injects the UserProfile into the page so I can use it. Secondly, I use it like this:

@await UserProfile.DisplayName(User.Identity.Name)

The @await means the method is called asynchronously – this matches the definition of the method I am calling. I also pass in the current username which is available in the User.Identity object.

There is still work to be done. I need to add a profile page so that a user can edit the display name, for example, or update the registration page to ask for the name up front. In addition, I need to handle the case where the user does not enter a display name.

For now, my current code is on my GitHub Repository.