Asp.net Core Identity Framework Core, VS 2017

Nearly every application needs to manage users, roles, rights, authentications and authorizations. Asp.net Core works well with the default identity framework provided by .net team.

Let’s start with a blank Asp.core Project having Mvc configured.

  • Open nuget package console and install Entity Framework Core package as we will be using SQL Server database for Identity Framework.

    PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer

  • Now install the Asp.net Core identity packages using following commands

    PM> Install-Package Microsoft.AspNetCore.Identity
    PM> Install-Package Microsoft.AspNetCore.Identity.EntityFrameworkCore

  • In models folder create a new class that will hold the information related to your users. I call it “AppUser” class. AppUser should inherit the IdentiyUser class so that it can inherit the builtin features of Identity framework for a user. You can add your custom fields to AppUser as per your requirement.
    public class AppUser : IdentityUser
    {
        // no additional members are required right now
    }
    
  • In models folder create a new class for database context. You can name it according to your database name. In my case it would be VenueDbContext. Your context class should inherit one of the DbContexts from the framework. Since you are interested in Identity Framework, let’s inherit from IdentityDbContext.
    public partial class VenuesDbContext : IdentityDbContext<AppUser>
    {
        public VenuesDbContext(DbContextOptions<VenuesDbContext> options) :
            base(options)
        { }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
        }
    }
    

    Write a constructor to provide the context options using dependency injection. You will notice another override OnModelCreating in the sample code above. This method is called while creating a model, you can customize the model e.g., provide a different name of the table then the class name we are using in our context. If you provide this override make sure you are calling the base.OnModelCreating() at the beginning of your code, If you do not call the base method you will need to handle few properties of IdentityUser class for which the tables are to be created by yourself.
    Also note that we are using IdentityDbContext. This is the base class Entity Framework context used for the given IdentityUser.

  • Once the context is ready, we now need to register the context with Asp.net Core middlewares. Add a configuration property of type IConfigurationRoot in the Startup class.

    public IConfigurationRoot Configuration { get; set; }

    Also add a constructor to the Startup class in your asp.net core application.

    public Startup(IHostingEnvironment env) {
        Configuration = new ConfigurationBuilder()
           .SetBasePath(env.ContentRootPath)
           .AddJsonFile("appsettings.json")
           .AddEnvironmentVariables()
           .Build();
    }
    

    In the constructor we are building the configuration object using a Json file “appsettings.json”. This json file will contain the connection string and other related configurations in future. Add appsettings.json file from “Add File” menu option for the project. Contents of appsettings.json file are as follows.

    {
      "ConnectionStrings": {
        "MyConnection": "Server=.\\SQLExpress;Database=VenuesDb;Trusted_Connection=True;MultipleActiveResultSets=true"
      }
    }
    
  • You need to add the context with dependency injection in Startup class ConfigureServices() method.
  • First we need to add database to the services
    services.AddDbContext<VenuesDbContext>(options => {
        options.UseSqlServer(Configuration.GetConnectionString("MyConnection"));
    });
    
  • Now add the identity to the services right after adding dbcontext to the services.
    services.AddIdentity<AppUser, IdentityRole>()
            .AddEntityFrameworkStores<VenuesDbContext>()
            .AddDefaultTokenProviders();
    

    While adding identity we need to inform this identity will use VenueDbContext to store and retrieve information. You also need to provide the AppUser and IdentityRole classes that you will use to manage identities.

  • After registration or identity services now we can safely insturuct the middleware to use Identity. In the Configure() method of Startup class we build the request pipelines using middlewares. Right before adding Mvc, you need to add the Identity middleware.

    app.UseIdentity();

  • Identity framework is fully configured in the application. You can now use the identity related classes in your controllers e.g.,
    namespace VenueApp.Controllers
    {
        public class HomeController : Controller
        {
            private readonly UserManager<AppUser> _userManager;
            private readonly SignInManager<AppUser> _signInManager;
            public HomeController(UserManager<AppUser> userManager,
            SignInManager<AppUser> signInManager) {
                _userManager = userManager;
                _signInManager = signInManager;
            }
            public IActionResult Index()
            {
                ContentResult content = new ContentResult();
                content.Content = "Hello World!";
                return content;
            }
        }
    }
    
  • One last step is to create the database using Migrations i.e., open the nuget package console and run the following command

    Add-Migration create_database

  • When the migration is created, you will be able to see a new folder with migration and a snapshot file. Migration file contains all the table creation related code for asp.net Identity framework.
  • After adding a migration, update the database so that the newly created migration is applied on the database.

    PM> Update-Database

