Skip to content

Instantly share code, notes, and snippets.

@SIRHAMY
Created March 22, 2017 18:22
Show Gist options
  • Save SIRHAMY/72abbbc44ef876e2e8d24be52d22caf9 to your computer and use it in GitHub Desktop.
Save SIRHAMY/72abbbc44ef876e2e8d24be52d22caf9 to your computer and use it in GitHub Desktop.
Example of how to use Microsoft's System.IdentityModel.Tokens.Jwt to create a JWT Token
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Linq
using System.Text;
using Microsoft.IdentityModel.Tokens;
public class JwtTokenCreator
{
private readonly JwtSecurityTokenHandler _jwtSecurityTokenHandler;
public JwtTokenCreator()
{
this._jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
}
public string GenerateJwtToken(string secretKey, IReadOnlyDictionary<string, string> payloadContents, string encryptionAlgorithm)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
var signingCredentials = new SigningCredentials(securityKey, encryptionAlgorithm);
var payloadClaims = payloadContents.Select(c => new Claim(c.Key, c.Value));
var payload = new JwtPayload(payloadClaims);
var header = new JwtHeader(signingCredentials);
var securityToken = new JwtSecurityToken(header, payload);
return this._jwtSecurityTokenHandler.WriteToken(securityToken);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment