How to Generate JWT Token in .NET Core

JSON Web Tokens (JWT) are a popular and secure method of authenticating users in a web application. In this article, we will go over the process of generating JWT tokens in a .NET Core application.

How to Generate JWT Token in .NET Core

Learn How to Generate JWT Token in .NET Core

First, you will need to add the following to the appsettings.json file

"Jwt": {
    "Issuer": "https://issuer url/",
    "Audience": "https://audience url/",
    "Key": "This is a sample secret key - please don't use in production environment.'"
  }

Then install the Microsoft.AspNetCore.Authentication.JwtBearer package from NuGet, which provides the necessary functionality for generating and validating JWT tokens in a .NET Core application.

Once the package is installed, you can use the JwtBearerOptions class to configure the JWT token generation. Here is an example of how to set up JWT token generation in a Startup.cs file:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = builder.Configuration["Jwt:Issuer"],
                ValidAudience = builder.Configuration["Jwt:Audience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
            };
        });
}

In this example, the JwtBearerDefaults.AuthenticationScheme is used to specify the default authentication scheme for JWT tokens, and the AddJwtBearer method is used to configure the token generation options. The TokenValidationParameters class is used to specify the validation options for the JWT token, such as the issuer and audience, and the signing key.

Once the JWT token generation is set up, you can use the IAuthenticationService interface to generate a JWT token for a user. Here is an example of how to generate a JWT token for a user in a AccountController:

[HttpPost]
public async Task<IActionResult> Login([FromBody] LoginViewModel model)
{
    // Authenticate the user
    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, model.Email),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
    };

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

    var token = new JwtSecurityToken(_config["Jwt:Issuer"],
      _config["Jwt:Audience"],
      claims,
      expires: DateTime.Now.AddMinutes(30),
      signingCredentials: creds);

    return Ok(new
    {
        token = new JwtSecurityTokenHandler().WriteToken(token)
    });
}

In this example, the JwtSecurityToken class is used to create a new JWT token, with the specified claims, expiration time, and signing credentials. The JwtSecurityTokenHandler class

Final Words

In conclusion, generating JWT tokens in a .NET Core application is a straightforward process. By installing the Microsoft.AspNetCore.Authentication.JwtBearer package, you can configure the JWT token generation and use the IAuthenticationService interface to generate tokens for users. The JwtBearerOptions class and TokenValidationParameters class are used to specify the validation options for the JWT token, such as the issuer, audience, and signing key. Remember to validate the token on the server side and also keep the secret key safe. It's also important to keep in mind that JWT tokens are not encrypted, so sensitive information should not be stored within the payload. Following these steps can help you to implement a secure and reliable JWT token generation system in your .NET Core application.

Post a Comment

Previous Post Next Post