JSON Web Tokens and the new JWTSecurityTokenHandler class

Last week, Vittorio Bertocci announced the developer preview of the new JWT Security Token Handler, which provides support for a important piece of the modern identity and access control management puzzle.

What are security tokens?

In the context of the claims model, a security token is an interoperable  container of security-related information, typically identity claims, securely packaged for communication between two or more parties. This packaging ensures properties such as:

  • Confidentiality – only the authorized receiver should be able to access the contained information
  • Integrity – the authorized receiver should be able to detect any modifications to token, while in transit between the two parties.

On Web Single-Sign On protocols, security tokens are used to securely transport the identity information from the identity provider to the identity consumer. On a delegated authorization protocol, such as OAuth 2.0, security tokens can be used to convey the authorization information from the client to the resource server.

For instance, the SAML (Security Assertion Markup Language) assertion is an example of a very popular token format, used by  Single-Sign On protocols such as: Shibboleth, the SAML protocols and WS-Federation. SAML assertions are XML-based and use the XML Digital Signature and XML Encryption standards for providing integrity and confidentiality.

What is JWT?

JWT stands for  JSON Web Token, and is a new format for packing and protecting security information. It is based on the JSON (JavaScript Object Notation) syntax and aims to be usable in “space constrained environments such as HTTP Authorization headers and URI query parameters”.

The following example (taken from the spec), represents a unprotected token (line breaks added for display purposes)

eyJhbGciOiJub25lIn0
.
eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ

 

The encoded token is composed by a sequence of parts, separated by the ‘.’ character. Each part is the base64url encoding of an octet stream. In this example, both octet stream result from the UTF-8 encoding of JSON objects. The first object (encoded in the first part) is the JWT header

{“alg”:”none”}

The header defines the token cryptographic protection, which is ‘none’ in this case.

The second object (encoded in the second part) is the JWT Claims Set

{“iss”:”joe”,

“exp”:1300819380,

http://example.com/is_root”:true}

The JWT Claims Set object is a container of claims, where the object’s property corresponds to the claim type and the property’s value contains the claims value. Some claims types are defined by the JWT spec (e.g. “iss” and “exp”), while others are context specific (e.g. “http://example.com/is_root”).

We will see more examples of JWT tokens after presenting the JWT Security Token Handler.

What are Security Token Handlers?

Security Token Handlers are a concept introduced by the  WIF (Windows Identity Foundation) framework, which is now an integral part of the .NET 4.5 framework. A token handler has multiple responsibilities, namely:

  • Serialize and deserialize tokens between a XML or string format and a SecurityToken-derived instance;
  • Validate security tokens and extract the contained claims into a claims identity or a claims principal;
  • Create a token from a token description.

This behavior is defined by the abstract SecurityTokenHandler class, with multiple concrete derived classes for each token type (e.g. the Saml2SecurityTokenHandler class).

The JTWSecurityTokenHandler class

The recently announced Microsoft.IdentityModel.Tokens.JWT NuGet package contains a new token handler for the JWT token format – the JWTSecurityTokenHandler class – depicted in the next diagram.

TokenHandlers

As a token handler,  the JWTSecurityTokenHandler can be used to create and validate JWT tokens, as shown by the next example

 

 

  • First, we create a token handler and a symmetric key, that will be used by both the sending and the receiving party to sign and validate the token, respectively.
  • Then, we create a token descriptor, defining the token contents, namely:
    • The contained claims, i.e., the subject of the token,
    • The token issuer name,
    • The intended recipient of the token (AppliesToAddress),
    • The token lifetime, defined by a not before and an expires date-time,
  • The token descriptor also contains the signing credentials, namely the symmetric key and the MAC (Message Authentication Code) algorithm identifier (“http://www.w3.org/2001/04/xmldsig-more#hmac-sha256”).
  • Then, we use the token handler to create the token from the token descriptor. We also use the token handler to serialize the token into a string.
  • On the receiving side, we begin by defining the validation parameters, namely:
    • The allowed audience, i.e., the value defined in the AppliestoAddress property of the token descriptor. This value should be an identifier of the receiving party.
    • The validation cryptographic, in the form of a BinarySecretSecurityToken containing the shared symmetric key.
    • The name of the accepted issuer.
  • Finally, we use the token handler to simultaneously deserialize the token, validate its signature and extract the contained claims into a claims principal.
  • We end the example by asserting that the claims principal does contains the Name and Role claims inserted in the token by the issuer.

 

The serialized token is just the concatenation of three base64url encoded parts (line breaks added for display purposes).

 

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9

.

eyJhdWQiOiJodHRwOi8vd3d3LmV4YW1wbGUuY29tIiwiaXNzIjoic2VsZiIsIm5iZiI6MTM1Mzk3NDczNiwi

ZXhwIjoxMzUzOTc0ODU2LCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5

L2NsYWltcy9uYW1lIjoiUGVkcm8iLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYv

aWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJBdXRob3IifQ

.

a-Tu5ojQSyiGSzTb9E5QbEYxyhomywzh2wqKs4El7lc

 

The first part contains the JWT Header

{“typ”:”JWT”,”alg”:”HS256″}

The second part contains the claims, including the audience, issuer and validity

{“aud”:”http://www.example.com”,

“iss”:”self”,”nbf”:1353973142,”exp”:1353973262,

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name“:”Pedro”,

http://schemas.microsoft.com/ws/2008/06/identity/claims/role”:”Author”}

Finally, the third part is the signature value, computed by the MAC algorithm over the first two parts.

9 thoughts on “JSON Web Tokens and the new JWTSecurityTokenHandler class

  1. Pingback: WIF JWT hotair « Peter's ruminations

  2. peter

    How about how you leverage this in a WCF Service? .. I imagine one can use the extention methothds of “ChannelFactory Token” extension methods to pass it across … but it is not clear to me on the Service how you get the Service to use JWT and extract the Claims

    Reply
  3. Pingback: Eigene Json-Web-Tokens (JWTs) erstellen und validieren | Code-Inside Blog

  4. Bruce Patin

    SecurityTokenDescriptor and Lifetime are missing. I installed nuget “Windows Identity Foundation”, which got me reference for Microsoft.IdentityModel, then “JSON Web Token Handler For the Microsoft .Net Framework 4.5” which go me a reference for System.IdentityModel.Tokens. My using statements are:

    using System.IdentityModel.Tokens;
    using System.Security.Claims;
    using System.Security.Cryptography;

    When I try to add using Microsoft.IdentityModel, I get error that IdentityModel is not part of Microsoft.

    I feel inclined to try some other source of token handling that is maintained properly.

    Reply
  5. Bruce Patin

    I installed “Microsoft HTTP Client Libraries”, “Microsoft ASP.NET Identity Core” (prerelease) and a second time installed “Windows Identity Foundation”. This time, without changing any of my user statements, Visual Studio 2013 now accepts SecurityTokenDescriptor.

    Reply
  6. Bruce Patin

    I discovered that using Microsoft.IdentityModel.Tokens hides the SecurityTokenDescriptor, which is apparently provided by using System.IdentityModel.Tokens.

    Reply
  7. Pingback: Create and validate own Json-Web-Tokens (JWTs) | Code-Inside Blog International

  8. Pingback: JSON Web Token (JWT) Introduction for REST | Techartifact

  9. Philani

    Hi,

    Any idea why my following class libraries are mising after installing Install-Package System.IdentityModel.Tokens.Jwt via packate manager:
    1.InMemorySymmetricSecurityKey
    2.BinarySecretSecurityToken
    3.ValidateToken

    Please assist thanks.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s