> mobileapp Strategy - From Idea to Mobile App RealityVinova Our team will brainstorm with you on where to begin, where to go, and how to get you there. Whether you have a spark of an idea or an existing app – we can help. Getting your mobile strategy right is what our unique services are all about. We’ll wrestle with business challenges, discover new opportunities that will help you define and refine your product ideas into mobile app reality.

How to Implement JWT Authentication in Web API Using .Net 6.0, Asp.Net Core

How to Implement JWT Authentication in Web API Using .Net 6.0, Asp.Net Core

In this article, we are going to create a web application using .Net 6.0 and ASP.Net Core and also implement JWT Authentication.

JWT stands for JSON Web Token digitally signed using a secret key by a token provider. It helps the resource server to verify the token data using the same secret key.

JWT consists of three parts:

Here I am going to use Visual Studio 2022 and SQL Server 2014.

Creating Tables

First, we will create a database named “JWTAuthentication” or we can use any name and create two tables “UserInfo” and “Employee”. Open SQL Server and paste the below query to create the tables.

Create the Application

Here we will create a new project using Blazor WebAssembly App and .Net 6.0. Now open Visual Studio 2022 and follow the below steps.

Step 1

In this step, we will select the “Blazor WebAssembly App” project type.

Here we will select Framework type as .NET 6.0 and also select the ASP.NET Core hosted option.

Now, our application will be created with a folder structure as given in the below image.

Install Required Nuget Packages

Go to the “Tools” menu, select NuGet Package Manager > Package Manager Console and then run the below commands to add database provider and Entity Framework Tools.

=> Install-Package Microsoft.EntityFrameworkCore
=> Install-Package Microsoft.EntityFrameworkCore.SqlServer
=> Install-Package Microsoft.AspNetCore.Authentication.JwtBearer

Adding the Model to the Application

Now we will create two Model classes that will contain the UserInfo and Employee model properties.

To do that right-click on the “JWTAuth.WebApi” project and add a New Folder as “Models”.

Then right-click on the “Models” folder and add two classes as “UserInfo.cs” and “Employee.cs”.

Now open the “UserInfo.cs” file and paste the below code to it.

Now open the “Employee.cs” file and paste the below code to it.

Adding Data Access Layer to the Application:

Now we will create a “DatabaseContext.cs” class where we define database connection. To do that right-click on the “JWTAuth.WebApi” project and add a folder as “Models”. Add the “DatabaseContext.cs” file to the “Models” folder and put the below code to it.

Now we will create another two folders “Interface” and “Repository” to handle database-related operations.

Right-click on the “JWTAuth.WebApi” project and add two new folders as “Interface” and “Repository”.

Now add an interface to the “Interface” folder, name it as “IEmployees.cs” and put the below code to it.

Now add a class name as “EmployeeRepository.cs” to the “Repository” folder, which will inherit “IEmployees” interface, and put the below code to it.

Now we will add “DatabaseContext”,“IUser” and “UserManager” reference to the “Program.cs” file of the“JWTAuth.WebApi” project.

Open the “Program.cs” file and put the below code to it.

Adding the Web API Controller to the Application

Right-click on the “Controllers” folder and select “Add” then “New Item”. It will open an “Add New Item” dialog box. Select “ASP.NET” from the left panel, then select “API Controller – Empty” from templates and put the controller class name as “EmployeeController.cs”. Press Add to create the controller.

Now open the “EmployeeController.cs” file and put the below code into it.

Run the Application and Test APIs with Postman

Before we execute the application, change the lunch URL to “api/employee” in “launchSettings.json”. When we execute the application will be able to see all employee listings like the below image.

Now we will see how to consume our service using Postman.

Postman is an API testing tool that helps developers consume and check how an API works. You can download and install Postman here.

To view the Employee list

Step 1

Open Postman and enter this endpoint: https://localhost:7113/api/employee.

Step 2 

Choose the method as GET and click Send. Now, all the employee details will be listed as shown in the below image.

To view the details of an Employee

Step 1

Open Postman and enter this endpoint: https://localhost:7113/api/employee/1.

Step 2

Choose method as GET and click Send. Now, you can see the details of the employee.

To create a new employee

Step 1

Enter this endpoint into Postman: https://localhost:7113/api/employee.

Step 2

Choose the POST method and under Body > Raw, choose type JSON and paste the employee details. By clicking Send, a new employee is created.

To update details of an employee

Step 1

Enter this endpoint into Postman: https://localhost:7113/api/employee/5.

Step 2

Choose the PUT method and under Body > Raw, choose type JSON and paste the employee details to update. By clicking on Send, the details are updated.

To delete an employee

Enter this endpoint into Postman: https://localhost:7113/api/employee/12.

Step 2

Choose the DELETE method and click Send. Now, the employee details will be deleted from the database.

Implementation of JWT

Above we learned how to how we can consume and test our APIs in postman. But here our APIs are not secure, because anyone who knows the APIs endpoint can consume it. So to secure our APIs we will use JWT bearer token in our APIs.

Adding the Token to the Application

Right-click on the “Controllers” folder and select “Add” then “New Item”. It will open an “Add New Item” dialog box. Select “ASP.NET” from the left panel, then select “API Controller – Empty” from templates and put the controller class name as “TokenController.cs”. Press Add to create the controller.

Now open the “TokenController.cs” file and put the below code into it

The “TokenController” action method accepts username and password as input. It will check the user’s credentials with the database to ensure the user’s identity. If the username and password are valid then it will return the access token and if it’s invalid then a bad request error will be returned.

Now open “appsetting.json” and add the below code to the file

Now open “Program.cs” and add the below code to the file.

In the above code, we configured authorization middleware in the startup. Here we have passed the security key when creating the token and enabled validation of Issuer and Audience. Also, we have set “SaveToken” to true, which stores the bearer token in HTTP Context. So we can use the token later in the controller.

Here is the modified “Program.cs” file code.

Now we add the authorization attribute to the “EmployeeController” controller, so all the APIs under this controller will be secured with the token.

Test APIs are secured by the JWT with Postman

Now when we try to get the employee list by using postman we will get a “401 Unauthorized” error.

Now, we will see how to access the APIs using the JWT token.

To create a token using Postman

Step 1

Enter this endpoint https://localhost:7113/api/token.

Step 2

Choose the POST method under Body > Raw, choose type JSON, and paste the user details. By clicking Send, user credentials will be checked, and it will generate the token.

Copy the token that was created. Under “Auth” choose type as “Bearer Token” and paste the copied token key in the “Token” field. Now by clicking on Send we will see the employee list.

In this article, we have learned how to create a REST API using .Net 6.0, ASP.NET Core, perform basic CRUD operations, create a JWT token, and secure the APIs. Hope this article will help the readers.

Happy Coding!!!

This content was originally published here.

Malcare WordPress Security

singapore website design,web application singapore,website developer singapore,mobile app developer singapore,website designer singapore,website development singapore,mobile developer singapore,android developer singapore,web design singapore,developers in singapore,design agency singapore,ruby on rails developer singapore,singapore mobile application developer,singapore web design services,web designer singapore,developer in singapore,web development company singapore,singapore web design,web design services singapore,mobile application developer singapore,graphic designer in singapore,ios app development singapore,mobile apps singapore,design firms in singapore,singapore app developer,mobile app development singapore,ios developer singapore,web design company singapore,app developer singapore,mobile game developer singapore,app development singapore,singapore mobile app developer,web development singapore,mobile apps development singapore,website design singapore,mobile application development singapore,singapore web development