logo

,

Creating JWT Tokens in .NET 7 Web API: A Step-by-Step Guide with Code Snippets

JSON Web Tokens (JWT) are a popular method for securely transmitting information between parties as a JSON object. JWTs can be used for a wide range of scenarios, including authentication, authorization, and data exchange. In this tutorial, we’ll look at how to create a JWT token in .NET 7 Web API.

Step 1: Install Required Packages

Before we start, we need to install the required NuGet packages for JWT authentication in .NET 7 Web API. We can install them using the NuGet package manager or by adding them to the project file.

Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 7.0.0
Install-Package Microsoft.IdentityModel.Tokens -Version 6.15.0

Step 2: Configure Authentication

Next, we need to configure authentication in our Web API project. We can do this by adding the following code in the Program.cs:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

// ...

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.RequireHttpsMetadata = false;
    options.SaveToken = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(builder.Configuration["Jwt:SecretKey"])),
        ValidateIssuer = false,
        ValidateAudience = false
    };
});

In this code, we’re configuring JWT authentication by adding the JwtBearer middleware to our authentication pipeline. We’re also specifying the parameters for token validation, including the secret key that we’ll use to sign and verify the token.

Note that we’re storing the secret key in the appsettings.json file and retrieving it using the IConfiguration interface. You can modify this to suit your own needs.

Step 3: Create a Token Generator Service

Now that we’ve set up authentication, we can create a service that generates JWT tokens. We can do this by creating a class that implements an interface with a GenerateToken method. Here’s an example implementation:

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;

public interface ITokenGeneratorService
{
    string GenerateToken(string username, string role);
}

public class TokenGeneratorService : ITokenGeneratorService
{
    public string GenerateToken(string username, string role)
    {
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"]));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, username),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            new Claim(ClaimTypes.Role, role)
        };

        var token = new JwtSecurityToken(
            issuer: null,
            audience: null,
            claims: claims,
            expires: DateTime.UtcNow.AddMinutes(30),
            signingCredentials: credentials);

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}

In this code, we’re creating a TokenGeneratorService class that implements the ITokenGeneratorService interface. The GenerateToken method takes a username and a role as parameters and returns a JWT token as a string.

We’re creating a SymmetricSecurityKey object from our secret key and using it to create SigningCredentials. We’re then defining some claims.

Claims are basically a name-value pair that contains claim name and claim value. Claims are pieces of information that are encoded within the token itself. In general, claims provide a way to transmit information about the user, the token itself, or other contextual data. When the token is decoded, the claims can be read and used to make authorization or authentication decisions.

Once the claims are defined, then we are generating the token and returning it.

Don’t forget to checkout: 5 Steps to Generate QR Codes in Asp.net Core

Step 4: Use the Token Generator Service in a Controller

Finally, we can use the TokenGeneratorService in a controller to generate a JWT token for a user. Here’s an example controller that uses the TokenGeneratorService to generate a token:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

[Route("api/[controller]")]
[ApiController]
public class TokenController : ControllerBase
{
    private readonly ITokenGeneratorService _tokenGeneratorService;

    public TokenController(ITokenGeneratorService tokenGeneratorService)
    {
        _tokenGeneratorService = tokenGeneratorService;
    }

    [AllowAnonymous]
    [HttpPost]
    public IActionResult GenerateToken([FromBody] TokenRequestModel model)
    {
        var token = _tokenGeneratorService.GenerateToken(model.Username, model.Role);

        return Ok(new { token });
    }
}

public class TokenRequestModel
{
    public string Username { get; set; }
    public string Role { get; set; }
}

In this code, we’re creating a TokenController that has a single GenerateToken action. The action takes a TokenRequestModel as input, which contains a username and a role. We’re then using the TokenGeneratorService to generate a JWT token for the user and returning it as an object in the response.

Note that we’re also using the AllowAnonymous attribute on the action to allow unauthenticated access. You can modify this to suit your own needs.

Conclusion

In this tutorial, we looked at how to create a JWT token in .NET 7 Web API using the Microsoft.AspNetCore.Authentication.JwtBearer and Microsoft.IdentityModel.Tokens packages. We created a TokenGeneratorService that generates a token from a username and a role, and used it in a controller to generate a token for a user. By following these steps, you can implement JWT authentication in your .NET 7 Web API and securely transmit information between parties.

Don’t forget to check out this awesome udemy course: .NET Core Microservices – The Complete Guide (.NET 6 MVC)

Share on facebook
Share on twitter
Share on linkedin

Related articles