Jwt Authentication In ASP.NET Core Web API

A Step by Step guide how to implementation Login, Register and token based authentication process.

Pritomsarkar
C# Programming

--

Overview

It is an open standard that allows transmitting data between parties as a JSON object in a secure and compact way. The data transmitting using JWT between parties is digitally signed so that it can be easily verified and trusted. There are various ways to Authenticate ASP.NET Core API. In this Guide let’s build a Secure ASP.NET Core API with JWT Authentication.

Prerequisites

I expect you to have knowledge of object-oriented programming concepts in C# also I assume you know .NET Core Web API basic concepts and PostMan Software for testing purpose.

To code along with me, you will have to install the minimum .NET Core 2.2 Or higher version as well as Visual Studio and PostMan Software.You can also use another IDE instead of a visual studio.You can find a link to the Github repository end of this article.

Environment Setup

At first you have to create an ASP.NET Core Web Application with API template.

Configure Asp.Net Core Web API for JWT authentication

First, have to create an AppUser model for the user entity.

Okay, so we have to create a new controller for that we will manage user login and register. now we are going to create AccountController.

Okay, Great! Now we got our register method. so what we will do now is go to PostMan test our register method. we have actually two different register user options. one is from the register of the user using a query string http://localhost:59750/api/account/register?username=sam&password=password

and the other one is register users using the body of the request. so in body, we have username is “dave” password has “password”.but our API controller in register don’t know actually where parameter value is coming from, it could be in the body, it could be in the query. so let’s see what will happen.

Now we will try to send the username and password in the body of the request.

But we get in the 500 Internal Server Error. But using query string we will succeed we already see that above. but normally question that comes to mind is why the body of the request is not succeded. so now debug your code and look at that what actually happened. if you debug your code which you send body request, you will see two-parameter of register method are null. the reason for this is when we send body requests we actually send an object. but our two input parameter is just string type, not an object. this is the reason actually. so for that, we have to use DTO(Data Transfer Object). So now we are going to create a folder name is DTO and inside here we have to create a new c# class and this name is RegisterDto.cs.

Now we have to update some code in AccountController.

We created a private UserExists method to check Username is unique or not. We access this method in the register method. so now we have to go to our PostMan for the test now the register is perfectly working or not. And this time should be successful.

And now we see it’s working now as expected and that’s what we looking for.

Now time to Create the Login method in AccountController.but before we have to create a separate DTO for the Login method. So our DTO folder we have to create a new c# class and this name is LoginDto.cs.

And this is Login Method in AccountController.

So above code, once any user Login; at first, we need to do is get the user from the database. and then if we don’t find any user that means null then we throw an exception Unauthorized and send a message Invalid UserName.now we used hmacsha512. we need to calculate the computed hash of the password using the Passwordsalt. so we have to something compare against. if loginDto.Password is the same which is already created the original hash version of the password is similar, then it should be identical. if they are identical the user should logged in. if the user is not identical then we return Unauthorized in that case. so what we need to do, it’s a byte array of the above code. we need to loop over each element in this array. just for testing if all is identical then return the user object above my code. now we going to PostMan to test our Login code.

If you enter an incorrect password

So Everything works fine as expected. our login is working. now we prove we can login and register. but we have not done how to authenticate. now time to play with the JWT token.

So at first, we have to create another folder and which name is Interfaces. in this folder, we will create a new C# Interface and its name ITokenService.an interface does not contain any implementation logic. only contains a signature of the functionality the interface provides.

Now we have to create an implementation class for our ITokenService.for that now we have to create another folder. and its name is Services and inside here we will create a new C# class, this class name is TokenService.

The above code is totally incomplete. we will update this soon. but now we have to add our service into our Dependency injection container in Startup.cs

Now we are going to create a JWT token. So now we have to install a NuGet Package System.IdentityModel.Token.Jwt

Now we are going to complete our incomplete code which I mentioned. basically, here we will create a token and return this.

So above code, we do that, adding our claims, created some credentials, described how token our look, then we use tokenHandler for just something, we need to create. then we go ahead for create. then return the WriteToken for whoever needs it.

So we are already have done generate a token, register, and login functionality. so we have to make functionality for find token service from the Accountcontroller. because we built this separately, now time to combined each other as needed. So, We have to make some changes in AccountController.In Register and Login method, we return AppUser type data. we need to change its type. because we need to return the token. so for the return type, we need another DTO. Now we will be going to create c# class UserDto.cs in our created DTO folder.

And this is these object we are going to return when user login and register. Now we will update the Login and Register method in AccountController.

Above code, we return UserDto type data in Register and Login method. also added tokenservice in the constructor in AccountController.Now time to specify a TokenKey in appsettings.json file which will create Tokesnservice.cs ‘s constructor.

Now time to test

So we got the Username and token as expected. Now we are going to do Authenticate user requests. now need to create a custom middleware for authenticating with the JWT token. so for that first, we have to install the NuGet package Microsoft.AspNetCore.Authentication.JwtBearer

So now we need to add service for our Authentication in Startup.cs file.So we need to some update in our startup.cs file.

Now time to test.I will write [Authorize] in top of method in my default ValuesController.

Now we will test is Authorize works or not parfectly.

So working fine as expected.now we successfully Authentication enabled in our app.

We are completed Authentication setup.Now we will just tidy up our startup class.we are going to make some extensions method or you can say going to build a custom services for tidy our startup.cs.So first we have to create a Folder in our project and it’s name is Extensions and inside this folder,we will create two extension class,ApplicationServiceExtensions.cs and IdentityServiceExtensions.cs.

ApplicationServiceExtensions.cs

IdentityServiceExtensions.cs

Startup.cs

Now Startup.cs is much clean because of using custom service or Extension method.If we test again,then we will found result as expected.

Conclusion

This article has covered Register and Login using JWT Authentication.I think now you are understand about token based Authentication system.you can download this source code in my Github Repository.hope you guys enjoy this article.

--

--