Examples of JWT Token Generation & Verification in C#

Examples of JWT Token Generation & Verification in C#

Nowadays, web applications and APIs rely heavily on security and authentication. JSON Web Tokens (JWT) have become the standard for transmitting user information and authorizing requests. This article focuses on working with JWT tokens in C# programming language, specifically generating and validating them using the System.IdentityModel.Tokens.Jwt library. This tutorial will teach you how to create and validate JWT tokens, which offer security and authentication benefits for your application. Let’s begin!

What is JWT?

JWT or JSON Web Token is a standard open token format used to exchange information between two parties in JSON format. It is commonly used for user authentication and authorization in web applications and APIs, as well as for transferring data about users and other entities.

JWT consists of three parts:

  1. Header: This section contains information about the token type (JWT) and the signature algorithm (e.g., HMAC, SHA256, or RSA).
  2. Payload: It contains claims about the user or other data. Claims can include information about the user, access rights, and other user data.
  3. Signature: This section contains a signature created from the header and payload using a secret key. The signature is used to authenticate the token.

Library Installation

To work with JWT in C#, you need to install the System.IdentityModel.Tokens.Jwt library. You can do this by using the NuGet Package Manager in Visual Studio or by using the following command in a console:

Install-Package System.IdentityModel.Tokens.Jwt

How to Create a JWT Token

To create a JWT token, first import the required namespaces:

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

You can then create a method to generate the JWT token:

public string GenerateJwtToken(string secretKey, string issuer, string audience, int expireMinutes = 30)
{
    var securityKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(secretKey));
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

    var claims = new[]
    {
        new Claim(ClaimTypes.Name, "Tomas Anderson"),
        new Claim(ClaimTypes.Email, "tomas.anderson@amarozka.dev"),
        // Other custom data (claims)
    };

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

    var tokenHandler = new JwtSecurityTokenHandler();
    return tokenHandler.WriteToken(token);
}

In this example, the secretKey is used to sign the token, while issuer and audience are used to specify the publisher and audience of the token, respectively. Additionally, expireMinutes is used to specify the lifetime of the token in minutes.

How to Verification and Parsing of JWT Token

To parse and verify a JWT token, use the following code:

public bool ValidateJwtToken(string token, string secretKey, string issuer, string audience)
{
    var tokenHandler = new JwtSecurityTokenHandler();
    var securityKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(secretKey));

    var tokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidIssuer = issuer,
        ValidateAudience = true,
        ValidAudience = audience,
        ValidateLifetime = true,
        IssuerSigningKey = securityKey
    };

    try
    {
        SecurityToken validatedToken;
        tokenHandler.ValidateToken(token, tokenValidationParameters, out validatedToken);
        return true;
    }
    catch
    {
        return false;
    }
}

This method validates and parses the token using the specified validation settings.

Example of Usage

Here is an example of how to use the created methods:

class Program
{
    static void Main(string[] args)
    {
        string secretKey = "your_secret_key";
        string issuer = "your_issuer";
        string audience = "your_audience";

        JwtService jwtService = new JwtService();

        // Generating JWT token
        string jwtToken = jwtService.GenerateJwtToken(secretKey, issuer, audience);

        Console.WriteLine($"JWT token: {jwtToken}");

        // Verification and Parsing of JWT Token
        bool isValid = jwtService.ValidateJwtToken(jwtToken, secretKey, issuer, audience);

        if (isValid)
        {
            Console.WriteLine("The token has been successfully validated and parsed.");
        }
        else
        {
            Console.WriteLine("The token is invalid or the parsing process has failed.");
        }
    }
}

This code generates a JWT token containing user data, which can be used to authenticate and authorize users in your web application or API. It is important to keep the secret key secure.

Leave a Reply

Your email address will not be published. Required fields are marked *