-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathJwtToken.cs
More file actions
292 lines (248 loc) · 8.04 KB
/
JwtToken.cs
File metadata and controls
292 lines (248 loc) · 8.04 KB
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
using System;
using System.Collections.Generic;
using System.Text;
using Waher.Content;
using Waher.Runtime.Collections;
using Waher.Script;
using Waher.Security.JWS;
namespace Waher.Security.JWT
{
/// <summary>
/// Contains information about a Java Web Token (JWT). JWT is defined in RFC 7519:
/// https://tools.ietf.org/html/rfc7519
///
/// JWT are based on JSON Web Signature (JWS), defined in RFC 7515:
/// https://tools.ietf.org/html/rfc7515
///
/// Signature algorithms are defined in RFC 7518:
/// https://tools.ietf.org/html/rfc7518
/// </summary>
public class JwtToken
{
private string token;
private IJwsAlgorithm algorithm;
private Dictionary<string, object> claims;
private string header;
private string payload;
private string signature = null;
private string type = null;
private string issuer = null;
private string subject = null;
private string id = null;
private string[] audience = null;
private DateTime? expiration = null;
private DateTime? notBefore = null;
private DateTime? issuedAt = null;
/// <summary>
/// Contains information about a Java Web Token (JWT). JWT is defined in RFC 7519:
/// https://tools.ietf.org/html/rfc7519
///
/// JWT are based on JSON Web Signature (JWS), defined in RFC 7515:
/// https://tools.ietf.org/html/rfc7515
///
/// Signature algorithms are defined in RFC 7518:
/// https://tools.ietf.org/html/rfc7518
/// </summary>
/// <param name="Token">String-representation of token.</param>
public JwtToken(string Token)
{
if (!ParseInto(Token, this, out string Reason))
throw new Exception("Unable to parse JWT token: " + Token + "\r\nReason: " + Reason);
}
/// <summary>
/// Contains information about a Java Web Token (JWT). JWT is defined in RFC 7519:
/// </summary>
private JwtToken()
{
}
/// <summary>
/// Tries to parse a JWT token.
/// </summary>
/// <param name="Token">String-representation of token.</param>
/// <param name="ParsedToken">Parsed token, if successful.</param>
/// <returns>If successful in parsing token.</returns>
public static bool TryParse(string Token, out JwtToken ParsedToken)
{
return TryParse(Token, out ParsedToken, out _);
}
/// <summary>
/// Tries to parse a JWT token.
/// </summary>
/// <param name="Token">String-representation of token.</param>
/// <param name="ParsedToken">Parsed token, if successful.</param>
/// <param name="Reason">Reason, if not successful.</param>
/// <returns>If successful in parsing token.</returns>
public static bool TryParse(string Token, out JwtToken ParsedToken, out string Reason)
{
ParsedToken = new JwtToken();
return ParseInto(Token, ParsedToken, out Reason);
}
/// <summary>
/// Parses a token into a provided JwtToken object.
/// </summary>
/// <param name="Token">String-representation of token.</param>
/// <param name="ParsedToken">Token to receive parsed information.</param>
/// <param name="Reason">Reason, if not successful.</param>
/// <returns>If successful in parsing token.</returns>
public static bool ParseInto(string Token, JwtToken ParsedToken, out string Reason)
{
try
{
ParsedToken.token = Token;
string[] Parts = Token.Split('.');
ParsedToken.header = Parts[0];
byte[] HeaderBin = Base64Url.Decode(ParsedToken.header);
string HeaderString = Encoding.UTF8.GetString(HeaderBin);
if (!(JSON.Parse(HeaderString) is Dictionary<string, object> Header))
{
Reason = "Invalid JSON header.";
return false;
}
if (Header.TryGetValue("typ", out object Typ))
ParsedToken.type = Typ as string;
if (!Header.TryGetValue("alg", out object Alg) || !(Alg is string AlgStr))
{
Reason = "Invalid alg header field.";
return false;
}
if (string.IsNullOrEmpty(AlgStr) || string.Compare(AlgStr, "none", true) == 0)
ParsedToken.algorithm = null;
else if (!JwsAlgorithm.TryGetAlgorithm(AlgStr, out ParsedToken.algorithm))
{
Reason = "Unrecognized algorithm reference in header field.";
return false;
}
if (Parts.Length < 2)
{
Reason = "Claims set missing.";
return false;
}
byte[] ClaimsBin = Base64Url.Decode(ParsedToken.payload = Parts[1]);
string ClaimsString = Encoding.UTF8.GetString(ClaimsBin);
if (!(JSON.Parse(ClaimsString) is Dictionary<string, object> Claims))
{
Reason = "Invalid JSON claims set.";
return false;
}
ParsedToken.claims = Claims;
foreach (KeyValuePair<string, object> P in Claims)
{
switch (P.Key)
{
case JwtClaims.Issuer:
ParsedToken.issuer = P.Value as string;
break;
case JwtClaims.Subject:
ParsedToken.subject = P.Value as string;
break;
case JwtClaims.JwtId:
ParsedToken.id = P.Value as string;
break;
case JwtClaims.Audience:
if (P.Value is string AudStr)
ParsedToken.audience = AudStr.Split(',');
else if (P.Value is Array A)
{
ChunkedList<string> Audience2 = new ChunkedList<string>();
foreach (object Item in A)
Audience2.Add(Item.ToString());
ParsedToken.audience = Audience2.ToArray();
}
break;
case JwtClaims.ExpirationTime:
ParsedToken.expiration = JSON.UnixEpoch.AddSeconds(Expression.ToDouble(P.Value));
break;
case JwtClaims.NotBeforeTime:
ParsedToken.notBefore = JSON.UnixEpoch.AddSeconds(Expression.ToDouble(P.Value));
break;
case JwtClaims.IssueTime:
ParsedToken.issuedAt = JSON.UnixEpoch.AddSeconds(Expression.ToDouble(P.Value));
break;
case "expires":
break;
}
}
if (Parts.Length < 3)
{
Reason = "Signature missing.";
return false;
}
ParsedToken.signature = Parts[2];
Reason = null;
return true;
}
catch (Exception ex)
{
Reason = ex.Message;
return false;
}
}
/// <summary>
/// The Base64URL-encoded header.
/// </summary>
public string Header => this.header;
/// <summary>
/// The Base64URL-encoded payload.
/// </summary>
public string Payload => this.payload;
/// <summary>
/// The Base64URL-encoded signature.
/// </summary>
public string Signature => this.signature;
/// <summary>
/// String token that can be embedded easily in web requests, etc.
/// </summary>
public string Token => this.token;
/// <summary>
/// JWS signature algoritm.
/// </summary>
public IJwsAlgorithm Algorithm => this.algorithm;
/// <summary>
/// Claims provided in token. For a list of public claim names, see:
/// https://www.iana.org/assignments/jwt/jwt.xhtml
/// </summary>
public IEnumerable<KeyValuePair<string, object>> Claims => this.claims;
/// <summary>
/// Tries to get a claim from the JWT token.
/// </summary>
/// <param name="Key">Claim key.</param>
/// <param name="Value">Claim value.</param>
/// <returns>If the corresponding claim was found.</returns>
public bool TryGetClaim(string Key, out object Value)
{
return this.claims.TryGetValue(Key, out Value);
}
/// <summary>
/// Type of token, if available, null otherwise.
/// </summary>
public string Type => this.type;
/// <summary>
/// Issuer of token, if available, null otherwise.
/// </summary>
public string Issuer => this.issuer;
/// <summary>
/// Subject of whom the token relates, if available, null otherwise.
/// </summary>
public string Subject => this.subject;
/// <summary>
/// Token ID, if available, null otherwise.
/// </summary>
public string Id => this.id;
/// <summary>
/// Indended audience, if available, null otherwise.
/// </summary>
public string[] Audience => this.audience;
/// <summary>
/// Token expiration time, if available, null otherwise.
/// </summary>
public DateTime? Expiration => this.expiration;
/// <summary>
/// Token not valid before this time, if available, null otherwise.
/// </summary>
public DateTime? NotBefore => this.notBefore;
/// <summary>
/// Token issued at this time, if available, null otherwise.
/// </summary>
public DateTime? IssuedAt => this.issuedAt;
}
}