How to implement JWT Token Authentication in ASP.NET Core 5.0 Web API using JWT
Tags: dotnet, programming, security, csharp
Published: 2021-04-10 08:13:07

---
title: How to implement JWT Token Authentication in ASP.NET Core 5.0 Web API using JWT
published: true
date: 2021-04-09 06:30:17 UTC
tags: dotnet,programming,security,csharp
canonical_url: https://www.faciletechnolab.com/blog/how-to-implement-jwt-token-authentication-in-aspnet-core-50-web-api-using-jwt/
---

In this article, I’m going to show you how to implement token authentication in ASP.NET Core 5.0 Web API using JWT. I will create ASP.NET Web API project and show you step by step how to generate JWT token and use it for authentication and authorization.

### Creating a new .NET 5.0 Web API project

Open visual studio 2019 community and click on “create a new project” and select “ASP.NET Core Web API” project and click next.

![create new project in visual studio](https://www.faciletechnolab.com/media/ipuetqlf/jwt-1.png?rmode=max&width=500)

In the “configure your new project”, enter name, location, and solution name of your project and click next.

![configure your new project in visual studio](https://www.faciletechnolab.com/media/c44bb0r2/jwt-2.png?rmode=max&width=500)

In the “Additional information” step, choose “.NET 5.0 in “Target Framework” dropdown, None in “Authentication Type” and click on create

![configure Additional information for new project in visual studio](https://www.faciletechnolab.com/media/51tftyl0/jwt-3.png?rmode=max&width=500)

 

### Adding JWT configurations in appsettings.json

Run your application once and copy the url of your application. That will be used for JwtIssuer value in app settings. Open appsettings.json and add following configurations at the end of file:

{% gist https://gist.github.com/FacileTechnolab/761cebe1e26759bd6293984a38f58a42 %}

 

### Adding login feature

Add new empty controller in the “Controllers” folder of your project and name it AccountController and add following code into it.

{% gist  https://gist.github.com/FacileTechnolab/414b81f4f8acdc81b816cb743951ced1 %}

 

### Securing resources using JWT Authentication

Open “WeatherForcastController.cs” and above `Get()` method, add this line `[Authorize(Roles = "Role1")]` and this will enforce the method will be only accessible if JWT token is present in the header and the user for which the token is generated belongs to Role1. you can use `[Authorize()]` attribute to ensure the user passes JWT token in order to access the method.

 

### Testing the Login method issuing tokens 

Run the project and you will see an Open API documentation as shown below.

![Run project, OpenAPI documentation](https://www.faciletechnolab.com/media/xp3b0wok/jwt-4.png?rmode=max&width=500)

Under Account, click on the “POST /Login” and click try it out in the write. Enter body as shown in figure below and hit execute.

![invoke login method](https://www.faciletechnolab.com/media/jooho5vf/jwt-5.png?rmode=max&width=500)

You will see a success response with token and username as shown below.

![token and user name in login response](https://www.faciletechnolab.com/media/oighqi3o/jwt-6.png?rmode=max&width=500)

Next, we want to test the WeatherForecast service that we secure earlier. Scroll down to “WeatherForcast” section in the OpenAPI documentation and click on “GET /WeatherForcast” and click on “Try it out” in the top right of the expanded section and hit execute.

![invoke WeatherForcast Get method](https://www.faciletechnolab.com/media/toybrrtd/jwt-7.png?rmode=max&width=500)

Once you hit execute, you will see following error.

![weatherforcast error](https://www.faciletechnolab.com/media/snojuu3e/jwt-7-5.png?rmode=max&width=500)

class="post\_\_text">The error says “System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found.” And it means we need some more configuration to make it work.

 

### Configure token authentication in ASP.NET Core

The error means ASP.NET Core do not know how to authorize the request since we added authorization attribute in WeatherForcast service.

In order to configure ASP.NET Core to use token authentication as the default authentication scheme and how to validate in coming tokens, add following to your CofigureServices method.
{% gist https://gist.github.com/FacileTechnolab/4e6ea3d97cb72c01f03bb475276fd35e %}

Next, in the Configure method, add `app.UseAuthentication();` before `app.UseAuthorization();` if not present.

 

### Testing weatherForcast service with authentication 

Now that we have configured ASP.NET Core to use token authentication, we should be able to use the token issued by Login method to access WeatherForcast.

Since OpenAPI documentation do not support setting up headers, we can use Postman tool to test the same.

You can copy the token received in the login response and use Authorization: Bearer <token> and you will be able to access WeatherForcast service.</token>

![Run project, OpenAPI documentation](https://www.faciletechnolab.com/media/i04pnimc/jwt-8.png?rmode=max&width=500)

Under Account, click on the “POST /Login” and click try it out in the write. Enter body as shown in figure below and hit execute.

![weather forcast response](https://www.faciletechnolab.com/media/ggiddqxc/jwt-9.png?rmode=max&width=500)

 

### Using token authentication with ASP.NET Core Identity and Entity Framework Core.

You can extend the code here to use it with ASP.NET Core Identity and Entity Core. Here are reference articles that shows the same.

- [https://dotnetdetail.net/asp-net-core-5-web-api-token-based-authentication-example-using-jwt/](https://dotnetdetail.net/asp-net-core-5-web-api-token-based-authentication-example-using-jwt/) 
- [https://www.c-sharpcorner.com/article/authentication-and-authorization-in-asp-net-5-with-jwt-and-swagger/](https://www.c-sharpcorner.com/article/authentication-and-authorization-in-asp-net-5-with-jwt-and-swagger/) 

### Conclusion

We just learned how to implement a basic token authentication in .NET 5.0.


> Looking to extend your [software development team](https://www.faciletechnolab.com/hire-remote-net-core-developers/)? [Try ASP.NET Developers or team](https://www.faciletechnolab.com/hire-remote-net-core-developers/) from [Facile Technolab](https://www.faciletechnolab.com/). We are the [TOP RATED PLUS Upwork Agency](https://www.upwork.com/ag/faciletechnolab/), [Registered Umbraco Partner](https://www.faciletechnolab.com/technologies/content-management-system/umbraco), [ASP.NET Zero](https://www.faciletechnolab.com/technologies/software-development-frameworks/aspnet-zero) Reseller Partner, [Abp.io Experts](https://www.faciletechnolab.com/technologies/software-development-frameworks/abpio) and [Top ASP.NET Development Team in India](https://www.faciletechnolab.com/hire-remote-net-core-developers/).