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:
- Develop a minimal API project in Visual Studio 2022.
- Produce an API endpoint in the Program.cs file.
- Include the Microsoft.AspNetCore.Authentication.JwtBearer NuGet package to our project.
- Execute JWT authentication in the Program.cs file.
- Develop a user model class named User to keep the login qualifications of the user.
- Specify a secret type in the appsettings.json file.
- Define JWT authentication settings in the Program.cs file.
- Include authorization services middleware to our application in the Program.cs file.
- 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:
- Launch the Visual Studio 2022 IDE.
- Click “Produce brand-new job.”
- In the “Develop new task” window, choose “ASP.NET Core Web API” from the list of templates showed.
- Click Next.
- In the “Configure your new task” window, specify the name and place for the brand-new project.
- Optionally check the “Place service and task in the very same directory” check box, depending upon your choices.
- Click Next.
- 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).
- 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.
- 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();
() => “Hey there World!”). RequireAuthorization();
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