Wednesday, 20 November 2024

JWT Token Generation Code in C#

Install the required NuGet packages

You'll need the following packages in your C# project:

  • System.IdentityModel.Tokens.Jwt (for JWT token generation and validation)
  • Microsoft.IdentityModel.Tokens (for creating signing keys and algorithms)

Set up the JWT Token Generation Code

Here’s an example of how to generate a JWT token in C# using various options:

public string GenerateJwtToken(string username)
{
     // Define JWT claims
    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, "userid"), // Registered Claims
        new Claim(JwtRegisteredClaimNames.Name, username), // Registered Claims
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim("role", "admin"), // Custom Claims
        new Claim("email", "johndoe@example.com") // Custom Claims
    };

    //  Define the security key
    string secretKey = "your_secret_key_here";
    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));

     // Define the signing credentials (HMACSHA256 algorithm)
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

// Create jwt token
    var token = new JwtSecurityToken(
        issuer: "your-issuer", // Can be your app name
        audience: "your-audience", // Can be a target application or service
        claims: claims,
        expires: DateTime.Now.AddMinutes(30),
        signingCredentials: creds);

     // Serialize the token to a string
     var tokenHandler = new JwtSecurityTokenHandler();
     string jwtToken = tokenHandler.WriteToken(token);

    return jwtToken ;
}

Explanation of the Options Used:

  1. Security Key and Signing Credentials:

    • A secret key is used to sign the token. It's crucial to keep this key secure. We use the HMACSHA256 algorithm (SecurityAlgorithms.HmacSha256) to sign the token with the SymmetricSecurityKey.
  2. Claims:

    • Claims are used to include information about the user (e.g., sub, name) and other custom claims (e.g., role, email). Claims are represented as Claim objects.
  3. Issuer and Audience:

    • Issuer: The entity that issued the token, often the name of the app or service that generates the token.
    • Audience: The recipient(s) of the token, often a service or application that will validate the token.
  4. Expiration Time:

    • You can set the expiration time for the token using expires. The token will be invalid once the expiration date is reached.
  5. JWT Token Generation:

    • We use JwtSecurityToken to construct the JWT with all the provided information (issuer, audience, claims, expiration time, and signing credentials).
  6. Serialize the Token:

    • JwtSecurityTokenHandler is used to serialize the JwtSecurityToken object into a string that can be used as the actual JWT token.

3. Customization Options

You can customize the JWT further with the following options:

  1. Audience:

    • If your token is intended for a specific service or client, you can set the audience to that service's identifier.
  2. Signing Algorithms:

    • You can use different signing algorithms like HmacSha256, Rs256, Es256, etc., depending on your use case.

      Example for RSA or ECDSA signing:
      var rsaKey = new RsaSecurityKey(privateKey); // Private RSA key
      var signingCredentials = new SigningCredentials(rsaKey, SecurityAlgorithms.RsaSha256);
  3. Claims: JWT tokens allow you to add custom claims (e.g., roles, permissions, etc.). You can add any additional claim that might be useful for your system's authorization.

  4. NotBefore (nbf): Set the NotBefore claim to indicate that the token is not valid before a certain time: 
    nbf: DateTime.UtcNow.AddMinutes(1)
  5. Issuer & Audience Validation:

    • On the validation side, when you decode the token, you can specify the allowed Issuer and Audience values to ensure that the token is intended for your service.
  6. Example of Token Validation:

    Once you have generated the token, you would typically validate it on the receiving side:

var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = new TokenValidationParameters
{
    ValidateIssuer = true,
    ValidateAudience = true,
    ValidateLifetime = true,
    ValidIssuer = "your-issuer",
    ValidAudience = "your-audience",
    IssuerSigningKey = symmetricKey // Same key used to sign the token
};

try
{
    var principal = tokenHandler.ValidateToken(jwtToken, validationParameters,
out SecurityToken validatedToken);
    Console.WriteLine("Token is valid.");
}
catch (SecurityTokenException ex)
{
    Console.WriteLine("Token validation failed: " + ex.Message);
}

Conclusion

By following this approach, you can generate a highly customizable JWT token in C# using multiple options, such as custom claims, signing algorithms, and expiration times. You can further extend this with more advanced features like refreshing tokens, audience validation, and different signing algorithms for more complex security needs.


0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives