JSON Web Token (JWT) Handler for .NET
Before diving into the Code, let’s have some basic information about JWT.
JWT stands for “JSON Web Token”, pronounced as “JOT”. According to Wikipedia:
“JSON Web Token (JWT)is a JSON-based open standard (RFC 7519) for passing claims between parties in web application environment. The tokens are designed to be compact, URL-safe and usable especially in web browser single sign-on (SSO) context. JWT claims can be typically used to pass identity of authenticated users between an identity provider and a service provider, or any other type of claims as required by business processes. The tokens can also be authenticated and encrypted.”
JWT FORMAT is simple, it’s a string that is composed of three parts, separated by a “.” (dot). Each part is the base64url encoding of an octet stream. The third part is the signature value, computed by the MAC algorithm over the first two parts. Here is the graphical representation of JWT.
JWT EXAMPLE
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.
eyJ1bmlxdWVfbmFtZSI6IltBbnkgTmFtZV0iLCJyb2xlIjoiW0FueSBSb2xlXSIsImlzcyI6IltUb2tlbiBJc3N1ZXIgTmFtZV0iLCJhdWQiOiJodHRwOi8vd3d3Lm1pY3Jvc29
mdC5jb20iLCJleHAiOjE0NDcxMzM2NTcsIm5iZiI6MTQ0NzEzMDA1N30.
u97MWuNbHxKXFXOoC04A0k8QFdCY8P4ym2K2pL5L-WM
JWT DECODER can be used to decode Token in readable form. Copy and paste the above Token (including dots) to this website and it will decode the Token to JSON format:
IMPLEMENTATION
Now, let’s write some code to generate and verify JWT using Microsoft JSON Web Token Handler.
1) Open Visual Studio > Create a New Website
2) In the Solution Explorer > Right Click the Website Name and select “Manage NuGet Packages”
3) Search “JWT Token Handler” in the search box and hit “Install”.
4) This will add “System.IdentityModel.Tokens.Jwt.dll” to the reference/bin folder.
5) Reference following namespaces in your Class
using System.IdentityModel.Protocols.WSTrust; using System.IdentityModel.Tokens; using System.Security.Claims; using System.ServiceModel.Security.Tokens; using System.Text;
6) Add following method to your Class to generate JWT
public string GetJWToken() { // Create Jwt Security Token Handler Object var tokenHandler = new JwtSecurityTokenHandler(); // Symmetric key must be atleast 128 bits long string symmetricKey = "This is the Symmetric Key"; // Declare Time Out variable, value is in minutes. double tokenTimeOut = 30; // Get Current Date Time for expiry Date var currentDT = DateTime.Now; // Creating Token Description part var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, "[Any Name]"), new Claim(ClaimTypes.Role, "[Any Role]"), }), TokenIssuerName = "[Token Issuer Name]", AppliesToAddress = "http://www.microsoft.com", // define lifetime of the token Lifetime = new Lifetime(currentDT, currentDT.AddMinutes(tokenTimeOut)), // Create Signing Credentials // Param 1 : signing key // Param 2 : signature algorithm // Param 3 : digest algorithm SigningCredentials = new SigningCredentials( new InMemorySymmetricSecurityKey(Encoding.ASCII.GetBytes(symmetricKey)), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256") }; // Create Token var token = tokenHandler.CreateToken(tokenDescriptor); // convert Token to string var tokenString = tokenHandler.WriteToken(token); return tokenString; }
7) Add following method to your Class to verify JWT
public bool VerifyJWT(string token) { var tokenHandler = new JwtSecurityTokenHandler(); // Create symmetric key with the random number and prefix in web.config var symmetricKey = "This is the Symmetric Key"; // validation parameters, JWtValidator requires this object to validate the token. var validationParameters = new TokenValidationParameters() { ValidAudience = "http://www.microsoft.com", // Same as AppliesToAddress IssuerSigningToken = new BinarySecretSecurityToken(Encoding.ASCII.GetBytes(symmetricKey)), ValidIssuer = "[Token Issuer Name]", // same as Token Issuer Name RequireExpirationTime = true, ValidateLifetime = true, ValidateAudience = true, ValidateIssuer = true, ValidateIssuerSigningKey = true, }; SecurityToken validatedToken; try { // if token is valid, it will output the validated token that contains the JWT information // otherwise it will throw an exception var principal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken); } catch (Exception ex) { return false; } return true; }
8) Add 2 buttons on the web page, one for generating JWT and other for verifying Token.
9) Add a Text Box to display the generated Token.
10) Add a label to display the status of Token.
OUTPUT
– Click on “Generate JWT”
– Click on “Validate JWT”
ONE LAST THING, the Token expiration time…
As, in this example, the life time of the Token is “30 mins” but when you test this, Token will expire after 35 mins. So, from where this 5 mins added to the Token life time? To fix this, we need to set another property of class TokenValidationParameters i.e. “ClockSkew” to Zero.
Default Value of TokenValidationParameters.ClockSkew is 5
Let’s modify “VerifyJWT” method and set this property.
// validation parameters, JWtValidator requires this object to validate the token. var validationParameters = new TokenValidationParameters() { ValidAudience = "http://www.microsoft.com", // Same as AppliesToAddress IssuerSigningToken = new BinarySecretSecurityToken(Encoding.ASCII.GetBytes(symmetricKey)), ValidIssuer = "[Token Issuer Name]", // same as Token Issuer Name RequireExpirationTime = true, ValidateLifetime = true, ValidateAudience = true, ValidateIssuer = true, ValidateIssuerSigningKey = true, ClockSkew = TimeSpan.Zero // default value of this property is 5, it adds 5 mins to the expiration time. };
That’s all !
I hope, you will find this article useful.