using JWT; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Tango.Web.Security; namespace Tango.UnitTesting.Web { [TestClass] [TestCategory("Web")] public class JWT_Tokens_TST { private class TokenObject { public String Name { get; set; } public int Age { get; set; } } [TestMethod] public void Test_JWT_Tokens_Read_Write_Validation() { string secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk"; //Create new web token with embedded object. Expiration in 2 seconds. var webToken = WebToken.CreateNew(secret, new TokenObject() { Name = "Roy", Age = 35 }, DateTime.UtcNow.AddSeconds(2)); //Get the actual string token. String token = webToken.AccessToken; //Validate the string token using the secret. WebToken.Validate(secret, token); //Read the token payload (Expiration, Issued, Embedded Object).. var read_web_token = WebToken.FromToken(token); //Validate the token again using the web token instance (Just to see if the method is working..) read_web_token.Validate(secret); //Validate the token payload reading.. Assert.AreEqual(read_web_token.Expiration.Value.ToString("hh:mm"), webToken.Expiration.Value.ToString("hh:mm")); Assert.AreEqual(read_web_token.Issued.ToString("hh:mm"), webToken.Issued.ToString("hh:mm")); Assert.AreEqual(read_web_token.Object.Name, webToken.Object.Name); Assert.AreEqual(read_web_token.Object.Age, webToken.Object.Age); //Ensure token validation fails when messing with the token string. Assert.ThrowsException(() => { WebToken.Validate(secret, token.Substring(0, token.Length - 1) + "0"); }); //Wait for the token to expire... Thread.Sleep(2000); //Ensure the token validation fails with 'token expired'. Assert.ThrowsException(() => read_web_token.Validate(secret)); } } }