Last active
March 18, 2016 12:57
-
-
Save ansariabr/9aba87b15cb72bb917f6 to your computer and use it in GitHub Desktop.
Encoding and Decoding JWT using JWT library(https://www.nuget.org/packages/JWT/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using JWT; | |
namespace MyJWTUtility | |
{ | |
public static class JWTUtility | |
{ | |
/// <summary> | |
/// Generate Token(Or encode payload) Using HS256 Algorithm | |
/// </summary> | |
/// <param name="payload"></param> | |
/// <returns></returns> | |
public static string Encode(object payload) | |
{ | |
string secretKey = "somethingvERYdifficultSecretKey1234"; | |
return JWT.JsonWebToken.Encode(payload, secretKey, JWT.JwtHashAlgorithm.HS256); | |
} | |
/// <summary> | |
/// Decode token(which was encoded with HS256 algorithm) | |
/// </summary> | |
/// <param name="token"></param> | |
/// <returns></returns> | |
public static string DecodeToken(string token) | |
{ | |
string secretKey = "somethingvERYdifficultSecretKey1234"; | |
return JWT.JsonWebToken.Decode(token, secretKey); | |
} | |
} | |
public class MyJWT() | |
{ | |
public string Field1 { get; set; } | |
public string Field2 { get; set; } | |
public double exp { get; set; } | |
} | |
public class TestClass() | |
{ | |
public static string GenerateJWT() | |
{ | |
MyJWT myJWTObject=new MyJWT(); | |
var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); | |
var expiryTime = Math.Round((DateTime.UtcNow.AddMinutes(5) - unixEpoch).TotalSeconds);//Set Expiry time accordingly | |
myJWTObject.Field1 = "SomeRandomValue"; | |
myJWTObject.Field2 = "AgainSomeRandomValue"; | |
myJWTObject.exp = expiryTime; | |
//Generated JWT with 5 minutes expiry time | |
return JWTUtility.GetToken(myJWTObject); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment