Create and validate own Json-Web-Tokens (JWTs)

image1929-570x143_thumb.png

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: }


Explanation

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.

 

image

This code is of course also available on GitHub.

Read more

Micro-Optimization: how to shrink or „embed“ pictures

  I’m currently working on the “CodeInside Dashboard” and since the page structure isn’t that difficult it should be possible to fulfill all of Google Pagespeed or Yahoos YSlow recommendations. One of the rules was to optimize the 4 PNGs that are embedded on the page.   Before – without optimization: Below you can see […]

Read more

Move to Windows Azure – VMs, Word Press Migration, DNS changes

image1979-570x194.png

Since mid January this blogs runs on a WordPress installation in an Azure VM. Because I always thought that the subject is quite complicated this blogpost offers a view behind the scenes. Why this move? So far this blog (both German and English Version) runs on a hoster somewhere in Germany. The main problem with this […]

Read more

Windows Azure Active Directory – CRUD for users and groups

  Windows Azure Active Directory? If you are not informed about the subject I recommend you to have a look on this Azure Info site. Which resources are there? The Azure AD contains the following entities: – Users – Groups – Contacts – Roles Access to the directory or on the “directory graph” Although the […]

Read more

Introduction into SignalR 2.0 & Azure Website Websockets

  SignalR is an Open Source Framework for Real Time WebApps. The main problem with Real-Time in the web is the canal between Browser and Server. If you never had to deal with SignalR and this problem before here is a brief introduction:   The problem Traditionally the browser initiates the request to the server […]

Read more

ESENT – the „ancient NoSQL DB“ made by Windows

  Those of you who use RavenDB might have heard about ESENT already. In the inside RavenDB uses the “Extensible Storage Engine” which is included into Windows since XP. Read here why Ayende is looking for an alternative for a while – although ESENT is basically reliable but that’s just a side note. ESENT is […]

Read more

Caller Information with .NET 4.5 or „Who touched the function?“

  Debugging and Logging Code are usually full of function names and so on just so you are able to find the right place in the code at the end. Of course there are several other reasons to find out who was the last one to open the code. The interface INotifyPropertyChanged is such an […]

Read more

OWIN, Katana & One ASP.NET

This was the topic of the .NET User Group Zurich meeting last Wednesday and I want to share my presentation with the demo code and some links that I found during my research. Presentation on SpeakerDeck Link to Speaker Deck. Demo Code The complete demo code is available on our GitHub Repo. Background information A […]

Read more

Internal tools – cheap and tasteless?

  A common German saying is „the shoe maker always wears the worst pair of shoes!“ – that’s also true for the IT business. Usually internal tools or services are developed lukewarm and without the required professionalism.   The basic idea – everything for the customer! The time you might spend on “polishing” those projects […]

Read more

TFS API: Query Build-Definitions

The Team Foundation Server offers On-Premise and as „Cloud-TFS“ (Team Foundation Server) (German-Blogpost) several services (Build, WorkItems, Source Control,…). Those services are easy to use with the help of .NET APIs. In this blogpost I try to call the last build results of a team-project. Required assemblies To request a build you won’t need all […]

Read more

Recent Posts

  • image1929-570x143_thumb.png
    Create and validate own Json-Web-Tokens (JWTs)

    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 […]

  • Micro-Optimization: how to shrink or „embed“ pictures

      I’m currently working on the “CodeInside Dashboard” and since the page structure isn’t that difficult it should be possible to fulfill all of Google Pagespeed or Yahoos YSlow recommendations. One of the rules was to optimize the 4 PNGs that are embedded on the page.   Before – without optimization: Below you can see […]

  • image1979-570x194.png
    Move to Windows Azure – VMs, Word Press Migration, DNS changes

    Since mid January this blogs runs on a WordPress installation in an Azure VM. Because I always thought that the subject is quite complicated this blogpost offers a view behind the scenes. Why this move? So far this blog (both German and English Version) runs on a hoster somewhere in Germany. The main problem with this […]

  • Windows Azure Active Directory – CRUD for users and groups

      Windows Azure Active Directory? If you are not informed about the subject I recommend you to have a look on this Azure Info site. Which resources are there? The Azure AD contains the following entities: - Users - Groups - Contacts - Roles Access to the directory or on the “directory graph” Although the […]

  • Introduction into SignalR 2.0 & Azure Website Websockets

      SignalR is an Open Source Framework for Real Time WebApps. The main problem with Real-Time in the web is the canal between Browser and Server. If you never had to deal with SignalR and this problem before here is a brief introduction:   The problem Traditionally the browser initiates the request to the server […]

Support us