aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.UnitTesting/Web/JWT_Tokens_TST.cs
blob: 6f97e1c4e60ca66b8f68347da1c5e9ff71a3cfb2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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<TokenObject>.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<TokenObject>.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<SignatureVerificationException>(() =>
            {
                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<TokenExpiredException>(() => read_web_token.Validate(secret));
        }
    }
}