Authentication using ASP.NET Core Identity


Welcome to the new blog. Here we'll learn what ASP.NET Core Identity is, what is the use of this and how we can implement in our project. So Let's start!

What is ASP.NET Identity?

ASP.NET Idetity is a built in authentication provider for ASP.NET Core Application which is used to manage authentication and authorization. It provides ready to use APIs, UIs and Database configuration to apply autentication in our app. It includes features like registering a user, login into app, allowing a user to access protected resources. It also provides external logins like logging from facebook, google etc and multi factor autentication as well.

When to use ASP.NET Core Identity?

It is most suitable for Single Page Application (SPA) where we have only browser as a client and we don't have any OIDC provider to implement. It is not suitable for app which can use Single Sign On (SSO). 

Apply Authentication using ASP.NET Core Identity

 We already have an Employee management Solution, where we learned the basics of Controller Based Web APIs. Now the time has come to secure our Web APIs i.e. only authenticated user can access our APIs. We want only authenticated users can create or manage employee. If we'll not apply authentication to our APIs then everyone can create or manage employee and we can't control creation of employees. Thus we need authentication badly here, otherwise the system will have of no use.

We choose ASP.NET Core Identity as our authentication provider for our Web API project as it provides built in  Identity management APIs and Database configuration as well. The reason behind this is, currently our Web API will only be consumed by a client Application i.e. a SPA. We currently don't need any OIDC provider. Another reason behind this is we don't want to invest time in building an custom authentication provider from our own when ready to use solution is already present. Also, we don't have to worry about the standards on authentication as it is already handled there. These are some of the the reason we decided to use ASP.NET Core Identity as an Authentication Provider to our Employee Management Web APIs

Now let's start implement this into our Web APIs.

As a quick overview we're using EF Core and Controller Based APIs and SQL Server as DB for our project. Thus, we've already added the required packages to configure EF Core. Please follow this link to verify that your Web API is already using EF Core.

Add Identity Nuget Package

The first step for adding ASP.NET Core Identity will start from adding the below Nuget Package.

Add DBContext and Migration

Now, we'll add DB Context for our Identity entities. Here is our IdentityDbContext.cs definition.
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace EmployeeManagement.Models
{
    public class IdentityDBContext(DbContextOptions<IdentityDBContext> options) : IdentityDbContext<IdentityUser>(options)
    {
    }
}
Register the above DBContext. This below line will register the IdentityDBContext to our web application. Add this after WebApplication.CreateBuilder(args);.
builder.Services.AddDbContext<IdentityDBContext>(x => x.UseSqlServer(builder.Configuration.GetConnectionString("EmployeeConn")));

Now we'll add migration for our Identity Entities.  We'll name our migration as IdentitySchema
dotnet ef migrations add IdentitySchema --context IdentityDBContext
You can see the Migration file is added with all the identity tables.
Let's update the database with the Identity tables. Below command will apply the schema changes to our DB. 
dotnet ef update database

Configure Identity Services

Now, the time has come to register the Identity services to Web Application service collection that will be used to support Identity in our app. We've to configures authentication schemes as well, so that authentication middleware can understand which scheme to use  i.e. Cookie and Bearer token. We've to also tells the Identity Services to use EF Core implementation for Idebtity store. Below line will add the required configuration into our app.
builder.Services.AddIdentityApiEndpoints<IdentityUser>()
    .AddEntityFrameworkStores<IdentityDBContext>();

Now, we'll add endpoints for managing registration, login, logout, password recovery etc. To do that we've added the below line after the call to builder.build().
app.MapIdentityApi<IdentityUser>();
The above line will expose all the Identity APIs.

Test the ASP.NET Core Identity Implementation

To test the above implementation, first we'll make our EmployeeController to Authorised access only. 
For now we're not adding any permission but we want our Web APIs will only be accessible to authenticated users. For that, we'll add the Authorization Middleware to our application. Below line need to be added before app.MapControllers().
app.UseAuthorization()
This will add the AuthorizationMiddleware which will be used to apply Authorization to our Web APIs.

The next step will be to add the Authorize attribute. This will tell the middleware to apply authorization to the particular Controller or action methods. 


We can add the Authorize attribute to a particular Action if we don't want to apply Authorization to all the Action methods of Controller.

Our ASP.NET Core Identity implementation is done. It requires minimal steps to onfigur. Now, let's start testing our ASP.NET Core Identity Implementation

As our EmployeeController has Authorize attribute that means only authenticated user will be able to access that endpoint. Let's try to access any enpoint present in EmployeeController Anonymously.


It is giving us 401 Unauthorized, which means only Authenticated users can access the API. So, let's statrt authenticating ourselves.

Register Endpoint

Let's register ourselfs using the POST /register endpoint.

Our registeration is successful. That means our email and password is now registered with the system. Now we can access the APIs after Login.

Login Endpoint




As we have seleced useCookies = true. This will use Cookie Based Authentication. Now, we are authenticated and can access all the Protected APIs. 

As we've chosen Cookie Based Authentication, so the passing of Authentication will automatically handled in browsers. Browser will pass the Authentication cookie on each HTTP Request to server. We don't have to pass any extra header to let the server know about authenicated request. Browser will automatically handle the cookie and pass te cookie. And while processing the request on server side ASP.NET Identity will validate the cookie is valid or not and based on that allow access to Protected resources.
If we'd chosen useCookie = false, then by default it will use Bearer Token and it will return access and refresh token. That access token need to be passed in each HTTP Request as a Authorization header and we can access the APIs after that.
But, for now we'll go with Cookie Authentication. Microsoft also suggest to use Cookie Based Authentication whereever possible.

Let's try accessing our protected endpoints from EmployeeController.



We're now able to access our protected endpoints. Now our Web APIs are secured. No, Unauthenticaed uses can access our APIs. Only Authenticated users can access.

Conclusion

In this blog, we got to know about how to implement authentication using ASP.NET Core Identity and EF Core. If you're developing a Web API and you've only a browser as a client, you don't have OIDC server or you don't need Single Sign On, then ASP.NET Core Identity is the best option. Most of the time this is the only option we need. 
Here we tried only simple register and login. There are lot's of model validation present on the register endpoint. You can try those validation by passing an invalid data o request. Also, we can customize the validation based on the requirement. But, most of them as standard validation and we don't need to customize. 
However we'll learn about those validations and use of rest of the endpoints on later session.

If you think this information helped you then please share this to your friend. If you don't like or found somehing wrong then your feedback will be appreciated.

Thanks!

Comments