How to execute JWT authentication in ASP.NET Core 6

Uncategorized

ASP.NET Core 6 presents a simplified hosting model that allows us to build lightweight APIs with very little reliances. Naturally, you will typically need to secure the endpoints of such APIs in your applications. The objective of this post is to provide you a head start on doing so.We have talked about how to get going with minimal APIs, how to use logging and dependency injection in minimal APIs, and how to test minimal APIs in earlier posts. This post talks about how we can protect our minimal API endpoints using JWT authentication– i.e., authentication based on JSON Web Tokens.To secure a

minimal API using JWT authentication, we will follow these steps:

  1. Develop a minimal API project in Visual Studio 2022.
  2. Produce an API endpoint in the Program.cs file.
  3. Include the Microsoft.AspNetCore.Authentication.JwtBearer NuGet package to our project.
  4. Execute JWT authentication in the Program.cs file.
  5. Develop a user model class named User to keep the login qualifications of the user.
  6. Specify a secret type in the appsettings.json file.
  7. Define JWT authentication settings in the Program.cs file.
  8. Include authorization services middleware to our application in the Program.cs file.
  9. Produce and verify the JSON Web Token in the Program.cs file.

Note that all of the code examples shown in this post, except the User design class, ought to become part of Program.cs. The User design class should be part of the User.cs file.To deal with the code examples offered in this short article, you need to have Visual Studio 2022 set up in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create an ASP.NET Core 6 very little Web API project in Visual Studio 2022

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

  1. Launch the Visual Studio 2022 IDE.
  2. Click “Produce brand-new job.”
  3. In the “Develop new task” window, choose “ASP.NET Core Web API” from the list of templates showed.
  4. Click Next.
  5. In the “Configure your new task” window, specify the name and place for the brand-new project.
  6. Optionally check the “Place service and task in the very same directory” check box, depending upon your choices.
  7. Click Next.
  8. In the “Additional Details” window shown next, uncheck the check box that says “Use controllers …” given that we’ll be using very little APIs in this example. Leave the “Authentication Type” as “None” (default).
  9. Ensure that the check boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Support” are unattended as we won’t be utilizing any of those features here.
  10. Click Create.

We’ll utilize this ASP.NET Core 6 Web API project to create a minimal API endpoint and carry out JWT authentication for it in the subsequent areas of this article.Create a HTTP Get

endpoint in ASP.NET Core 6

When you develop a new minimal Web API job in Visual Studio 2022, a Program.cs file will be created with a few lines of default code. You can replace the default code with the following code bit to keep things easy and still supply a method to check your API.

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

Note using the RequireAuthorization extension technique here. This helps you protect your paths utilizing authorization policies and forces you to supply authentication info when calling this endpoint. The authorization middleware will use this information to verify the request for the current execution context.If you perform this endpoint without this information, you’ll come across a HTTP 401 Unauthorized mistake as displayed in Figure 1. IDG Figure 1. An HTTP 401 Unapproved error will be created if permission is needed and no authorization details is offered. Install the JwtBearer NuGet bundle Now add

the Microsoft.AspNetCore.Authentication.JwtBearer NuGet plan to your task. To do this, pick the task in the Solution Explorer window,

then right-click and select”Manage NuGet Bundles.” In the NuGet Package Supervisor window, look for the Microsoft.AspNetCore.Authentication.JwtBearer plan and set up it.Alternatively, you can install the package via the NuGet Bundle Manager console by getting in the command revealed below. PM > Install-Package Microsoft.AspNetCore.Authentication.JwtBearer Define a secret key in the appsettings.json file Next, develop a section in the appsettings.json file for the Company, Audience, and Secret info. This information will be utilized later on to create a JSON Web Token. Note that you can offer any name to this area you desire; I’ll use the name”Jwt”for benefit. Add the following details in the appsettings.json file.”Jwt”: “Company “:” https:

Define authentication settings in the Program.cs file The AddAuthenication technique
in the Program.cs file is utilized to configure JWT authentication at the time when the application starts. It specifies the authentication plan as JwtBearer. Furthermore the call to the AddJwtBearer approach helps configure token parameters.The Company

