Click here to Skip to main content
15,887,676 members
Articles / Web Development / ASP.NET / ASP.NET Core

ASP.NET Core Identity: Setting Up a Web Project and the Identity Database

Rate me:
Please Sign up or sign in to vote.
3.26/5 (9 votes)
5 Dec 2017CPOL4 min read 31.2K   12   7
Setting up the project and database

Introduction

In the previous articles, I tried to explain how ASP.NET Core Identity works. In this step, we will create the project and database to use ASP.NET Core Identity. We will start with an empty project and step by step build features on that project.

Setting Up a Web Project and the Identity Database

The code for this article is available in the Demo 1 folder in this repo - https://github.com/ra1han/aspnet-core-identity.

Creating the Project

This article is based on ASP.NET Core 2.0 and Visual Studio 15.4.3. Previous versions of Visual Studio may not have proper project templates, so make sure you have the right version of Visual Studio.

In Visual Studio, let's create an ASP.NET Core 2.0 web project using the Empty project template. We want to start from scratch as we want to understand exactly how ASP.NET Core Identity works.

Image 1

The empty project doesn't have much content. The key things to know about it are:

  • Program.cs - Code in this file basically defines the web server and the startup class.
  • Startup.cs - We define the request handling pipeline and configure the services in this class.

ConfigureServices method is used to configure different services like Entity Framework, Identity, etc. that are used in the application.

C#
public void ConfigureServices(IServiceCollection services)
{
}

Configure method is used to configure the request handling pipeline using middleware.

C#
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Hello World!");
    });
}

As we progress through the article, we will be making changes to both of these methods.

Another interesting thing about ASP.NET Core 2.0 is that it has a .csproj file instead of a project.json file. You can go to the .csproj file by right clicking on the Project node on Solution Explorer and selecting Edit (ProjectName).csproj.

If we open the .csproj file, we will find that Microsoft.AspNetCore.All metapackage is referenced here. All nuget packages required for ASP.NET Core 2.x and Entity Framework Core 2.x are included in the Microsoft.AspNetCore.All package.

Preparing the Models

Microsoft.AspNetCore.Identity namespace defines the following models for user management:

  • IdentityUser
  • IdentityRole
  • IdentityUserRole
  • IdentityUserClaim
  • IdentityUserLogin
  • IdentityUserToken
  • IdentityRoleClaim

We can use these classes directly in our application (in most cases, we will). But we can also define our own class and inherit from them. Let's extend IdentityUser class and add First Name and Last Name to this model.

To do this, let's add a Models folder to the solution. Add a class named ApplicationUser which inherits from IdentityUser.

C#
public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Preparing Entity Framework

Before starting the next step, we will add an appsettings.json file to the solution. By default, it should add a connection string which looks like this:

XML
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;
    Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

Let's change the database name from "_CHANGE_ME" to "IdentityDemo" or something more meaningful.

Preparing Entity Framework

ASP.NET Core Identity comes with Entity Framework Core Identity package, which has an EF core implementation for storing the user information in the SQL Server database.

The Microsoft.AspNetCore.Identity.EntityFrameworkCore namespace implements the IdentityDbContext<TUser> which inherits from DbContext. This class provides the ready DbSets for all the identity models.

So, we can create our ApplicationDbContext which inherit from the IdentityDbContext<ApplicationUser>.

Let's add a folder named Data to the solution and add ApplicationDbContext class to this folder.

C#
public class ApplicationDbContext : IdentityDbContext<applicationuser>
{
	public ApplicationDbContext(DbContextOptions<applicationdbcontext> options)
	: base(options)
	{
	}

	protected override void OnModelCreating(ModelBuilder builder)
	{
		base.OnModelCreating(builder);
	}
}

Preparing Service and Middleware

In the previous step, it looks like we didn't use any connection string in ApplicationDbContext class. Rather, we injected DbContextOptions using Dependency Injection. Remember we have to configure this in the ConfigureServices method of Startup class.

Another important thing that we have to do is Configure the services related to ASP.NET Core Identity for the dependency injection. The final ConfigureServices method will look like this:

C#
public void ConfigureServices(IServiceCollection services)
{
	services.AddDbContext<applicationdbcontext>(options =>
			 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

	services.AddIdentity<applicationuser, identityrole="">()
										  .AddEntityFrameworkStores<applicationdbcontext>()
										  .AddDefaultTokenProviders();
}

Finally, we have to add identity to request pipeline. To do this, we have to add the following line at the end of the Configure method.

C#
app.UseAuthentication();

This line adds authentication middleware to the request pipeline.

Preparing Migration and Database

To create database using EF Core, we need migrations. To do that, install the following package:

C#
Install-package Microsoft.EntityFrameworkCore.Tools

Make sure the .csproj file looks like this:

XML
<ItemGroup>
  <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />
  <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
  <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
  <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.1" />
</ItemGroup>

Now to create a migration named "initial", run the following command in cmd in the folder where .csproj file is sitting.

dotnet ef migrations add Initial

Now, run the following command to create the database:

dotnet ef database update

Now if you open the database, you will see that the database is created according to the name mentioned in the connection string. The database will look like this:

Image 2

So now, we have configured Identity from scratch in an empty project and also created the database. In the next article, we will see how to use this in an MVC project.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionGood article Pin
ovisariesdk23-Dec-17 22:01
ovisariesdk23-Dec-17 22:01 
QuestionGreat Article Pin
Vinod T Abraham16-Dec-17 1:54
Vinod T Abraham16-Dec-17 1:54 
AnswerRe: Great Article Pin
Raihan Alam16-Dec-17 3:12
professionalRaihan Alam16-Dec-17 3:12 
Bug[My vote of 2] Thanks for the article but... Pin
Payrok5-Dec-17 18:13
Payrok5-Dec-17 18:13 
GeneralRe: [My vote of 2] Thanks for the article but... Pin
Raihan Alam6-Dec-17 1:01
professionalRaihan Alam6-Dec-17 1:01 
GeneralGood article, but Pin
Vitaliy Markitanov25-Nov-17 15:30
Vitaliy Markitanov25-Nov-17 15:30 
GeneralRe: Good article, but Pin
Raihan Alam26-Nov-17 1:09
professionalRaihan Alam26-Nov-17 1:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.