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.
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.
public void ConfigureServices(IServiceCollection services)
{
}
Configure
method is used to configure the request handling pipeline using middleware.
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
.
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:
{
"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 DbSet
s 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.
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:
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.
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:
Install-package Microsoft.EntityFrameworkCore.Tools
Make sure the .csproj file looks like this:
<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:
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.