Implementing JWT in ASP.NET Core 6.0 Web API (C#)

Kendrick
Bina Nusantara IT Division
5 min readSep 30, 2022
Photo by Christopher Burns on Unsplash

JSON Web Token (JWT) is an open standard used to share information between two parties. The information of JWT is encoded as JSON containing claims or signatures.

When creating an API endpoint that executes operations such as creating or deleting important data, we don’t want the endpoint to be freely accessible by everyone. Using JWT as an authentication method is a way to achieve this.

Prerequisites

.NET 6.0
Visual Studio

Creating a new project

Open Visual Studio and click Create a new project. Choose “ASP.NET Core Web API”. Because we will use the C# language, pick the first choice which has the C# tag and icon.

If this option is unavailable, install “ASP.NET and web development” features from Visual Studio Installer.

Enter your project name, location, and solution name. I will use “SimpleJWT” as the project and solution name.

We will use .NET 6.0 Framework. Leave everything except “Use controllers” unticked because we are not using these options in this tutorial.

The generated project will have this structure.

WeatherForecastController has a method “Get” which will return the randomly generated weather forecast for the next 5 days.

You can run the API and hit the endpoint directly without authentication. We used Postman for testing the API endpoint.

Implementing JWT

First, Install “Microsoft.AspNetCore.Authentication.JwtBearer” NuGet package.

Let’s add the following line in “appsettings.json

"Jwt": {
"Issuer": "Issuer",
"Audience": "Audience",
"Key": "bd1a1ccf8095037f361a4d351e7c0de65f0776bfc2f478ea8d312c763bb6caca"
}

This will define the configuration which is needed to implement JWT. Notes: The key used in this tutorial are randomly generated for example purposes, Do not use this for the production environment.

Add the following code below “builder.Services.AddControllers();” in “Program.cs

builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey (Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = false,
ValidateIssuerSigningKey = true
};
});
builder.Services.AddAuthorization();// Add configuration from appsettings.json
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();

The above code defines the Authentication Schema for JWT which we will use as an authentication method for our API. The code will use the JWT configuration we defined in “appsetting.json

Then, add the following lines below “app.UseAuthentication();”.

app.UseAuthorization();IConfiguration configuration = app.Configuration;IWebHostEnvironment environment = app.Environment;

The resulting “Program.cs” file should look like this

Let’s create a “User” Model to store the Username and Password which we will usefor authorization.

Create a new Controller “AuthController” which we will use to authorize the user and return the JWT Token.

For the sake of simplicity, we will create an Auth method that validates the email “test@email.com” and password “a” and create a JWT token.

var issuer = configuration["Jwt:Issuer"];
var audience = configuration["Jwt:Audience"];
var key = Encoding.UTF8.GetBytes(configuration["Jwt:Key"]);
var signingCredentials = new SigningCredentials(
new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha512Signature
);

The code above retrieves the Issuer, Audience, and Key which we defined in “appsettings.json. We will “signingCredentials” variable to store SigningCredentials with SymmetricSecurityKey created from our key and use the HmacSha512 security algorithm.

var subject = new ClaimsIdentity(new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Email, user.UserName),
});

The variable “subject” is used to store Claims. In This tutorial, we will generate the Claim of Sub and Email from the username.

var expires = DateTime.UtcNow.AddMinutes(10);

Create a variable to contain the expiration date for the token.

var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = subject,
Expires = DateTime.UtcNow.AddMinutes(10),
Issuer = issuer,
Audience = audience,
SigningCredentials = signingCredentials
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var jwtToken = tokenHandler.WriteToken(token);

Finally, create a “tokenDescriptor” with the previously defined variable. Use JwtSecurityTokenHandler to create a token from the “tokenDescriptor”. Then use the “WriteToken” method to return the string value of the JWT

To make our endpoint requires authorization. Add the [Authorize] tag above the Get Method in WeatherForecast Controller

Now hit the WeatherForecast endpoint again. You will get an Error 401 Unauthorized message.

Let’s use the auth endpoint we created earlier to get the token and use it to hit the WeatherForecast endpoint.

Copy the resulting token and use it in the Authorization Header with the Bearer token schema)

Authorization: Bearer <token>

If you are using postman, click the “Authorization” Tab and choose “Bearer Token”. Paste the token inside the Token input field.

After setting up the Authorization Header, Hit the Weather Forecast endpoint again.

Voila, we successfully implemented JWT in our ASP.NET Core 6.0 Web API.
We only discussed the implementation of JWT. To read more about the specification you can read it here.

The full source code of this tutorial is available here. Thank you for reading.

--

--