create jwt token in csharp

Here's an example of how to create a JWT token in C# using the System.IdentityModel.Tokens.Jwt package:

main.cs
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;

public class JwtTokenGenerator
{
    public static string GenerateJwtToken(string secret, string issuer, string audience, int expireMinutes, params Claim[] claims)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
        var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

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

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}
796 chars
25 lines

To generate a token, you can call the GenerateJwtToken method and pass in the required parameters:

main.cs
var token = JwtTokenGenerator.GenerateJwtToken(
    secret: "{your-secret-key}",
    issuer: "{your-issuer}",
    audience: "{your-audience}",
    expireMinutes: 60,
    new Claim[] {
        new Claim("userId", "1234"),
        new Claim("userName", "john.doe")
    }
);
272 chars
11 lines

This will generate a JWT token with the specified claims and an expiration time of 60 minutes. Don't forget to replace {your-secret-key}, {your-issuer}, and {your-audience} with your desired values.

gistlibby LogSnag