How to implement JWT authentication in ASP.NET Core

Uncategorized

ASP.NET Core uses a streamlined hosting design, called very little APIs, that permits us to build light-weight APIs with minimal reliances. Very little APIs are perfect for developing microservices and quick HTTP APIs. Naturally, you will frequently require to secure the endpoints of such APIs in your applications. The goal of this post is to offer you a head start on doing so.We have actually gone over how to start with minimal APIs, how to use logging and dependency injection in very little APIs, and how to check minimal APIs in earlier short articles. This post goes over how we can secure our minimal API endpoints utilizing JWT authentication– i.e., authentication based upon JSON Web Tokens.To secure a

very little API utilizing JWT authentication, we will follow these actions:

  1. Develop a very little API task in Visual Studio 2022.
  2. Develop an API endpoint in the Program.cs file.
  3. Add the Microsoft.AspNetCore.Authentication.JwtBearer NuGet bundle to our project.
  4. Execute JWT authentication in the Program.cs file.
  5. Produce a user model class called User to save the login qualifications of the user.
  6. Specify a secret type in the appsettings.json file.
  7. Specify JWT authentication settings in the Program.cs file.
  8. Include permission services middleware to our application in the Program.cs file.
  9. Develop and validate the JSON Web Token in the Program.cs file.

Note that all of the code examples displayed in this post, except the User model class, ought to belong to Program.cs. The User model class must be part of the User.cs file.To work with the code examples offered in this post, you need to have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Develop an ASP.NET Core very little Web API job in Visual Studio 2022

First of all, let’s create an ASP.NET Core job in Visual Studio. Following these steps will develop a brand-new ASP.NET Core Web API project in Visual Studio 2022:

  1. Launch the Visual Studio 2022 IDE.
  2. Click “Produce new task.”
  3. In the “Develop brand-new project” window, select “ASP.NET Core Web API” from the list of templates showed.
  4. Click Next.
  5. In the “Configure your new job” window, specify the name and location for the brand-new task.
  6. Additionally inspect the “Place option and project in the exact same directory” check box, depending on your preferences.
  7. Click Next.
  8. In the “Extra Info” window revealed next, uncheck the check box that says “Use controllers …” since we’ll be using minimal APIs in this example. Leave the “Authentication Type” as “None” (default).
  9. Make sure that the check boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Assistance” are unchecked as we will not be utilizing any of those functions here.
  10. Click Create.

We’ll utilize this ASP.NET Core Web API job to develop a minimal API endpoint and implement JWT authentication for it in the subsequent areas of this article.Create a HTTP Get

endpoint in ASP.NET Core

When you produce a brand-new very little Web API project in Visual Studio 2022, a Program.cs file will be developed with a few lines of default code. You can replace the default code with the following code bit to keep things simple and still provide a way to test your API.

var home builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet(“/ security/getMessage”, () => “Hey there World!”). RequireAuthorization(); app.Run();

Note making use of the RequireAuthorization extension approach here. This assists you secure your routes using authorization policies and forces you to offer authentication details when calling this endpoint. The authorization middleware will utilize this details to validate the ask for the current execution context.If you execute this endpoint without this details, you’ll encounter a HTTP 401 Unauthorized mistake as displayed in Figure 1. IDG Figure 1. An HTTP 401 Unauthorized error will be generated if authorization is required and no authorization details is offered. Set Up the JwtBearer NuGet plan Now include

the Microsoft.AspNetCore.Authentication.JwtBearer NuGet bundle to your task. To do this, select the project in the Option Explorer window,

then right-click and select”Manage NuGet Plans.” In the NuGet Package Manager window, look for the Microsoft.AspNetCore.Authentication.JwtBearer package and install it.Alternatively, you can install the package via the NuGet Plan Manager console by entering the command shown listed below. PM > Install-Package Microsoft.AspNetCore.Authentication.JwtBearer Specify a secret key in the appsettings.json file Next, create a section in the appsettings.json file for the Provider, Audience, and Key info. This info will be utilized later on to generate a JSON Web Token. Note that you can offer any name to this area you desire; I’ll utilize the name”Jwt”for convenience. Include the following details in the appsettings.json file.”Jwt”:

