Adding ASP .NET Core Identity to Web API Project

Adding 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. The completed web API project is available in my GitHub repository.

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.

Leave a Reply

This Post Has 9 Comments

  1. bplus0

    Great article. Can you provide some insight how we’d handle this if we created a web mvc app to connect to the api? How do we utilize the identity in that case

    1. Manoj Choudhari

      Thanks ! I will try to create a POC around it and try to publish blog post on it.

  2. Alex

    Thank you, very clear and well done article!

  3. Muzammal

    thank u

  4. Azizjan Ayupov

    Nice tutorial. Please, don’t stop and continue this guide with an article on how to create auth with JWT.

  5. Raj

    Most important is how to use it in an application say for ex; ASP.NET Core Web Application.

  6. sanjib

    Just awesome !

  7. Semih

    Thank you. It’s a beautiful write