Identity 2 is the new Windows authentication implementation. This simple example will show you how to extend Identity and collect additional information during registration. Identity 2 uses Entity Framwork and we will use code first to generate the database locally. Nothing elaborate here just simply adding a few new columns to the AspNetUsers table and accessing the data in our application using Identity object model.

Start by creating a new MVC project in Visual Studio 2013 using the default options. I named the project Identity2.

Now Open IdentityModel.cs and we will add to the ApplicationUser model. We add the model object to ApplicationUser and add claims for each object. Claims is what is used to make your values available for presentation.

public class ApplicationUser : IdentityUser
{
    public string FullName { getset; }
    public string Address { getset; }
    public string City { getset; }
    public string State { getset; }
    public string Zip { getset; }
 
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(thisDefaultAuthenticationTypes.ApplicationCookie);
 
        // Add custom user claims here
        userIdentity.AddClaim(new Claim("FullName", FullName.ToString()));
        userIdentity.AddClaim(new Claim("Address", Address.ToString()));
        userIdentity.AddClaim(new Claim("City", City.ToString()));
        userIdentity.AddClaim(new Claim("State", State.ToString()));
        userIdentity.AddClaim(new Claim("Zip", Zip.ToString()));
 
        return userIdentity;
    }
 
 
}

Now we need to create a class that defines the new model objects. First add using System.Security.Principal to IdentityModel.cs.

using System.Security.Principal;

This makes the interface IPrincipal available to our new class. IPrincipal provides the security context as get the values for the new objects we added to ApplicationUser. I called the class ExtendedIdentityExtensions and just added it to the IdentityModel.

public static class ExtendedIdentityExtensions
{
 
    public static string FullName(this IPrincipal user)
    {
        if (user.Identity.IsAuthenticated)
        {
            ClaimsIdentity claimsIdentity = user.Identity as ClaimsIdentity;
            foreach (var claim in claimsIdentity.Claims)
            {
                if (claim.Type == "FullName")
                    return claim.Value;
 
            }
            return "";
        }
        else
            return "";
    }
 
    public static string Address(this IPrincipal user)
    {
        if (user.Identity.IsAuthenticated)
        {
            ClaimsIdentity claimsIdentity = user.Identity as ClaimsIdentity;
            foreach (var claim in claimsIdentity.Claims)
            {
                if (claim.Type == "Address")
                    return claim.Value;
 
            }
            return "";
        }
        else
            return "";
    }
 
    public static string City(this IPrincipal user)
    {
        if (user.Identity.IsAuthenticated)
        {
            ClaimsIdentity claimsIdentity = user.Identity as ClaimsIdentity;
            foreach (var claim in claimsIdentity.Claims)
            {
                if (claim.Type == "City")
                    return claim.Value;
 
            }
            return "";
        }
        else
            return "";
    }
 
    public static string State(this IPrincipal user)
    {
        if (user.Identity.IsAuthenticated)
        {
            ClaimsIdentity claimsIdentity = user.Identity as ClaimsIdentity;
            foreach (var claim in claimsIdentity.Claims)
            {
                if (claim.Type == "State")
                    return claim.Value;
 
            }
            return "";
        }
        else
            return "";
    }
 
    public static string Zip(this IPrincipal user)
    {
        if (user.Identity.IsAuthenticated)
        {
            ClaimsIdentity claimsIdentity = user.Identity as ClaimsIdentity;
            foreach (var claim in claimsIdentity.Claims)
            {
                if (claim.Type == "Zip")
                    return claim.Value;
 
            }
            return "";
        }
        else
            return "";
    }
 
}

Our new calls holds all the methods used to return the values of ApplicationUser. These method can be used to return the extended values where ever the Identity model is being implemented . They may be used in a Html.ActionLink or anywhere else by using User.MethodName(). Let's replace the the ActionLink in _LoginPartial.cshtml that displays the login email address with the code below.  You will also need to add using statement to access the extended model.

@using Identity2.Models

 

@Html.ActionLink("Hello " + User.FullName()  + " !""Index""Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
@Html.ActionLink( User.Address() + "-" + User.City() + "-" + User.State() + "-" + User.Zip(),"Index""Manage")

In AccountViewModels.cs we need to update the RegisterViewModel to account for our new model objects.

public class RegisterViewModel
 {
        #region "Extended Info"
     [Required]
     [Display(Name = "Name")]
     public string Name { getset; }
 
     [Required]
     [Display(Name = "Address")]
     public string Address { getset; }
 
     [Required]
     [Display(Name = "City")]
     public string City { getset; }
 
     [Required]
     [Display(Name = "State")]
     public string State { getset; }
 
     [Required]
     [Display(Name = "Zip")]
     public string Zip { getset; }
        #endregion
 
     [Required]
     [EmailAddress]
     [Display(Name = "Email")]
     public string Email { getset; }
 
     [Required]
     [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
     [DataType(DataType.Password)]
     [Display(Name = "Password")]
     public string Password { getset; }
 
     [DataType(DataType.Password)]
     [Display(Name = "Confirm password")]
     [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
     public string ConfirmPassword { getset; }
 }

The AccountController needs updating by adding the model objects to the new ApplicationUser.

// POST: /Account/Register
 [HttpPost]
 [AllowAnonymous]
 [ValidateAntiForgeryToken]
 public async Task<ActionResult> Register(RegisterViewModel model)
 {
     if (ModelState.IsValid)
     {
         var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FullName = model.Name, Address = model.Address, City = model.City, State = model.State, Zip = model.Zip };
         var result = await UserManager.CreateAsync(user, model.Password);
         if (result.Succeeded)
         {
             await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
             
             // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
             // Send an email with this link
             // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
             // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
             // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
 
             return RedirectToAction("Index""Home");
         }
         AddErrors(result);
     }
 
     // If we got this far, something failed, redisplay form
     return View(model);
 }

Update Register.cshtml and add code to collect values for your new model objects.

@model Identity2.Models.RegisterViewModel
@{
    ViewBag.Title = "Register";
}
 
<h2>@ViewBag.Title.</h2>
 
@using (Html.BeginForm("Register""Account"FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary(""new { @class = "text-danger" })
 
    <div class="form-group">
        @Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
        </div>
    </div>
 
    <div class="form-group">
        @Html.LabelFor(m => m.Address, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Address, new { @class = "form-control" })
        </div>
    </div>
 
    <div class="form-group">
        @Html.LabelFor(m => m.City, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.City, new { @class = "form-control" })
        </div>
    </div>
 
    <div class="form-group">
        @Html.LabelFor(m => m.State, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.State, new { @class = "form-control" })
        </div>
    </div>
 
 
    <div class="form-group">
        @Html.LabelFor(m => m.Zip, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Zip, new { @class = "form-control" })
        </div>
    </div>
 
    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Register" />
        </div>
    </div>
}
 
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

 

Now run the project and register a new user. Visual Studio will Create the database for you in the App_Data folder. You can examine the AspNetUsers table and see it added your model objects. If you change your database connection for the DefaultConnection it will create the database there as well when using SQL server.

I wanted to return the users Full Name instead of email address which is the default value displayed in the base template for a MVC project. Hope this helps you quickly extend Identity 2 in your project. This just touches the subject but this is what I was looking for and didn't find in any other simple examples. 

Learn more about our process and have one of our solutions developed for you today!