Define authentication settings in the Program.cs file The AddAuthenication approach in the Program.cs file is used to set up JWT authentication at the time when the application begins. It specifies the authentication plan as JwtBearer. Additionally the call to the AddJwtBearer method assists set up token parameters.The Provider, Audience, and Key worths are read from the appsettings.json config file. The TokenValidationParameters instance is used to indicate if the Company, Audience, Secret, and Life time details must be confirmed or not. builder.Services.AddAuthentication(options => ). AddJwtBearer(o= > ); To include permission services to your application, your Program.cs ought to also include the following code snippet.builder.Services.AddAuthorization(); Your Program.cs ought to also consist of the following techniques to make it possible for authentication and authorization capabilities.app.UseAuthentication(); app.UseAuthorization(); Produce a user design in ASP.NET Core We will need a class to save the login credentials of the user or users.

Produce a class named User in a file having the same name with a.cs extension. Then insert the following code.public class User This class will be used to accept user credentials as input.Create an endpoint to produce JSON Web Tokens Lastly, we need to compose the needed code to produce and confirm the JWTs we’ll utilize to license calls to the API. When a token is produced in reaction to an initial request to the API, you can copy it and utilize it for permission in all subsequent requests.Now, write the following code in the Program.cs file to develop a brand-new HTTP Post endpoint that will develop a JWT for a confirmed user.app.MapPost (“/ security/createToken”, [AllowAnonymous](User user)=> <); A circumstances of the User class is used to accept a user name and a password passed to this endpoint. Keep in mind the AllowAnonymous attribute. This is used to specify that we do not require an authorization check in this endpoint. The Provider, Audience, and Secret read from the configuration file. Each of these is utilized to develop the token, which we have actually specified will expire in 5 minutes.The complete source code for Program.cs Here is the total source code of the Program.cs file for your reference.using Microsoft.AspNetCore.Authentication.JwtBearer; utilizing Microsoft.AspNetCore.Authorization; utilizing Microsoft.IdentityModel.Tokens; utilizing System.IdentityModel.Tokens.Jwt; using System.Security.Claims; utilizing System.Text; var home builder=WebApplication.CreateBuilder( args); builder.Services.AddAuthentication(choices=> ). AddJwtBearer (o => ); builder.Services.AddAuthorization(); var app=builder.Build(); app.UseHttpsRedirection(); app.MapGet(“/ security/getMessage “,()=>”Hi World!”). RequireAuthorization(); app.MapPost(“/ security/createToken “, [AllowAnonymous](User user)=> if(user.UserName== ” joydip”& & user.Password = =”joydip123″) return Results.Unauthorized ();); app.UseAuthentication (); app.UseAuthorization (); app.Run (); JWT authentication in action When you publish the user credentials to the createToken endpoint using Postman, you ‘ll have the ability to see the produced token. IDG Figure 2. The JWT is generated successfully. Note that we’ve passed the user credentials, i.e., the user name and password, in the body of the request.Now, call the HTTP Get endpoint we produced earlier and pass the generated token as a bearer token in the request header. If your created token is valid, you’ll see the message revealed in Figure 3. IDG Figure 3. The HTTP Get endpoint returns the text message in the response. As you can see in Figure 3, the text message”Hey there World!”is displayed due to the fact that the token we passed stands.

Note the HTTP 200 OK response as well (highlighted in a green rectangular shape). In this example, we hardcoded the user name and password to keep things easy. Of course, you need to never ever hardcode user credentials in a production environment. A great choice is to use ASP.NET Core Identity to handle user accounts.To test our minimal API implementation here, we’ve used Postman, among the most popular tools available today to check APIs. To evaluate your minimal API endpoints, you could also use Swagger, a toolkit that makes it easy to offer a graphical representation of your API. Copyright © 2023 IDG Communications, Inc. Source

Leave a Reply

Your email address will not be published. Required fields are marked *