Database is created. Now run the application and use user managers and other identity framework features as per your need.

Configurations

Identity Framework can be configured with different settings for password and cookies to be used in the application. These configurations can be passed to the service in Startup class ConfigureServices() method.

services.Configure<IdentityOptions>(options =>
{
    // Password settings
    options.Password.RequireDigit = true;
    options.Password.RequiredLength = 8;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequireUppercase = true;
    options.Password.RequireLowercase = false;
}

Along with password you can also configure

  • Cookies options
  • Lockouts  options
  • User options
  • Token options
  • Claims options
  • Sign-In options
  • Security stamp related options

For more details
https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration

4 thoughts on “Asp.net Core Identity Framework Core, VS 2017

  1. What if
    1). I don’t want to use Code First approach of Entity Framework, but the DBFirst Approach?
    2). I don’t even want to use EntityFramework for this, as I am using ADO.Net?
    3). I don’t want to keep my Data Access code in the presentation layer i.e. MVC. How can I move them to Data Access Layer?
    4) What if I have my own table for user, role, and permission? Can I still use ASP.Net Core Identity?

    Liked by 1 person

  2. //Commenting again from my WordPress account in order to get the notifications. 🙂

    What if
    1). I don’t want to use Code First approach of Entity Framework, but the DBFirst Approach?
    2). I don’t even want to use EntityFramework for this, as I am using ADO.Net?
    3). I don’t want to keep my Data Access code in the presentation layer i.e. MVC. How can I move them to Data Access Layer?
    4) What if I have my own table for user, role, and permission? Can I still use ASP.Net Core Identity?

    Like

    1. Thank you Zeeshan for stopping by.
      1. You can use DB first approach, it’s not much different then the code first.
      https://viewbag.wordpress.com/2017/06/13/using-entity-framework-core-with-asp-net-core-vs-2017/
      You just need to use the Entity Framework package tool from NPM with the command scaffold-database “connection-string-to-your-db”. It will automatically create everything just like it did with edmx. We don’t have a viewer with core like edmx files but other then that everything is pretty much the same.

      2. You can avoid using EF or EF Core. If you have noticed identity framework registers an EFStore while adding Identity into the services.
      services.AddIdentity()
      .AddEntityFrameworkStores()
      .AddDefaultTokenProviders();
      You will need to create your own store by implementing IUserStore and then register this store with Identity.
      I haven’t tried that, but the idea is the same. Somebody already tried on the same lines.
      https://code.msdn.microsoft.com/Simple-Aspnet-Identiy-Core-7475a961/

      3. Nobody keep their data access code on presentation layer. It depends on the size of application. If smaller mostly people put DbSet classes in Models. You can keep them in separate DLLs. The important part is when do you register your DbContext with your application. As it has to be added in the dependency injection (IServiceProvider) it should be registered earlier at the start of application either in the startup or Application_start.

      4. It’s tricky, but yes even with your own tables you can use Identity. You will need to make changes to your database column names to match asp.net identity tables so that data insertion is made possible from Identity framework. Following video will help in understanding

      Hope this helps.

      Liked by 1 person

      1. Thanks Azmat for such great help, and sorry for acknowledging this so late. I will definitely look into this. Thanks again!

        Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.