Part - 2 ASP - Net Core Identity Setup
Part - 2 ASP - Net Core Identity Setup
So, create a new ASP.NET Core Application using the ASP.NET Core Web App (Model-View-Project)
template and provide the project name ASPNETCoreIdentityDemo. As we discuss everything from
scratch, select the Authentication type as None. With this, the project should be created with the
following structure.
So, open NuGet Package Manager for the solution and search
for Microsoft.AspNetCore.Identity.EntityFrameworkCore, and then install the package as shown in
the image below.
You need to install the following packages in the same way. While installing the packages, please
review the changes and accept the license.
Microsoft.AspNetCore.Identity.UI
Microsoft.EntityFrameworkCore.SqlServer (if using SQL Server)
Microsoft.EntityFrameworkCore.Tools (for migrations)
Once all the packages are installed, your package folder should look as shown below.
So, our application Context class needs to be inherited from the IdentityDbContext class
instead of the DbContext class. This is because IdentityDbContext provides all
the DbSet properties needed to manage the Identity Tables in SQL Server. We will see all the
tables the ASP.NET Core identity framework generates in just a bit.
So, create a class file named ApplicationDbContext.cs within the Models folder and then copy
and paste the following code. Our ApplicationDbContext class is inherited from the
IdentityDbContext, and if you go to the definition of IdentityDbContext, you will see it is inherited from
the DbContext class.
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace ASPNETCoreIdentityDemo.Models
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
}
The AddIdentity Method also allows us to specify various configuration options for the identity system,
such as password strength requirements, lockout settings, user validation rules, etc. As we progress
in this course, we will see all these options. So, please add the following code within the Program
class.
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
If you want to store additional information about the registered users, like their Gender, City,
First Name, Last Name, etc., we need to create a custom class that derives from the
IdentityUser class. Add the additional properties you need within the custom class and then
use that custom class instead of the built-in IdentityUser class while registering the Identity
service. We will discuss how to do this in our upcoming articles.
Similarly, IdentityRole is a built-in class provided by ASP.NET Core Identity that contains Role
information. Like the IdentityUser class, we can also customize the IdentityRole class.
We want to store and retrieve the User and Role information of the registered users using
EntityFrameWork Core from the underlying SQL Server database. We specify this
using AddEntityFrameworkStores<ApplicationDbContext>(), passing our application DbContext
class as the generic argument.
Alternatives: In addition to AddIdentity, we can also use AddIdentityCore, which adds only the
core parts of the Identity system. This provides a lighter option if you don’t need the full services like
user interface (UI) login functionality, which is used in the ASP.NET Core Web API Application.
var connectionString =
builder.Configuration.GetConnectionString("SQLServerIdentityConnection") ?? throw new
InvalidOperationException("Connection string 'SQLServerIdentityConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
In this code, AddDbContext<ApplicationDbContext> registers your DbContext with the DI
container. options.UseSqlServer(…) configures EF Core to use SQL Server with the connection string
defined in your appsettings.json file.
{
"ConnectionStrings": {
"SQLServerIdentityConnection": "Server=LAPTOP-6P5NK25R\\
SQLSERVER2022DEV;Database=IdentityCoreDB;Trusted_Connection=True;TrustServerCertifi
cate=True;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
using ASPNETCoreIdentityDemo.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System;
namespace ASPNETCoreIdentityDemo
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
//MVC Middleware
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
}
}
}
Now, if you verify the database, you should see the following tables in the
IdentityCoreDB database.
Differences Between AddIdentity and AddIdentityCore in ASP.NET Core
Identity
In ASP.NET Core Identity, AddIdentity and AddIdentityCore are two methods used to register the
identity services into the built-in dependency injection container, but they serve different purposes and
have different scopes of functionality. Let us understand the differences between them:
AddIdentity:
AddIdentity is used to add the full identity system to the application, including user and role
management and UI support.
It registers services like UserManager, RoleManager, SignInManager, and others essential for
handling user and role operations.
It is ideal for applications where a complete identity system with user interface components
for registration, login, etc., is required.
Typically, AddIdentity is used in ASP.NET Core MVC applications where views and controllers
are used.
AddIdentityCore:
This method is useful when you need the basic identity functionality without the additional
overhead of the full identity system.
AddIdentityCore registers only the core services of ASP.NET Core Identity, such as
UserManager and RoleManager.
It does not register services related to sign-in, cookies, or any UI components.
It’s ideal for API-based projects (like ASP.NET Core Web API) where we manage the
authentication flow (like token-based authentication) and do not require the built-in UI
and cookie-based authentication mechanisms.