DEV Community

Nick
Nick

Posted on

Encode and Decode JWTs in C#

JWT (JSON Web Tokens) have become widely adopted for securely transmitting information between parties in a compact and self-contained manner. In C#, it is relatively straightforward to encode and decode JWTs using the System.IdentityModel.Tokens.Jwt library.

To encode a JWT, you need to create a JwtSecurityToken object with the necessary claims and signing credentials. Claims contain the relevant data, such as user information or access permissions. The signing credentials are used to ensure the integrity and authenticity of the token.

Here's a simple example for encoding a JWT:

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

// Create claims for the token
var claims = new[]
{
    new Claim("userId", "123"),
    new Claim("role", "admin")
};

// Create signing credentials
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"));
var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

// Create JWT
var token = new JwtSecurityToken(
    issuer: "your_issuer",
    audience: "your_audience",
    claims: claims,
    expires: DateTime.UtcNow.AddMinutes(10), // Token expiration time
    signingCredentials: signingCredentials
);

// Encode the JWT
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(token);
Enter fullscreen mode Exit fullscreen mode

Decoding the JWT is equally straightforward:

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

// Decode JWT
var handler = new JwtSecurityTokenHandler();
var token = handler.ReadToken(encodedJwt) as JwtSecurityToken;

// Validating token
var validationParameters = new TokenValidationParameters
{
    ValidIssuer = "your_issuer",
    ValidAudience = "your_audience",
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"))
};

SecurityToken validatedToken;
var principal = handler.ValidateToken(encodedJwt, validationParameters, out validatedToken);
Enter fullscreen mode Exit fullscreen mode

In the above example, we validate the token using parameters matching the original encoding configuration. If validation is successful, the decoded token is stored in validatedToken, and the principal contains the user claims.

Encoding and decoding JWTs in C# using the System.IdentityModel.Tokens.Jwt library allows for secure and efficient data transmission while ensuring data integrity and authenticity.

Top comments (0)