Generating and Validating JSON Web Tokens in .NET

Generating and Validating JSON Web Tokens in .NET
Photo by Shubham Dhage / Unsplash

JSON Web Tokens (JWT) are used for secure information exchange between systems, commonly used for Authentication and Authorization. A JWT consists of three parts:

  • Header - specifies the token type and signing algorithm (e.g. HMAC SHA256)
  • Payload - contains claims and user specific information
  • Signature - which ensures the token hasn't been tampered with. That is, the signature verifies the token's integrity and authenticity.

An example JWT is available on JWT.io - a website for decoding and verifying JWTs.

With JWTs, there is no need for server side session storage since JWTs are stateless and can be passed through HTTP headers.

Let's explore how to generate and validate a JWT with a basic .NET console application.

💡
The code sample is available in the GitHub repository

This method generates a JWT.

private static string GenerateToken(string secret)
{
    var signingCredentials = new SigningCredentials(
        new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)), 
        SecurityAlgorithms.HmacSha256);

    var claims = new List<Claim>
    {
        new("sub", "321"),
        new("name", "Luke Skywalker"),
        new("email", "luke.skywalker@starwars.com")
    };

    var jwtSecurityToken = new JwtSecurityToken
        (
            "https://starwars.com",  // Issuer
            "https://starwarsapi",   // Audience
            claims,
            DateTime.UtcNow,
            DateTime.UtcNow.AddMinutes(30),
            signingCredentials
        );

    return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
}
  • It accepts a secret string to create signing credentials using HMAC-SHA256
  • It defines a list of claims with a subject (sub), name, and email
  • A JwtSecurityToken is created with an issuer (https://starwars.com) and an audience (https://starwarsapi)
  • The token's validity is set from the current UTC time to 30 minutes into the future
  • The JwtSecurityToken is signed with the provided secret
  • The JwtSecurityTokenHandler is used to write the token as a string
  • The function returns the serialized JWT token as a string

This method validates the JWT.

    private static bool ValidateToken(string token, string secret)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var validationParameters = new TokenValidationParameters()
        {
            ValidateIssuer = true,
            ValidIssuer = "https://starwars.com",
            ValidateAudience = true,
            ValidAudience = "https://starwarsapi",
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret))
        };

        SecurityToken validatedToken;

        IPrincipal principal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);

        return true;
    }
  • It accepts a token and a secret for validation
  • A JwtSecurityTokenHandler is created to handle the token
  • Validation parameters are set, including issuer, audience, and signing key
  • The ValidateToken method checks the token's validity using the provided parameters
  • If the token is valid, the method returns true

The verified token on JWT.io