How to Add ASP.NET Core Identity to Web API Project

Now a days, many applications use third party authentication services. There are various providers which can help you to authenticate and authorize the users. The providers include Microsoft, Facebook, Twitter, etc. In this article, we will see how ASP .NET Core identity can be added to a web API project.

Create .NET Core API

Crate a new .NET Core Web Application project in visual studio. In create project wizard, Visual Studio will ask you which type of web application you want. The options would be MVC, API, Angular, React, etc. Select API option and then click on Create button.

This should create a simple Web API and you can run the web API by hitting the run button on IIS Express.

If you are using Visual Studio 2019 template for .NET Core Web Application (API), then you will get a WeatherForcast model and WeatherForecastController.

I have moved the WeatherForcast model under Models folder. If you also follow the same step, the solution structure should be as shown below:

Add NuGet Packages

Please make sure you add below NuGet packages to the Web API Project:

IdentityDbContext

This is the DbContext which comes out of the box with Microsoft.AspNetCore.Identity.EntityFrameworkCore NuGet package. The important classes are:

  • IdentityDbContext, represents the DbContext for Identity. It has definitions for all the tables required to enable ASP .NET Core Identity.
  • IdentityUser, which represents a user in Identity database
  • IdentityRole, which represents a role in Identity database

Now, in your web API project, create a class ApplicationDbContext, which derives from IdentityDbContext. The ApplicationDbContext can contain your application tables as well. For the purpose of this demo, let’s just derive this class from IdentityDbContext and create a constructors which accepts DbContextOptions parameter as shown in below code.

public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
    public ApplicationDbContext(DbContextOptions options) : base(options)
    {
    }
}

Configure Identity

Now, open the Startup configurations and add below code under ConfigureServices. This code will setup the database context. The second line configures the database which should be used for identity.

AddIdentity(IServiceCollection) adds the default identity system configuration for the specified User and Role types.

services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SqlConnection")));
            
services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();

Please note that you should have a connection string with name “SqlConnection” in your appsettings.json. Otherwise the application will not be able to connect to database, resulting in errors while running the application. The Sample appsettings.json is provided below:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },

  "ConnectionStrings": {
    "SqlConnection": "Server=.;Initial Catalog=MyAppDb; Integrated Security=true;"
  },

  "AllowedHosts": "*"
}

Migrations and Create Database

Below commands are the commands which can be used to create the database.

First command is to install the EF Core migration tools.

dotnet tool install --global dotnet-ef --version 3.1.0

The Second command can be used to create a migration.

dotnet-ef migrations add First --project CookieAuthSampleAPI

The third one to create the database in SQL Server. The database will be created in the SQL server instance which is specified in the connection string inside appsettings.json.

dotnet-ef database update --project CookieAuthSampleAPI

Now, if you go to SSMS and connect to right SQL Server instance, you should be able to see the database created as shown in below snapshot.

So, in this article, we have seen how to add Identity in Web API project. We have not yet used it for authentication / authorization purpose. I hope you enjoyed this article. Let me know your thoughts.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *