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?
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
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
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.
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.
As a token handler, the JWTSecurityTokenHandler can be used to create and validate JWT tokens, as shown by the next example
|public void First()|
|var tokenHandler = new JWTSecurityTokenHandler();|
|var symmetricKey = GetRandomBytes(256/8);|
|var now = DateTime.UtcNow;|
|var tokenDescriptor = new SecurityTokenDescriptor|
|Subject = new ClaimsIdentity(new Claim|
|new Claim(ClaimTypes.Name, "Pedro"),|
|new Claim(ClaimTypes.Role, "Author"),|
|TokenIssuerName = "self",|
|AppliesToAddress = "http://www.example.com",|
|Lifetime = new Lifetime(now, now.AddMinutes(2)),|
|SigningCredentials = new SigningCredentials(|
|var token = tokenHandler.CreateToken(tokenDescriptor);|
|var tokenString = tokenHandler.WriteToken(token);|
|var validationParameters = new TokenValidationParameters()|
|AllowedAudience = "http://www.example.com",|
|SigningToken = new BinarySecretSecurityToken(symmetricKey),|
|ValidIssuer = "self"|
|var principal = tokenHandler.ValidateToken(tokenString, validationParameters);|
|.Any(c => c.Type == ClaimTypes.Name && c.Value == "Pedro"));|
|.Any(c => c.Type == ClaimTypes.Role && c.Value == "Author"));|
- 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).
The first part contains the JWT Header
The second part contains the claims, including the audience, issuer and validity
Finally, the third part is the signature value, computed by the MAC algorithm over the first two parts.