JWT Authentication in C# .NET Core 7 Web API — .NET Essentials

Sajad Shafi
3 min readJan 31, 2024

--

An introduction to the JWT Authentication in C# .NET Core — with this comprehensive article you will learn how you can easily implement jwt auth in C# .Net core.

Introduction

While developing a .NET core web API project, we may have come across a step where we needed to secure the APIs that we created so that they could only be accessed by authenticated users. Json Web Token abbreviated as JWT is a popular way of authenticating .NET core web APIs.

JSON Web Token

JSON web token(JWT) is an open industry standard (RFC 7519) for transmitting data securely between parties in the form of a JSON object. The main advantages of using a JWT are that it is more compact and therefore has a smaller size. It is secure and can use a shared secret between an issuer and a consumer. It uses the JSON format. Almost every programming language has a JSON parser, so you do not have to reinvent the wheel.

JSON web token has three parts:

  • Header
  • Payload
  • Signature

Header

The header is a combination of two parts

  • Type of token which is JWT
  • The signing Algorithm that is being used such as RSA or SHA256. Example:
{
"type":"JWT",
"alg":"RSA"
}

Payload

The second part of the JSON web token is payload which contains claims. Claims are some information about the user e.g: userId, email, username, etc. Example:

{
"userId":"868fd4e7-80a5-4b61-b212-1daa41a51936",
"email":"example@test.com"
}

Signature

Signature validates the sender’s authenticity. Signature is created by encoding the header, payload, a secret, and the algorithm defined in the header.

Let’s now configure JSON web token (JWT) authentication with a .NET Core 7 API.

Install dependencies

Install the Microsoft.AspNetCore.Authentication.JwtBearer NuGet package. This package provides the necessary components to use JWT authentication in your .NET Core API.

Configure Services

After the packages is installed successfully we need to configure the Authentication service in the Program.cs that will configure the jwt_authentication:

builder.Services.AddAuthentication(cfg => {
cfg.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
cfg.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
cfg.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x => {
x.RequireHttpsMetadata = false;
x.SaveToken = false;
x.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8
.GetBytes(configuration["ApplicationSettings:JWT_Secret"])
),
ValidateIssuer = false,
ValidateAudience = false,
ClockSkew = TimeSpan.Zero
};
});

the above code will configure the jwt_authentication in the .NET core API. It sets the default authentication as JWT and sets up JWT using the jwt_secret. This code configures the JWT authentication handler and specifies the authority that will issue the JWT tokens. The TokenValidationParameters property can be used to specify additional validation rules for the JWT tokens, such as the ValidateAudience flag which determines whether the audience (aud) claim in the token should be validated. It uses a jwt_secret that is added in the applicationSettings.json.

Add JWT_Secret in the appsettings file

Add a section in you applicationSettings.json file as:

"ApplicationSettings": {
"JWT_Secret": "this_is_my_dummy_secret"
},

You can configure appsettings seperately for development and production version of your project:

"ApplicationSettings": {
"JWT_Secret": "dummy_secret_for_development_mode"
},
"ApplicationSettings": {
"JWT_Secret": "dummy_secret_for_production_mode"
},

Generate a JSON web token

Now lets write a funcitons that generates a JSON web token. Create a folder and name it helpers inside this folder create a file and call it AuthHelpers.cs and write the following code:

public string GenerateJWTToken(SystemUser user) {
var claims = new List<Claim> {
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Name),
};
var jwtToken = new JwtSecurityToken(
claims: claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddDays(30),
signingCredentials: new SigningCredentials(
new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(configuration["ApplicationSettings:JWT_Secret"])
),
SecurityAlgorithms.HmacSha256Signature)
);
return new JwtSecurityTokenHandler().WriteToken(jwtToken);
}

This function will generate a JSON web token. In the claims I usually add userId and User’s name. We can add more details to the claims like, Username, Roles, etc. The generated token will expire in 30 days.

Enable Authentication

In Program.cs file, add the following line of code to enable authentication for your API:

app.UseAuthentication();

The above line should be added before the following lines:

app.UseAuthorization();
app.MapControllers();
app.Run();

This will enable the JWT authentication handler for all requests to your API.

Secure API

To require authentication for a specific route or controller, use the [Authorize] attribute:

[Authorize]
[Route("api/[controller]")]
public class ValuesController : Controller
{
// ...
}

This will require a valid JWT token to be present in the request in order to access the controller or its actions.

That’s it! You should now have JWT authentication configured in your .NET Core 7 API.

--

--

Sajad Shafi

Software engineer by profession experienced in C#, .Net, JavaScript Typescript, ReactJS and SQL.