06 April 2014 Auth, JSON CI Team

If you are interested in web authentication you probably have heard about JSON Web tokens (JWT).

What is a JWT?

Maybe I’m not using the correct security termination but however: JWTs are used to exchange claims between two systems. For example: You want to log on to a service (like Facebook, Twitter, etc.) and want to have a look on your informations. As an answer you receive a JWT including the authenticated and authorized user. Basically a claim is a Key/Value pair which you can fill with whatever you want.

The full specification includes more information.

Why JWTs?

If you are running your own authentication system and want to offer an OAuth interface (for Apps) you have to think about how your clients could log themselves onto the system. The JWT might be a good transportation medium.

Create and validate own JWTs

With the .NET Framework 4.5 and JSON Web Token Handler NuGet Package it is possible to validate tokens from other services or create your own. 99% of the code are from this blog which offers other helpful information about security and HTTP.


1: // Code source is from this awesome blog: 2: // http://pfelix.wordpress.com/2012/11/27/json-web-tokens-and-the-new-jwtsecuritytokenhandler-class/ 3: class Program 4: { 5: static void Main(string[] args) 6: { 7: var securityKey = GetBytes("ThisIsAnImportantStringAndIHaveNoIdeaIfThisIsVerySecureOrNot!"); 8: 9: var tokenHandler = new JwtSecurityTokenHandler(); 10: 11: // Token Creation 12: var now = DateTime.UtcNow; 13: var tokenDescriptor = new SecurityTokenDescriptor 14: { 15: Subject = new ClaimsIdentity(new Claim[] 16: { 17: new Claim(ClaimTypes.Name, "Pedro"), 18: new Claim(ClaimTypes.Role, "Author"), 19: }), 20: TokenIssuerName = "self", 21: AppliesToAddress = "http://www.example.com", 22: Lifetime = new Lifetime(now, now.AddMinutes(2)), 23: SigningCredentials = new SigningCredentials( 24: new InMemorySymmetricSecurityKey(securityKey), 25: "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", 26: "http://www.w3.org/2001/04/xmlenc#sha256"), 27: }; 28: var token = tokenHandler.CreateToken(tokenDescriptor); 29: 30: // Generate Token and return string 31: var tokenString = tokenHandler.WriteToken(token); 32: Console.WriteLine(tokenString); 33: 34: // Token Validation 35: var validationParameters = new TokenValidationParameters() 36: { 37: AllowedAudience = "http://www.example.com", 38: SigningToken = new BinarySecretSecurityToken(securityKey), 39: ValidIssuer = "self" 40: }; 41: 42: // from Token to ClaimsPrincipal - easy! 43: var principal = tokenHandler.ValidateToken(tokenString, validationParameters); 44: 45: Console.WriteLine(principal.Claims.Single(x => x.Type == ClaimTypes.Name).Value); 46: 47: Console.ReadLine(); 48: } 49: 50: static byte[] GetBytes(string str) 51: { 52: byte[] bytes = new byte[str.Length * sizeof(char)]; 53: System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); 54: return bytes; 55: 56: } 57: }

The first step is the creation of a SecurityKey which is necessary for the TokenHandler. In this case it is a symmetric key which means both parties need the whole key. The JWT can be saved with different methods (like certificates).

Enter a ClaimsPrincipal with the Token Handler – we want to read this Claims later.

The token is created with all parameters and with the same parameters and the key we will make the token readable again.

It is also possible to exchange this token between server applications or app and service.

The picture shows the output of the program: the token and at the end the “name”-Claim.



This code is of course also available on GitHub.