Created
March 22, 2017 18:22
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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