Created
January 17, 2019 10:19
-
-
Save fabiorecife/4a818e2cd1b381efab152b2eb4e9a108 to your computer and use it in GitHub Desktop.
How to generate JWT Token with C# - Hello World version ( jwt.io )
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; | |
| using System.IdentityModel.Tokens.Jwt; | |
| using System.Security.Claims; | |
| using System.Text; | |
| using Microsoft.IdentityModel.Tokens; | |
| namespace ConsoleApp3 | |
| { | |
| class Program | |
| { | |
| public static string buildJwtToken(string base64Key) | |
| { | |
| var tokenHandler = new JwtSecurityTokenHandler(); | |
| var now = DateTime.UtcNow; | |
| var securityKey = Convert.FromBase64String(base64Key); | |
| var tokenDescriptor = new SecurityTokenDescriptor | |
| { | |
| Subject = new ClaimsIdentity(new[] | |
| { | |
| new Claim( "sub","Example", ClaimValueTypes.String, "example" ) | |
| }), | |
| Issuer = "example", | |
| Audience = "https://www.example.com", | |
| Expires = now.AddMinutes(3), | |
| SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(securityKey), | |
| SecurityAlgorithms.HmacSha256), | |
| }; | |
| var token = tokenHandler.CreateToken(tokenDescriptor); | |
| var tokenString = tokenHandler.WriteToken(token); | |
| return tokenString; | |
| } | |
| static void Main(string[] args) | |
| { | |
| Console.WriteLine("version: Hello World!"); | |
| var base64Key = "MWNhMzA4ZGY2Y2RiMGE4YmY0MGQ1OWJlMmExN2VhYzE="; | |
| Console.WriteLine(buildJwtToken(base64Key)); | |
| Console.WriteLine("base64 key " + base64Key); | |
| Console.WriteLine(Encoding.ASCII.GetString(Convert.FromBase64String(base64Key))); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment