1 min read

What is JSON Web Token?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

Although JWTs can be encrypted to also provide secrecy between parties, we will focus on signed tokens. Signed tokens can verify the integrity of the claims contained within it, while encrypted tokens hide those claims from other parties. When tokens are signed using public/private key pairs, the signature also certifies that only the party holding the private key is the one that signed it.

When should you use JSON Web Tokens?

Here are some scenarios where JSON Web Tokens are useful:

Authorization: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.

Information Exchange: JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed—for example, using public/private key pairs—you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn’t been tampered with.

Implementing JWT on .NET Core project

Install the package Microsoft.AspNetCore.Authentication.JwtBearer.

You need to add configuration on the Startup.cs or Program.cs

JwtSettings jwtSettings = builder.Configuration.GetJwtSettings();
string key = Encoding.ASCII.GetBytes(jwtSettings.SecretKey);
builder.Services.AddAuthentication(config =>
  {
    config.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    config.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    config.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
  })
  .AddJwtBearer(options =>
  {
    options.SaveToken = true;
    options.RequireHttpsMetadata = false;
    options.TokenValidationParameters = new TokenValidationParameters
    {
      ValidateIssuerSigningKey = true,
      IssuerSigningKey = new SymmetricSecurityKey(key),
      ValidateLifetime = true,
      ValidateIssuer = true,
      ValidateAudience = true,
      ValidAudience = jwtSettings.ValidAudience,
      ValidIssuer = jwtSettings.ValidIssuer
    };
  });

.....
.....

app.UseAuthorization();

Create a service JwtTokenService.cs to generate the Token By GetToken function.

namespace ShadyNagy.ApiTemplate.Infrastructure.Identity;
public class JwtTokenService
{
  private readonly JwtSettings _jwtSettings;

  public JwtTokenService(JwtSettings jwtSettings)
  {
    _jwtSettings = jwtSettings;
  }

  public string GetToken(AuthenticationInfo authenticationInfo)
  {
    var key = Encoding.ASCII.GetBytes(_jwtSettings.SecretKey);
    var claims = new List<Claim>
    {
      new(ClaimTypes.Name, authenticationInfo.FullName),
      new(ClaimTypes.Sid, Guid.NewGuid().ToString()),
      new(ClaimTypes.Email, authenticationInfo.Email),
      new(ClaimTypes.PrimarySid, authenticationInfo.Code),
      new(ClaimTypes.NameIdentifier, authenticationInfo.UserName)
    };

    var tokenDescriptor = new SecurityTokenDescriptor
    {
      Subject = new ClaimsIdentity(claims.ToString()),
      Expires = DateTime.UtcNow.AddDays(1),
      SigningCredentials =
        new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
      Issuer = _jwtSettings.ValidIssuer,
      Audience = _jwtSettings.ValidAudience
    };

    var tokenHandler = new JwtSecurityTokenHandler();
    var token = tokenHandler.CreateToken(tokenDescriptor);

    return tokenHandler.WriteToken(token);
  }
}

Create the interface IJwtTokenService.cs

namespace ShadyNagy.ApiTemplate.Core.Interfaces;
public interface IJwtTokenService
{
  string GetToken(AuthenticationInfo authenticationInfo);
}

We need to add this service on the Startup.cs or Program.cs

builder.Services.AddScoped<IJwtTokenService, JwtTokenService>();

If you want to secure any Endpoint you have to add the attribute [Authorize] in the class.

namespace ShadyNagy.ApiTemplate.Api.Endpoints.BranchEndpoints;

[Authorize]
public class Add : BaseAsyncEndpoint
    .WithRequest<AddBranchRequest>
    .WithResponse<BranchDto>
{
  private readonly IMapper _mapper;
  private readonly IReadRepository<Branch> _readRepository;
  private readonly IRepository<Branch> _repository;

  public Add(IMapper mapper, IReadRepository<Branch> readRepository, IRepository<Branch> repository)
  {
    _mapper = mapper;
    _readRepository = readRepository;
    _repository = repository;
  }

  [HttpPost(AddBranchRequest.Route)]
  [SwaggerOperation(
      Summary = "Adds a branch",
      Description = "Adds a branch",
      OperationId = "Branch.Add",
      Tags = new[] { "BranchesEndpoints" })
  ]
  public override async Task<ActionResult<BranchDto>> HandleAsync([FromBody] AddBranchRequest branchDto, CancellationToken cancellationToken = default)
  {
    var entityToSave = _mapper.Map<Branch>(branchDto);

    var addedEntity = await _repository.AddAsync(entityToSave, cancellationToken);

    var response = _mapper.Map<BranchDto>(addedEntity);

    return Ok(response);
  }
}

If you want to use the full example you can find it here https://github.com/ShadyNagy/ShadyNagy.ApiTemplate
Click here if you want to use ShadyNagy.ApiTemplate.
Feel free to comment if there are any problems or questions.

About the author

For the last decade, Shady Nagy has worked with a variety of web technologies. He is currently focused on code quality. On his day to day job, he is working as a team leader engineer. As a digital nomad, he is living where the WiFi and sun are 😎
Do you want to know more? Visit my website!