-
Notifications
You must be signed in to change notification settings - Fork 462
/
JwtDecoder.cs
322 lines (284 loc) · 13.9 KB
/
JwtDecoder.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
using System;
using System.Linq;
using JWT.Algorithms;
using JWT.Builder;
using JWT.Exceptions;
using static JWT.Internal.EncodingHelper;
#if NET35
using static JWT.Compatibility.String;
#endif
namespace JWT
{
/// <summary>
/// Decodes JWT.
/// </summary>
public sealed class JwtDecoder : IJwtDecoder
{
private readonly IJsonSerializer _jsonSerializer;
private readonly IJwtValidator _jwtValidator;
private readonly IBase64UrlEncoder _urlEncoder;
private readonly IAlgorithmFactory _algFactory;
/// <summary>
/// Creates an instance of <see cref="JwtDecoder" />
/// </summary>
/// <remarks>
/// This overload supplies no <see cref="IJwtValidator" /> and no <see cref="IAlgorithmFactory" /> so the resulting decoder cannot be used for signature validation.
/// </remarks>
/// <param name="jsonSerializer">The JSON serializer</param>
/// <param name="urlEncoder">The base64 URL encoder</param>
/// <exception cref="ArgumentNullException" />
public JwtDecoder(IJsonSerializer jsonSerializer, IBase64UrlEncoder urlEncoder)
{
_jsonSerializer = jsonSerializer ?? throw new ArgumentNullException(nameof(jsonSerializer));
_urlEncoder = urlEncoder ?? throw new ArgumentNullException(nameof(urlEncoder));
}
/// <summary>
/// Creates an instance of <see cref="JwtDecoder" />
/// </summary>
/// <param name="jsonSerializer">The JSON serializer</param>
/// <param name="jwtValidator">The JWT validator</param>
/// <param name="urlEncoder">The base64 URL encoder</param>
/// <param name="algFactory">The JWT algorithm Factory</param>
/// <exception cref="ArgumentNullException" />
public JwtDecoder(IJsonSerializer jsonSerializer, IJwtValidator jwtValidator, IBase64UrlEncoder urlEncoder, IAlgorithmFactory algFactory)
: this(jsonSerializer, urlEncoder)
{
_jwtValidator = jwtValidator ?? throw new ArgumentNullException(nameof(jwtValidator));
_algFactory = algFactory ?? throw new ArgumentNullException(nameof(algFactory));
}
/// <summary>
/// Creates an instance of <see cref="JwtDecoder" />
/// </summary>
/// <param name="jsonSerializer">The JSON serializer</param>
/// <param name="jwtValidator">The JWT validator</param>
/// <param name="urlEncoder">The base64 URL encoder</param>
/// <param name="algorithm">The JWT algorithm</param>
/// <exception cref="ArgumentNullException" />
public JwtDecoder(IJsonSerializer jsonSerializer, IJwtValidator jwtValidator, IBase64UrlEncoder urlEncoder, IJwtAlgorithm algorithm)
: this(jsonSerializer, jwtValidator, urlEncoder, new DelegateAlgorithmFactory(algorithm))
{
}
/// <inheritdoc />
/// <exception cref="ArgumentException" />
/// <exception cref="InvalidTokenPartsException" />
/// <exception cref="FormatException" />
public string DecodeHeader(string token)
{
if (String.IsNullOrEmpty(token))
throw new ArgumentException(nameof(token));
var header = new JwtParts(token).Header;
var decoded = _urlEncoder.Decode(header);
return GetString(decoded);
}
/// <inheritdoc />
/// <exception cref="ArgumentException" />
/// <exception cref="ArgumentNullException" />
/// <exception cref="FormatException" />
public T DecodeHeader<T>(JwtParts jwt)
{
if (jwt is null)
throw new ArgumentNullException(nameof(jwt));
var decodedHeader = _urlEncoder.Decode(jwt.Header);
var stringHeader = GetString(decodedHeader);
return _jsonSerializer.Deserialize<T>(stringHeader);
}
/// <inheritdoc />
/// <exception cref="ArgumentException" />
/// <exception cref="ArgumentNullException" />
/// <exception cref="ArgumentOutOfRangeException" />
/// <exception cref="InvalidTokenPartsException" />
/// <exception cref="FormatException" />
/// <exception cref="SignatureVerificationException" />
/// <exception cref="TokenNotYetValidException" />
/// <exception cref="TokenExpiredException" />
public string Decode(JwtParts jwt, bool verify) =>
Decode(jwt, (byte[])null, verify);
/// <inheritdoc />
/// <exception cref="ArgumentException" />
/// <exception cref="ArgumentNullException" />
/// <exception cref="ArgumentOutOfRangeException" />
/// <exception cref="InvalidTokenPartsException" />
/// <exception cref="FormatException" />
/// <exception cref="SignatureVerificationException" />
/// <exception cref="TokenNotYetValidException" />
/// <exception cref="TokenExpiredException" />
public string Decode(JwtParts jwt, byte[] key, bool verify) =>
Decode(jwt, new[] { key }, verify);
/// <inheritdoc />
/// <exception cref="ArgumentException" />
/// <exception cref="ArgumentNullException" />
/// <exception cref="ArgumentOutOfRangeException" />
/// <exception cref="FormatException" />
/// <exception cref="SignatureVerificationException" />
/// <exception cref="TokenNotYetValidException" />
/// <exception cref="TokenExpiredException" />
public string Decode(JwtParts jwt, byte[][] keys, bool verify)
{
if (jwt is null)
throw new ArgumentNullException(nameof(jwt));
if (verify)
{
if (_jwtValidator is null)
throw new InvalidOperationException("This instance was constructed without validator so cannot be used for signature validation");
if (_algFactory is null)
throw new InvalidOperationException("This instance was constructed without algorithm factory so cannot be used for signature validation");
Validate(jwt, keys);
}
else
{
ValidateNoneAlgorithm(jwt);
}
return Decode(jwt);
}
/// <inheritdoc />
/// <exception cref="ArgumentException" />
/// <exception cref="ArgumentNullException" />
/// <exception cref="ArgumentOutOfRangeException" />
/// <exception cref="FormatException" />
/// <exception cref="SignatureVerificationException" />
/// <exception cref="TokenNotYetValidException" />
/// <exception cref="TokenExpiredException" />
public object DecodeToObject(Type type, JwtParts jwt, bool verify)
{
var payload = Decode(jwt, verify);
return _jsonSerializer.Deserialize(type, payload);
}
/// <inheritdoc />
/// <exception cref="ArgumentException" />
/// <exception cref="ArgumentNullException" />
/// <exception cref="ArgumentOutOfRangeException" />
/// <exception cref="FormatException" />
/// <exception cref="SignatureVerificationException" />
/// <exception cref="TokenNotYetValidException" />
/// <exception cref="TokenExpiredException" />
public object DecodeToObject(Type type, JwtParts jwt, byte[] key, bool verify)
{
var payload = Decode(jwt, key, verify);
return _jsonSerializer.Deserialize(type, payload);
}
/// <inheritdoc />
/// <exception cref="ArgumentException" />
/// <exception cref="ArgumentNullException" />
/// <exception cref="ArgumentOutOfRangeException" />
/// <exception cref="FormatException" />
/// <exception cref="SignatureVerificationException" />
/// <exception cref="TokenNotYetValidException" />
/// <exception cref="TokenExpiredException" />
public object DecodeToObject(Type type, JwtParts jwt, byte[][] keys, bool verify)
{
var payload = Decode(jwt, keys, verify);
return _jsonSerializer.Deserialize(type, payload);
}
/// <summary>
/// Prepares data before calling <see cref="IJwtValidator" />
/// </summary>
/// <param name="parts">The array representation of a JWT</param>
/// <param name="key">The key that was used to sign the JWT</param>
/// <exception cref="ArgumentNullException" />
/// <exception cref="ArgumentOutOfRangeException" />
/// <exception cref="FormatException" />
/// <exception cref="SignatureVerificationException" />
/// <exception cref="TokenNotYetValidException" />
/// <exception cref="TokenExpiredException" />
public void Validate(string[] parts, byte[] key) =>
Validate(new JwtParts(parts), key);
/// <summary>
/// Prepares data before calling <see cref="IJwtValidator" />
/// </summary>
/// <param name="parts">The array representation of a JWT</param>
/// <param name="keys">The keys provided which one of them was used to sign the JWT</param>
/// <exception cref="ArgumentNullException" />
/// <exception cref="ArgumentOutOfRangeException" />
/// <exception cref="FormatException" />
/// <exception cref="SignatureVerificationException" />
/// <exception cref="TokenNotYetValidException" />
/// <exception cref="TokenExpiredException" />
public void Validate(string[] parts, params byte[][] keys) =>
Validate(new JwtParts(parts), keys);
/// <summary>
/// Prepares data before calling <see cref="IJwtValidator" />
/// </summary>
/// <param name="jwt">The JWT parts</param>
/// <param name="keys">The keys provided which one of them was used to sign the JWT</param>
/// <exception cref="ArgumentException" />
/// <exception cref="ArgumentNullException" />
/// <exception cref="ArgumentOutOfRangeException" />
/// <exception cref="FormatException" />
/// <exception cref="SignatureVerificationException" />
/// <exception cref="TokenNotYetValidException" />
/// <exception cref="TokenExpiredException" />
public void Validate(JwtParts jwt, params byte[][] keys)
{
if (jwt is null)
throw new ArgumentNullException(nameof(jwt));
if (jwt.Payload is null)
throw new ArgumentNullException(nameof(JwtParts.Payload));
if (jwt.Signature is null)
throw new ArgumentNullException(nameof(JwtParts.Signature));
var decodedPayload = GetString(_urlEncoder.Decode(jwt.Payload));
var decodedSignature = _urlEncoder.Decode(jwt.Signature);
var header = DecodeHeader<JwtHeader>(jwt);
var algorithm = _algFactory.Create(JwtDecoderContext.Create(header, decodedPayload, jwt));
if (algorithm is null)
throw new ArgumentNullException(nameof(algorithm));
var bytesToSign = GetBytes(jwt.Header, '.', jwt.Payload);
if (algorithm is IAsymmetricAlgorithm asymmAlg)
{
_jwtValidator.Validate(decodedPayload, asymmAlg, bytesToSign, decodedSignature);
}
else
{
ValidSymmetricAlgorithm(keys, decodedPayload, algorithm, bytesToSign, decodedSignature);
}
}
private string Decode(JwtParts jwt)
{
if (jwt is null)
throw new ArgumentNullException(nameof(jwt));
var decoded = _urlEncoder.Decode(jwt.Payload);
return GetString(decoded);
}
private void ValidSymmetricAlgorithm(byte[][] keys, string decodedPayload, IJwtAlgorithm algorithm, byte[] bytesToSign, byte[] decodedSignature)
{
if (keys is null)
throw new ArgumentNullException(nameof(keys));
if (!AllKeysHaveValues(keys))
throw new ArgumentOutOfRangeException(nameof(keys));
// the signature on the token, with the leading =
var rawSignature = Convert.ToBase64String(decodedSignature);
// the signatures re-created by the algorithm, with the leading =
var recreatedSignatures = keys.Select(key => Convert.ToBase64String(algorithm.Sign(key, bytesToSign))).ToArray();
_jwtValidator.Validate(decodedPayload, rawSignature, recreatedSignatures);
}
private static bool AllKeysHaveValues(byte[][] keys)
{
if (keys is null)
return false;
if (keys.Length == 0)
return false;
return Array.TrueForAll(keys, key => KeyHasValue(key));
}
private static bool KeyHasValue(byte[] key)
{
if (key is null)
return false;
if (key.Length == 0)
return false;
return true;
}
private void ValidateNoneAlgorithm(JwtParts jwt)
{
var header = DecodeHeader<JwtHeader>(jwt);
if (String.IsNullOrEmpty(header.Type) &&
String.IsNullOrEmpty(header.Algorithm))
{
throw new InvalidOperationException("Error deserializing JWT header, all mandatory properties are null or empty");
}
if (String.Equals(header.Algorithm, nameof(JwtAlgorithmName.None), StringComparison.OrdinalIgnoreCase) &&
!String.IsNullOrEmpty(jwt.Signature))
{
throw new InvalidOperationException("Signature is not acceptable for algorithm None");
}
}
}
}