JWT authentication in an ASP.NET Core API

Sagar Kumar
2 min readFeb 20, 2023

--

JWT (JSON Web Tokens) is a popular way to secure web APIs, including ASP.NET Core APIs. Here are the steps to implement JWT authentication in an ASP.NET Core API:

  1. Add the necessary NuGet packages: Microsoft.AspNetCore.Authentication.JwtBearer and System.IdentityModel.Tokens.Jwt.
  2. In the ConfigureServices method of the Startup class, configure authentication by calling the AddAuthentication method and specifying the authentication scheme as JWT bearer:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"]))
};
});

In the Configure method, add authentication middleware to the pipeline:

app.UseAuthentication();

In the ConfigureServices method, configure the JWT authentication options:

services.Configure<JwtOptions>(Configuration.GetSection("Jwt"));

Create a JwtOptions class to hold the JWT configuration options:

public class JwtOptions
{
public string Issuer { get; set; }
public string Audience { get; set; }
public string SecretKey { get; set; }
}

In the Configure method, add authorization middleware to the pipeline:

app.UseAuthorization();

In the ConfigureServices method, configure the authorization policy:

services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.Build();
});

Add the [Authorize] attribute to any controller or action that needs to be secured with JWT authentication.

To generate a JWT token, you can use a library like System.IdentityModel.Tokens.Jwt to create a SecurityToken object and then call its WriteToken method to get the token string:

var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_jwtOptions.SecretKey);
var tokenDescriptor = new SecurityTokenDescriptor
{
Issuer = _jwtOptions.Issuer,
Audience = _jwtOptions.Audience,
Expires = DateTime.UtcNow.AddMinutes(30),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);

These are the basic steps to implement JWT authentication in an ASP.NET Core API. Of course, you may need to customize the implementation based on your specific requirements.

--

--