This post is about how to use Identity to secure a Web API backend for SPAs such as Angular, React, and Vue apps. Unlike ASP.NET Core MVC, Web API projects doesn’t support the --auth Individual option while creating the Web API project from dotnet SDK. We have to manually add the nuget package references. So first we need to create a web api project, we can do that using the following command - ` dotnet new webapi –name Weatherforecast.Api –output Weatherforecast`. Next we need to add reference of different NuGet packages. I am using Sql Server as the backend.
The first NuGet package is for getting the identity related objects. The other two for database interactions and for creating and running migrations.
Once the NuGet packages added, we can create the DbContext class which should be inheriting from IdentityDbContext. Here is the implementation.
And then we can modify the Program.cs file like this. First we need to configure the DbContext and then set the Identity Api endpoints, like this.
Also we need to update the appsettings.json with the Sql server connection string. Now we have completed the configuration. Next we can create migrations using the command dotnet ef migrations add InitialMigrations, then create database and apply migrations using dotnet ef database update command.
Now we are ready to run the web api. To protect the Api endpoints, we can use RequireAuthorization() extension method. To protect the /weatherforecast we can do like this.
For controller based projects, we can use the [Authorize] attribute as well. The RequireAuthorization() method can accept claims or roles if we want to control the access based on specific claims or role.
Here is the screenshot of the swagger UI.
Here is the complete Program.cs
This way we can configure ASP.NET Core Identity to protect a Backend API. This method works well with both Cookie based and Token based authentication models.