-
Notifications
You must be signed in to change notification settings - Fork 462
/
JWT.cs
executable file
·287 lines (254 loc) · 14.4 KB
/
JWT.cs
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace JWT
{
public enum JwtHashAlgorithm
{
HS256,
HS384,
HS512
}
/// <summary>
/// Provides methods for encoding and decoding JSON Web Tokens.
/// </summary>
public static class JsonWebToken
{
private static readonly IDictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>> HashAlgorithms;
/// <summary>
/// Pluggable JSON Serializer
/// </summary>
public static IJsonSerializer JsonSerializer = new DefaultJsonSerializer();
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
static JsonWebToken()
{
HashAlgorithms = new Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>>
{
{ JwtHashAlgorithm.HS256, (key, value) => { using (var sha = new HMACSHA256(key)) { return sha.ComputeHash(value); } } },
{ JwtHashAlgorithm.HS384, (key, value) => { using (var sha = new HMACSHA384(key)) { return sha.ComputeHash(value); } } },
{ JwtHashAlgorithm.HS512, (key, value) => { using (var sha = new HMACSHA512(key)) { return sha.ComputeHash(value); } } }
};
}
/// <summary>
/// Creates a JWT given a header, a payload, the signing key, and the algorithm to use.
/// </summary>
/// <param name="extraHeaders">An arbitrary set of extra headers. Will be augmented with the standard "typ" and "alg" headers.</param>
/// <param name="payload">An arbitrary payload (must be serializable to JSON via <see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>).</param>
/// <param name="key">The key bytes used to sign the token.</param>
/// <param name="algorithm">The hash algorithm to use.</param>
/// <returns>The generated JWT.</returns>
public static string Encode(IDictionary<string, object> extraHeaders, object payload, byte[] key, JwtHashAlgorithm algorithm)
{
var segments = new List<string>();
var header = new Dictionary<string, object>(extraHeaders)
{
{ "typ", "JWT" },
{ "alg", algorithm.ToString() }
};
byte[] headerBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(header));
byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(payload));
segments.Add(Base64UrlEncode(headerBytes));
segments.Add(Base64UrlEncode(payloadBytes));
var stringToSign = string.Join(".", segments.ToArray());
var bytesToSign = Encoding.UTF8.GetBytes(stringToSign);
byte[] signature = HashAlgorithms[algorithm](key, bytesToSign);
segments.Add(Base64UrlEncode(signature));
return string.Join(".", segments.ToArray());
}
/// <summary>
/// Creates a JWT given a payload, the signing key, and the algorithm to use.
/// </summary>
/// <param name="payload">An arbitrary payload (must be serializable to JSON via <see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>).</param>
/// <param name="key">The key used to sign the token.</param>
/// <param name="algorithm">The hash algorithm to use.</param>
/// <returns>The generated JWT.</returns>
public static string Encode(object payload, byte[] key, JwtHashAlgorithm algorithm)
{
return Encode(new Dictionary<string, object>(), payload, key, algorithm);
}
/// <summary>
/// Creates a JWT given a set of arbitrary extra headers, a payload, the signing key, and the algorithm to use.
/// </summary>
/// <param name="extraHeaders">An arbitrary set of extra headers. Will be augmented with the standard "typ" and "alg" headers.</param>
/// <param name="payload">An arbitrary payload (must be serializable to JSON via <see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>).</param>
/// <param name="key">The key bytes used to sign the token.</param>
/// <param name="algorithm">The hash algorithm to use.</param>
/// <returns>The generated JWT.</returns>
public static string Encode(IDictionary<string, object> extraHeaders, object payload, string key, JwtHashAlgorithm algorithm)
{
return Encode(extraHeaders, payload, Encoding.UTF8.GetBytes(key), algorithm);
}
/// <summary>
/// Creates a JWT given a payload, the signing key, and the algorithm to use.
/// </summary>
/// <param name="payload">An arbitrary payload (must be serializable to JSON via <see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>).</param>
/// <param name="key">The key used to sign the token.</param>
/// <param name="algorithm">The hash algorithm to use.</param>
/// <returns>The generated JWT.</returns>
public static string Encode(object payload, string key, JwtHashAlgorithm algorithm)
{
return Encode(new Dictionary<string, object>(), payload, Encoding.UTF8.GetBytes(key), algorithm);
}
/// <summary>
/// Given a JWT, decode it and return the JSON payload.
/// </summary>
/// <param name="token">The JWT.</param>
/// <param name="key">The key bytes that were used to sign the JWT.</param>
/// <param name="verify">Whether to verify the signature (default is true).</param>
/// <returns>A string containing the JSON payload.</returns>
/// <exception cref="SignatureVerificationException">Thrown if the verify parameter was true and the signature was NOT valid or if the JWT was signed with an unsupported algorithm.</exception>
public static string Decode(string token, byte[] key, bool verify = true)
{
var parts = token.Split('.');
if (parts.Length != 3)
{
throw new ArgumentException("Token must consist from 3 delimited by dot parts");
}
var header = parts[0];
var payload = parts[1];
var crypto = Base64UrlDecode(parts[2]);
var headerJson = Encoding.UTF8.GetString(Base64UrlDecode(header));
var payloadJson = Encoding.UTF8.GetString(Base64UrlDecode(payload));
var headerData = JsonSerializer.Deserialize<Dictionary<string, object>>(headerJson);
if (verify)
{
var bytesToSign = Encoding.UTF8.GetBytes(string.Concat(header, ".", payload));
var algorithm = (string)headerData["alg"];
var signature = HashAlgorithms[GetHashAlgorithm(algorithm)](key, bytesToSign);
var decodedCrypto = Convert.ToBase64String(crypto);
var decodedSignature = Convert.ToBase64String(signature);
Verify(decodedCrypto, decodedSignature, payloadJson);
}
return payloadJson;
}
private static void Verify(string decodedCrypto, string decodedSignature, string payloadJson)
{
if (decodedCrypto != decodedSignature)
{
throw new SignatureVerificationException(string.Format("Invalid signature. Expected {0} got {1}", decodedCrypto, decodedSignature));
}
// verify exp claim https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.4
var payloadData = JsonSerializer.Deserialize<Dictionary<string, object>>(payloadJson);
if (payloadData.ContainsKey("exp") && payloadData["exp"] != null)
{
// safely unpack a boxed int
int exp;
try
{
exp = Convert.ToInt32(payloadData["exp"]);
}
catch (Exception)
{
throw new SignatureVerificationException("Claim 'exp' must be an integer.");
}
var secondsSinceEpoch = Math.Round((DateTime.UtcNow - UnixEpoch).TotalSeconds);
if (secondsSinceEpoch >= exp)
{
throw new SignatureVerificationException("Token has expired.");
}
}
}
/// <summary>
/// Given a JWT, decode it and return the JSON payload.
/// </summary>
/// <param name="token">The JWT.</param>
/// <param name="key">The key that was used to sign the JWT.</param>
/// <param name="verify">Whether to verify the signature (default is true).</param>
/// <returns>A string containing the JSON payload.</returns>
/// <exception cref="SignatureVerificationException">Thrown if the verify parameter was true and the signature was NOT valid or if the JWT was signed with an unsupported algorithm.</exception>
public static string Decode(string token, string key, bool verify = true)
{
return Decode(token, Encoding.UTF8.GetBytes(key), verify);
}
/// <summary>
/// Given a JWT, decode it and return the payload as an object (by deserializing it with <see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>).
/// </summary>
/// <param name="token">The JWT.</param>
/// <param name="key">The key that was used to sign the JWT.</param>
/// <param name="verify">Whether to verify the signature (default is true).</param>
/// <returns>An object representing the payload.</returns>
/// <exception cref="SignatureVerificationException">Thrown if the verify parameter was true and the signature was NOT valid or if the JWT was signed with an unsupported algorithm.</exception>
public static object DecodeToObject(string token, byte[] key, bool verify = true)
{
var payloadJson = Decode(token, key, verify);
var payloadData = JsonSerializer.Deserialize<Dictionary<string, object>>(payloadJson);
return payloadData;
}
/// <summary>
/// Given a JWT, decode it and return the payload as an object (by deserializing it with <see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>).
/// </summary>
/// <param name="token">The JWT.</param>
/// <param name="key">The key that was used to sign the JWT.</param>
/// <param name="verify">Whether to verify the signature (default is true).</param>
/// <returns>An object representing the payload.</returns>
/// <exception cref="SignatureVerificationException">Thrown if the verify parameter was true and the signature was NOT valid or if the JWT was signed with an unsupported algorithm.</exception>
public static object DecodeToObject(string token, string key, bool verify = true)
{
return DecodeToObject(token, Encoding.UTF8.GetBytes(key), verify);
}
/// <summary>
/// Given a JWT, decode it and return the payload as an object (by deserializing it with <see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>).
/// </summary>
/// <typeparam name="T">The <see cref="Type"/> to return</typeparam>
/// <param name="token">The JWT.</param>
/// <param name="key">The key that was used to sign the JWT.</param>
/// <param name="verify">Whether to verify the signature (default is true).</param>
/// <returns>An object representing the payload.</returns>
/// <exception cref="SignatureVerificationException">Thrown if the verify parameter was true and the signature was NOT valid or if the JWT was signed with an unsupported algorithm.</exception>
public static T DecodeToObject<T>(string token, byte[] key, bool verify = true)
{
var payloadJson = Decode(token, key, verify);
var payloadData = JsonSerializer.Deserialize<T>(payloadJson);
return payloadData;
}
/// <summary>
/// Given a JWT, decode it and return the payload as an object (by deserializing it with <see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>).
/// </summary>
/// <typeparam name="T">The <see cref="Type"/> to return</typeparam>
/// <param name="token">The JWT.</param>
/// <param name="key">The key that was used to sign the JWT.</param>
/// <param name="verify">Whether to verify the signature (default is true).</param>
/// <returns>An object representing the payload.</returns>
/// <exception cref="SignatureVerificationException">Thrown if the verify parameter was true and the signature was NOT valid or if the JWT was signed with an unsupported algorithm.</exception>
public static T DecodeToObject<T>(string token, string key, bool verify = true)
{
return DecodeToObject<T>(token, Encoding.UTF8.GetBytes(key), verify);
}
private static JwtHashAlgorithm GetHashAlgorithm(string algorithm)
{
switch (algorithm)
{
case "HS256": return JwtHashAlgorithm.HS256;
case "HS384": return JwtHashAlgorithm.HS384;
case "HS512": return JwtHashAlgorithm.HS512;
default: throw new SignatureVerificationException("Algorithm not supported.");
}
}
// from JWT spec
public static string Base64UrlEncode(byte[] input)
{
var output = Convert.ToBase64String(input);
output = output.Split('=')[0]; // Remove any trailing '='s
output = output.Replace('+', '-'); // 62nd char of encoding
output = output.Replace('/', '_'); // 63rd char of encoding
return output;
}
// from JWT spec
public static byte[] Base64UrlDecode(string input)
{
var output = input;
output = output.Replace('-', '+'); // 62nd char of encoding
output = output.Replace('_', '/'); // 63rd char of encoding
switch (output.Length % 4) // Pad with trailing '='s
{
case 0: break; // No pad chars in this case
case 2: output += "=="; break; // Two pad chars
case 3: output += "="; break; // One pad char
default: throw new Exception("Illegal base64url string!");
}
var converted = Convert.FromBase64String(output); // Standard base64 decoder
return converted;
}
}
}