Click here to Skip to main content
15,890,845 members
Articles / Programming Languages / C#
Tip/Trick

Create and Consume JWT Tokens in C#

Rate me:
Please Sign up or sign in to vote.
3.73/5 (11 votes)
30 Sep 2017CPOL 164.1K   11   10
How to create and consume JWT tokens in C#

Introduction

There are plenty of materials on how to manage JWT tokens in C# environment.

But I found most of them are either too complicated for the beginner or outdated.
In this example, we will create and read a JWT token using a simple console app, so we can get a basic idea of how we can use it in any type of projects.

Let's create a simple console project and add these libraries as references:

C#
System.IdentityModel;  
System.Security 

Next, we will need JWT Tokens Package.

Nuget  install-package  "System.IdentityModel.Tokens.Jwt"   

Now we are ready to play with JWT Tokens:

C#
static void Main(string[] args)
       {
           Console.WriteLine("");

           // Define const Key this should be private secret key  stored in some safe place
           string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b372742
           9090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";

           // Create Security key  using private key above:
           // not that latest version of JWT using Microsoft namespace instead of System
           var securityKey = new Microsoft
               .IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));

           // Also note that securityKey length should be >256b
           // so you have to make sure that your private key has a proper length
           //
           var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
                             (securityKey, SecurityAlgorithms.HmacSha256Signature);

           //  Finally create a Token
           var header = new JwtHeader(credentials);

           //Some PayLoad that contain information about the  customer
           var payload = new JwtPayload
           {
               { "some ", "hello "},
               { "scope", "http://dummy.com/"},
           };

           //
           var secToken = new JwtSecurityToken(header, payload);
           var handler = new JwtSecurityTokenHandler();

           // Token to String so you can use it in your client
           var tokenString = handler.WriteToken(secToken);

           Console.WriteLine(tokenString);
           Console.WriteLine("Consume Token");


           // And finally when  you received token from client
           // you can  either validate it or try to  read
           var token = handler.ReadJwtToken(tokenString);

           Console.WriteLine(token.Payload.First().Value);

           Console.ReadLine();
       }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionComment correction Pin
JonathanSeattle29-Jul-21 8:53
JonathanSeattle29-Jul-21 8:53 
QuestionHow to know if the signature is valid? Pin
denko8313-Nov-20 5:44
denko8313-Nov-20 5:44 
AnswerRe: How to know if the signature is valid? Pin
Nordestino Brasileiro11-Apr-23 10:14
Nordestino Brasileiro11-Apr-23 10:14 
PraiseThanks for the sample Pin
rhinosoft00729-Sep-18 2:51
rhinosoft00729-Sep-18 2:51 
GeneralMy vote of 5 Pin
nospam19615-Jul-18 3:27
nospam19615-Jul-18 3:27 
BugInvalid Signature when testing with JWT.io Pin
Member 137056642-Mar-18 7:55
Member 137056642-Mar-18 7:55 
GeneralRe: Invalid Signature when testing with JWT.io Pin
Member 120782261-May-18 12:10
Member 120782261-May-18 12:10 
GeneralRe: Invalid Signature when testing with JWT.io Pin
Member 137056648-May-18 7:07
Member 137056648-May-18 7:07 
GeneralRe: Invalid Signature when testing with JWT.io Pin
Marc Foulke 202325-May-23 5:51
Marc Foulke 202325-May-23 5:51 
QuestionHow to Decode Header Payload & Signature Pin
Member 1370266028-Feb-18 19:05
Member 1370266028-Feb-18 19:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.