JsonWebToken.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. namespace Jwt
  6. {
  7. /// <summary>
  8. /// Encoding and decoding for JSON Web Tokens.
  9. /// </summary>
  10. public static class JsonWebToken
  11. {
  12. /// <summary>
  13. /// Gets or sets the <see cref="IJsonSerializer"/> implementation being used.
  14. /// </summary>
  15. public static IJsonSerializer JsonSerializer = new DefaultJsonSerializer();
  16. private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
  17. /// <summary>
  18. /// Creates a JWT using the specified payload and key hashed with <see cref="JwtHashAlgorithm.HS256 "/>.
  19. /// </summary>
  20. /// <param name="payload">An arbitrary payload (must be serializable to JSON).</param>
  21. /// <param name="key">The key bytes used to sign the token.</param>
  22. /// <returns>The generated JWT.</returns>
  23. public static string Encode(object payload, byte[] key)
  24. => Encode(new JwtData { Payload = payload, KeyBytes = key, Algorithm = JwtHashAlgorithm.HS256 });
  25. /// <summary>
  26. /// Creates a JWT using the specified payload, key and algorithm.
  27. /// </summary>
  28. /// <param name="payload">An arbitrary payload (must be serializable to JSON).</param>
  29. /// <param name="key">The key bytes used to sign the token.</param>
  30. /// <param name="algorithm">The hash algorithm to use.</param>
  31. /// <returns>The generated JWT.</returns>
  32. public static string Encode(object payload, byte[] key, JwtHashAlgorithm algorithm)
  33. => Encode(new JwtData { Payload = payload, KeyBytes = key, Algorithm = algorithm });
  34. /// <summary>
  35. /// Creates a JWT using the specified payload and key hashed with <see cref="JwtHashAlgorithm.HS256 "/>.
  36. /// </summary>
  37. /// <param name="payload">An arbitrary payload (must be serializable to JSON).</param>
  38. /// <param name="key">The key used to sign the token.</param>
  39. /// <returns>The generated JWT.</returns>
  40. public static string Encode(object payload, string key)
  41. => Encode(new JwtData { Payload = payload, Key = key, Algorithm = JwtHashAlgorithm.HS256 });
  42. /// <summary>
  43. /// Creates a JWT using the specified payload, key and algorithm.
  44. /// </summary>
  45. /// <param name="payload">An arbitrary payload (must be serializable to JSON).</param>
  46. /// <param name="key">The key used to sign the token.</param>
  47. /// <param name="algorithm">The hash algorithm to use.</param>
  48. /// <returns>The generated JWT.</returns>
  49. public static string Encode(object payload, string key, JwtHashAlgorithm algorithm)
  50. => Encode(new JwtData { Payload = payload, Key = key, Algorithm = algorithm });
  51. /// <summary>
  52. /// Creates a JWT using the specified <see cref="JwtData"/>.
  53. /// </summary>
  54. /// <param name="data">A <see cref="JwtData"/> object.</param>
  55. /// <returns>The generated JWT.</returns>
  56. public static string Encode(JwtData data)
  57. {
  58. var header = new Dictionary<string, object>(data.ExtraHeaders ?? new Dictionary<string, object>())
  59. {
  60. { "typ", "JWT" },
  61. { "alg", data.Algorithm.ToString() }
  62. };
  63. var headerBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(header));
  64. var payloadBytes = Encoding.UTF8.GetBytes(data.Serialized ? (string)data.Payload : JsonSerializer.Serialize(data.Payload));
  65. var segments = new List<string>
  66. {
  67. Base64UrlEncode(headerBytes),
  68. Base64UrlEncode(payloadBytes)
  69. };
  70. var bytesToSign = Encoding.UTF8.GetBytes(string.Join(".", segments));
  71. var keyBytes = data.KeyBytes;
  72. if (keyBytes == null || keyBytes.Length == 0)
  73. {
  74. keyBytes = Encoding.UTF8.GetBytes(data.Key);
  75. }
  76. var signature = ComputeHash(data.Algorithm, keyBytes, bytesToSign);
  77. segments.Add(Base64UrlEncode(signature));
  78. return string.Join(".", segments);
  79. }
  80. /// <summary>
  81. /// Decodes the specified JWT and returns the JSON payload.
  82. /// </summary>
  83. /// <param name="token">The JWT.</param>
  84. /// <param name="key">The key that was used to sign the JWT.</param>
  85. /// <param name="verify">Whether to verify the signature (default is true).</param>
  86. /// <returns>A string containing the JSON payload.</returns>
  87. /// <exception cref="SignatureVerificationException">
  88. /// If the <paramref name="verify"/> parameter was true and the signature was not valid
  89. /// or if the JWT was signed with an unsupported algorithm.
  90. /// </exception>
  91. /// <exception cref="ArgumentException">
  92. /// When the given <paramref name="token"/> doesn't consist of 3 parts delimited by dots.
  93. /// </exception>
  94. public static string Decode(string token, string key, bool verify = true)
  95. => Decode(token, Encoding.UTF8.GetBytes(key), verify);
  96. /// <summary>
  97. /// Decodes the JWT token and deserializes JSON payload to a dictionary.
  98. /// </summary>
  99. /// <param name="token">The JWT.</param>
  100. /// <param name="key">The key that was used to sign the JWT.</param>
  101. /// <param name="verify">Whether to verify the signature (default is true).</param>
  102. /// <returns>An object representing the payload.</returns>
  103. /// <exception cref="SignatureVerificationException">
  104. /// If the <paramref name="verify"/> parameter was true and the signature was not valid
  105. /// or if the JWT was signed with an unsupported algorithm.
  106. /// </exception>
  107. /// <exception cref="ArgumentException">
  108. /// When the given <paramref name="token"/> doesn't consist of 3 parts delimited by dots.
  109. /// </exception>
  110. public static Dictionary<string, object> DecodeToObject(string token, string key, bool verify = true)
  111. => DecodeToObject<Dictionary<string, object>>(token, key, verify);
  112. /// <summary>
  113. /// Decodes the JWT token and deserializes JSON payload to a dictionary.
  114. /// </summary>
  115. /// <param name="token">The JWT.</param>
  116. /// <param name="key">The key that was used to sign the JWT.</param>
  117. /// <param name="verify">Whether to verify the signature (default is true).</param>
  118. /// <returns>An object representing the payload.</returns>
  119. /// <exception cref="SignatureVerificationException">
  120. /// If the <paramref name="verify"/> parameter was true and the signature was not valid
  121. /// or if the JWT was signed with an unsupported algorithm.
  122. /// </exception>
  123. /// <exception cref="ArgumentException">
  124. /// When the given <paramref name="token"/> doesn't consist of 3 parts delimited by dots.
  125. /// </exception>
  126. public static Dictionary<string, object> DecodeToObject(string token, byte[] key, bool verify = true)
  127. => DecodeToObject<Dictionary<string, object>>(token, key, verify);
  128. /// <summary>
  129. /// Decodes the JWT token and deserializes JSON payload to <typeparamref name="T"/>.
  130. /// </summary>
  131. /// <typeparam name="T">The type of the object.</typeparam>
  132. /// <param name="token">The JWT.</param>
  133. /// <param name="key">The key that was used to sign the JWT.</param>
  134. /// <param name="verify">Whether to verify the signature (default is true).</param>
  135. /// <returns>An object representing the payload.</returns>
  136. /// <exception cref="SignatureVerificationException">
  137. /// If the <paramref name="verify"/> parameter was true and the signature was not valid
  138. /// or if the JWT was signed with an unsupported algorithm.
  139. /// </exception>
  140. /// <exception cref="ArgumentException">
  141. /// When the given <paramref name="token"/> doesn't consist of 3 parts delimited by dots.
  142. /// </exception>
  143. public static T DecodeToObject<T>(string token, string key, bool verify = true)
  144. => DecodeToObject<T>(token, Encoding.UTF8.GetBytes(key), verify);
  145. /// <summary>
  146. /// Decodes the JWT token and deserializes JSON payload to <typeparamref name="T"/>.
  147. /// </summary>
  148. /// <typeparam name="T">The <see cref="Type"/> to return</typeparam>
  149. /// <param name="token">The JWT.</param>
  150. /// <param name="key">The key that was used to sign the JWT.</param>
  151. /// <param name="verify">Whether to verify the signature (default is true).</param>
  152. /// <returns>An object representing the payload.</returns>
  153. /// <exception cref="SignatureVerificationException">
  154. /// If the <paramref name="verify"/> parameter was true and the signature was not valid
  155. /// or if the JWT was signed with an unsupported algorithm.
  156. /// </exception>
  157. /// <exception cref="ArgumentException">
  158. /// When the given <paramref name="token"/> doesn't consist of 3 parts delimited by dots.
  159. /// </exception>
  160. public static T DecodeToObject<T>(string token, byte[] key, bool verify = true)
  161. => JsonSerializer.Deserialize<T>(Decode(token, key, verify));
  162. /// <summary>
  163. /// Decodes the specified JWT and returns the JSON payload.
  164. /// </summary>
  165. /// <param name="token">The JWT.</param>
  166. /// <param name="key">The key bytes that were used to sign the JWT.</param>
  167. /// <param name="verify">Whether to verify the signature (default is true).</param>
  168. /// <returns>A string containing the JSON payload.</returns>
  169. /// <exception cref="SignatureVerificationException">
  170. /// If the <paramref name="verify"/> parameter was true and the signature was not valid
  171. /// or if the JWT was signed with an unsupported algorithm.
  172. /// </exception>
  173. /// <exception cref="ArgumentException">
  174. /// When the given <paramref name="token"/> doesn't consist of 3 parts delimited by dots.
  175. /// </exception>
  176. public static string Decode(string token, byte[] key, bool verify = true)
  177. {
  178. var parts = token.Split('.');
  179. if (parts.Length != 3)
  180. {
  181. throw new ArgumentException($"Token must consist of 3 parts delimited by dot. Given token: '{token}'.", nameof(token));
  182. }
  183. // Decode JWT payload
  184. var payload = parts[1];
  185. var payloadBytes = Base64UrlDecode(payload);
  186. var payloadJson = Encoding.UTF8.GetString(payloadBytes);
  187. if (verify)
  188. {
  189. // Decode JWT header.
  190. var header = parts[0];
  191. var headerBytes = Base64UrlDecode(header);
  192. var headerJson = Encoding.UTF8.GetString(headerBytes);
  193. // Decode the signature from the JWT.
  194. var jwtSignature = UrlDecode(parts[2]);
  195. // Compute the signature for the JWT.
  196. var headerData = JsonSerializer.Deserialize<IDictionary<string, object>>(headerJson);
  197. var algorithm = (string)headerData["alg"];
  198. var bytesToSign = Encoding.UTF8.GetBytes(string.Concat(header, ".", payload));
  199. var signature = ComputeHash(GetHashAlgorithm(algorithm), key, bytesToSign);
  200. var computedSignature = Convert.ToBase64String(signature);
  201. Verify(jwtSignature, computedSignature, payloadJson);
  202. }
  203. return payloadJson;
  204. }
  205. private static void Verify(string jwtSignature, string computedSignature, string payloadJson)
  206. {
  207. // Compare the signature from the JWT and the computed signature.
  208. if (jwtSignature != computedSignature)
  209. {
  210. throw new SignatureVerificationException("Invalid JWT signature.");
  211. }
  212. // Verify exp claim: https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.4
  213. var payloadData = JsonSerializer.Deserialize<IDictionary<string, object>>(payloadJson);
  214. if (payloadData.TryGetValue("exp", out var expObj) && expObj != null)
  215. {
  216. // Safely unpack a boxed int.
  217. int exp;
  218. try
  219. {
  220. exp = Convert.ToInt32(expObj);
  221. }
  222. catch (Exception)
  223. {
  224. throw new SignatureVerificationException($"Claim 'exp' must be an integer. Given claim: '{expObj}'.");
  225. }
  226. var secondsSinceEpoch = Math.Round((DateTime.UtcNow - UnixEpoch).TotalSeconds);
  227. if (secondsSinceEpoch >= exp)
  228. {
  229. throw new SignatureVerificationException("Token has expired.");
  230. }
  231. }
  232. }
  233. private static byte[] ComputeHash(JwtHashAlgorithm algorithm, byte[] key, byte[] value)
  234. {
  235. HashAlgorithm hashAlgorithm;
  236. switch (algorithm)
  237. {
  238. case JwtHashAlgorithm.HS256:
  239. hashAlgorithm = new HMACSHA256(key);
  240. break;
  241. case JwtHashAlgorithm.HS384:
  242. hashAlgorithm = new HMACSHA384(key);
  243. break;
  244. case JwtHashAlgorithm.HS512:
  245. hashAlgorithm = new HMACSHA512(key);
  246. break;
  247. default:
  248. throw new Exception($"Unsupported hash algorithm: '{algorithm}'.");
  249. }
  250. using (hashAlgorithm)
  251. {
  252. return hashAlgorithm.ComputeHash(value);
  253. }
  254. }
  255. private static JwtHashAlgorithm GetHashAlgorithm(string algorithm)
  256. {
  257. switch (algorithm)
  258. {
  259. case "HS256":
  260. return JwtHashAlgorithm.HS256;
  261. case "HS384":
  262. return JwtHashAlgorithm.HS384;
  263. case "HS512":
  264. return JwtHashAlgorithm.HS512;
  265. default:
  266. throw new SignatureVerificationException($"Algorithm '{algorithm}' not supported.");
  267. }
  268. }
  269. private static readonly char[] _padding = new [] { '=' };
  270. private static string Base64UrlEncode(byte[] input)
  271. {
  272. var output = Convert.ToBase64String(input);
  273. output = output.TrimEnd(_padding); // Remove any trailing '='s
  274. output = output.Replace('+', '-'); // 62nd char of encoding
  275. output = output.Replace('/', '_'); // 63rd char of encoding
  276. return output;
  277. }
  278. private static byte[] Base64UrlDecode(string input)
  279. {
  280. var output = UrlDecode(input);
  281. var converted = Convert.FromBase64String(output);
  282. return converted;
  283. }
  284. private static string UrlDecode(string input)
  285. {
  286. var output = input;
  287. output = output.Replace('-', '+'); // 62nd char of encoding
  288. output = output.Replace('_', '/'); // 63rd char of encoding
  289. // Pad with trailing '='s
  290. switch (output.Length % 4)
  291. {
  292. case 0:
  293. break; // No pad chars in this case
  294. case 2:
  295. output += "==";
  296. break; // Two pad chars
  297. case 3:
  298. output += "=";
  299. break; // One pad char
  300. default:
  301. throw new Exception($"Illegal base-64 string: '{input}'.");
  302. }
  303. return output;
  304. }
  305. }
  306. }