ASP.NET, Entity Framework, Identity, Web API

ASP.NET Identity on an Entity Framework Solution with Repository Pattern (Including WebAPI)

I have written a new blog post about ASP.NET MVC5 and the Repository pattern; You should totally check the new post and ignore this one.

you are still here ? seriously check the new version !


today I had the chance to play a little with the new ASP.NET Identity and the OWIN paradigm. Let me tell you, it was really confusing (and to be honest, I still feel lost on so many things !), and I believe this is because I haven’t found a good reading about how to proceed. I know the baked solutions have all you need but still…

The scenario I will write about is really particular but you may be able to adapt it to other types of architectures. Let me describe the scenario:

I’m building a web application using the repository pattern and I have a few layers between the UI (MVC 5 using both normal and web api controllers) and the domain objects (a class library using EF and other technologies). I will enumerate the layers from bottom to top:

  • Domain (where the context lives)
  • Data Service
  • Business Logic
  • Web/Web API

Step 1: preparing the context

The first thing I needed to do was to prepare the context object. A few things are required in order to have the new ASP.NET Identity users/roles working with your database. It’s very VERY VERY important that you download from nuget the next packages on your projects that will use the Identity entities (normally the data service and the repository if you are using unit of work for instancing the context). Those packages are:

  • Microsoft.ASP.NET Identity Core
  • Microsfot.ASP.NET Identity EntityFramework

You must have an account class that inherits from IdentityUser

public class User : IdentityUser
    public DateTime RegistrationDate { getset; } 
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(thisDefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;

I’ve added a new field just to give some flavor. The next step is to change your Context class to inherit from IdentityDbContext:

public class MyContext : IdentityDbContext<User>
    public static MyContext Create()
        return new MyContext();

On my code I use the unit of work pattern but adding the factory and the related code wont add anything to this article. What I want you to know if this works in more complex scenarios.

Step 2: Going up, creating (or modifying) your ApplicationUserManager

If you are not using the empty MVC5 project, you just need to chage the ApplicationUser definition to your correct domain entity (in this example User)

public class ApplicationUserManager : UserManager<User>
       public ApplicationUserManager(IUserStore<User> store)
           : base(store)
       public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
           var manager = new ApplicationUserManager(new UserStore<User>(context.Get<MyContext>()));
           // Configure validation logic for usernames
           manager.UserValidator = new UserValidator<User>(manager)
               AllowOnlyAlphanumericUserNames = false,
               RequireUniqueEmail = true
           // Configure validation logic for passwords
           manager.PasswordValidator = new PasswordValidator
               RequiredLength = 6,
               RequireNonLetterOrDigit = false,
               RequireDigit = false,
               RequireLowercase = false,
               RequireUppercase = false,
           // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
           // You can write your own provider and plug in here.
           manager.RegisterTwoFactorProvider("PhoneCode"new PhoneNumberTokenProvider<User>
               MessageFormat = "Your security code is: {0}"
           manager.RegisterTwoFactorProvider("EmailCode"new EmailTokenProvider<User>
               Subject = "Security Code",
               BodyFormat = "Your security code is: {0}"
           manager.EmailService = new EmailService();
           manager.SmsService = new SmsService();
           var dataProtectionProvider = options.DataProtectionProvider;
           if (dataProtectionProvider != null)
               manager.UserTokenProvider = new DataProtectorTokenProvider<User>(dataProtectionProvider.Create("ASP.NET Identity"));
           return manager;

Step 3: And what about WebAPI ?

I’m using a web service that needs to know if a user is valid, this means we need to access to the Identity core to see if the user is valid. First, you MUST download from nuget the Microsoft ASP.NET Web API 2.1 OWIN package WHICH IS NOT INCLUDED BY DEFAULT. Once you have done this, you will be able to access to the ApplicationUserManager:

using Microsoft.AspNet.Identity.Owin;
private ApplicationUserManager _userManager;
   public ApplicationUserManager UserManager
           return _userManager ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
       private set
           _userManager = value;

Step 4: what now ?

Now it’s up to you ! I recomend taking a look at the backed login/register functions but here you have an example on web api:

        [HttpPostpublic LoginResponseModel LogIn(LoginRequestModel login)
    LoginResponseModel response = new LoginResponseModel() { IsValid = false };
    if (string.IsNullOrEmpty(login.Username) || string.IsNullOrEmpty(login.Password))
        return response;
    var user = UserManager.FindByName(login.Username);
    if (user != null)
        response.IsValid = true;
    return response;

2 thoughts on “ASP.NET Identity on an Entity Framework Solution with Repository Pattern (Including WebAPI)”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s