, Audience, and Secret worths read from the appsettings.json config file. The TokenValidationParameters circumstances is used to indicate if the Company, Audience, Key, and Life time info need to be confirmed or not. builder.Services.AddAuthentication (choices=> ). AddJwtBearer(o=> >;); To add authorization services to your application,
your Program.cs need to also consist of the following code snippet.builder.Services.AddAuthorization(); Your Program.cs must also include the following methods to enable authentication and authorization capabilities.app.UseAuthentication( ); app.UseAuthorization(); Develop a user design in ASP.NET Core 6 We will require a class to keep the login qualifications of the user or users. Produce a class called User in a file having the very 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 Finally, we require to write the required code to generate and confirm the JWTs we’ll use to license calls to
the API. Once a token is

created in response to a preliminary request to the API, you can copy it and utilize it for permission in all subsequent requests.Now, compose the following code in the Program.cs file to create a brand-new HTTP Post endpoint that will develop a JWTfor a verified user.app.MapPost(“/ security/createToken “, [AllowAnonymous]( User user)=> if(user.UserName==”joydip “& & user.Password==”joydip123”)var issuer =builder.Configuration [“Jwt: Provider “]; var audience =builder.Configuration [” Jwt: Audience “]; var secret=Encoding.ASCII.GetBytes (builder.Configuration [” Jwt: Key”]; var tokenDescriptor= brand-new SecurityTokenDescriptor >, Issuer=issuer, Audience = audience, SigningCredentials=new SigningCredentials(brand-new SymmetricSecurityKey ( key ), SecurityAlgorithms.HmacSha512Signature); var tokenHandler=brand-new JwtSecurityTokenHandler(); var token=tokenHandler.CreateToken( tokenDescriptor); var jwtToken=tokenHandler.WriteToken(token)
. Each of these is used to create the token,
which we have specified will end in 5 minutes.The complete source code for Program.cs Here is the total source code of the Program.cs declare your reference.using Microsoft.AspNetCore.Authentication.JwtBearer; utilizing Microsoft.AspNetCore.Authorization; using Microsoft.IdentityModel.Tokens; utilizing System.IdentityModel.Tokens.Jwt; using System.Security.Claims; utilizing System.Text;
var home builder =WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(options=> >= JwtBearerDefaults.AuthenticationScheme;
>); builder.Services.AddAuthorization( ); var app=builder.Build();
app.UseHttpsRedirection();
app.MapGet(“/ security/getMessage “,()=>” Hey there World!”
). RequireAuthorization(); app.MapPost(“/ security/createToken”, [AllowAnonymous]( User user)=> if(user.UserName==”joydip”& & user.Password==”joydip123″
JWT authentication in action When you post the user qualifications to the createToken endpoint utilizing Postman, you’ll have the ability to see the created token.< img alt="safe and secure minimal api 02 "width=" 1200"height ="
709 ” src =”https://images.idgesg.net/images/article/2022/08/secure-minimal-api-02-100931045-large.jpg?auto=webp&quality=85,70 “/ > IDG Figure 2. The JWT is produced successfully.
Keep in mind 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 created earlier and pass the produced token as a bearer token in the demand header. If your generated token stands, you’ll see the message shown in Figure 3.< img alt="safe very little api 03
” width=”1200 “height= ” 654″src=”https://images.idgesg.net/images/article/2022/08/secure-minimal-api-03-100931044-large.jpg?auto=webp&quality=85,70″/ > IDG Figure 3. The HTTP Get endpoint returns the text in the response. As you can see in Figure 3, the text message”Hey there World!”is shown because the token we passed is valid. Keep in mind the HTTP 200 OK reaction too(highlighted in a green rectangle). In this example, we hardcoded the user name and password to keep things simple. Of course, you
need to never ever hardcode user qualifications in a production environment. A good choice is to utilize ASP.NET Core 6 Identity to manage user accounts.To test our very little API implementation here, we have actually used Postman, one of the most popular tools available today to test APIs. To evaluate

your minimal API endpoints, you might also utilize Swagger, a toolkit that makes it basic to provide a graphical representation of your API. Copyright © 2022 IDG Communications, Inc.secure minimal api 02 Source

Leave a Reply

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