forked from DuendeSoftware/demo.duendesoftware.com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJwtDecoder.cshtml
More file actions
837 lines (747 loc) · 38.4 KB
/
JwtDecoder.cshtml
File metadata and controls
837 lines (747 loc) · 38.4 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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
@page "~/jwt-decoder"
@model IdentityServerHost.Pages.Home.JwtDecoder
<div class="jwt-decoder-page">
<h2 id="jwt-decoder" style="scroll-margin-top: 3em;">JSON Web Token (JWT) Decoder</h2>
<div id="intro">
<p class="lead">
Using this tool, you can decode and validate JSON Web Tokens (JWTs) issued by IdentityServer or another token issuer.
</p>
<p>
A JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties.
It is commonly used for authentication and information exchange in web applications.
A JWT consists of three parts: a header, a payload, and a signature, separated by dots.
<br />
<br />
For more details, see <a href="https://datatracker.ietf.org/doc/html/rfc7519" target="_blank">RFC 7519</a>.
</p>
</div>
<div class="alert alert-warning d-flex align-items-center">
<i class="glyphicon glyphicon-exclamation-sign" style="font-size: 3em" title="Warning"></i>
<div class="mx-3">
<strong>This tool does not send JWTs to any server, it only decodes the JWT locally in your browser.</strong><br/>
Always be cautious when pasting JWTs, as they may contain credentials or sensitive information.<br/>
To validate how this page decodes and validates JWTs, you can inspect <a href="https://github.com/DuendeSoftware/demo.duendesoftware.com/blob/main/src/Pages/Home/JwtDecoder/JwtDecoder.cshtml" target="_blank">the source code of this page</a>.
</div>
</div>
<div class="pb-2">
<div class="custom-control custom-control-inline d-md-inline-flex p-0">
<form asp-page="JwtDecoder" method="post">
<button class="btn btn-primary" type="submit" id="loadSampleJwt">Load sample JWT</button>
</form>
</div>
<div class="custom-control custom-switch custom-control-inline">
<input class="custom-control-input" type="checkbox" id="explainClaims">
<label class="custom-control-label" for="explainClaims">
Show claim information
</label>
</div>
<div class="custom-control custom-switch custom-control-inline d-none d-md-inline-flex">
<input class="custom-control-input" type="checkbox" id="togglePresenterMode">
<label class="custom-control-label" for="togglePresenterMode">
Presenter mode
</label>
</div>
</div>
<div class="jwt-decoder-container container-fluid container-lg p-0">
<div class="row-jwt row align-items-stretch">
<div class="col-jwt col-12 col-md-6 pb-4 pb-md-0">
<h3>Encoded JWT</h3>
<div class="h-100 d-flex flex-column">
<div class="form-group flex-grow-1">
<label for="jwt-input" class="sr-only">Paste your JWT here...</label>
<div id="jwt-input" class="form-control bg-dark text-light p-2 h-100 jwt-input-editable" contenteditable="true" rows="8" style="min-height: 10em;">@(Model.View?.Token ?? "Paste your JWT here...")</div>
</div>
<div class="form-group">
<label for="jwks-url">Issuer, Discovery Document or JWKs URI</label>
<input type="url" class="form-control mb-2 mr-sm-2 bg-dark text-light" id="jwks-url" name="jwks-url" aria-describedby="jwks-url-help" data-pristine="true" />
<small id="jwks-url-help" class="form-text text-muted">
Optionally, you can provide the issuer, discovery document or JWKs URI to validate the JWT's signature.
If you leave this field empty, the tool will use the value of the 'iss' claim.
</small>
</div>
</div>
</div>
<div class="col-jwt col-12 col-md-6 pb-4 pb-md-0">
<h3>Decoded JWT</h3>
<div class="jwt-decoded-output">
<h4 class="pt-1">Header</h4>
<div id="jwt-header" class="jwt-decoded jwt-header bg-dark text-light p-2"> </div>
<h4 class="pt-1">Payload</h4>
<div id="jwt-payload" class="jwt-decoded jwt-payload bg-dark text-light p-2"> </div>
<h4 class="pt-1">Signature</h4>
<pre id="jwt-signature" class="jwt-decoded jwt-signature bg-dark text-light p-2"> </pre>
<div class="jwt-signature-validation-result alert alert-success align-items-center d-none">
<i class="glyphicon glyphicon-ok-sign" style="font-size: 3em" title="Valid signature"></i>
<div class="result-message mx-3">This JWT has a valid signature.</div>
</div>
<div class="jwt-signature-validation-result alert alert-danger align-items-center d-none">
<i class="glyphicon glyphicon-remove-sign" style="font-size: 3em" title="Invalid signature"></i>
<div class="result-message mx-3">This JWT has an invalid signature.</div>
</div>
<div class="jwt-signature-validation-result alert alert-warning align-items-center d-none">
<i class="glyphicon glyphicon-question-sign" style="font-size: 3em" title="Validation failed"></i>
<div class="result-message mx-3">Signature validation failed.</div>
</div>
<div class="jwt-decoder-error d-none">
<pre id="jwt-decoder-error-message" class="alert-danger p-2"> </pre>
</div>
</div>
</div>
</div>
</div>
</div>
@section scripts
{
<script>
let jwks = {
keys: [],
loadedFrom: null
};
let decodedJwt = {
header: null,
payload: null,
signature: null
};
const optionsKey = 'jwtDecoderSettings';
let options = {
presenterMode: false,
explainClaims: false
};
function explainJwtClaim(claimType, value) {
// Add explanations for common JWT claims using a comment-like syntax
switch (claimType) {
// header claims
case 'alg':
return '// ' + explainAlgorithm(value) + 'Algorithm used to sign the JWT';
case 'kid':
return '// Key ID, identifying which key was used to sign the JWT';
case 'typ':
return `// Token type: ${explainTokenType(value)}`;
case 'cty':
return '// Content type, similar to MIME type, indicating the media type of the JWT.';
case 'jwk':
return '// JWK, a JSON Web Key representing the public key used to verify the JWT signature';
case 'jku':
return '// JWK Set URL, a URL pointing to the JSON Web Key Set containing the public key used to verify the JWT signature';
case 'x5u':
return '// X.509 URL, a URL pointing to an X.509 certificate chain used to verify the JWT signature';
case 'x5c':
return '// X.509 certificate chain used to verify the JWT signature';
case 'x5t':
return '// X.509 certificate SHA-1 thumbprint, a hash of the X.509 certificate used to verify the JWT signature';
case 'x5t#S256':
return '// X.509 certificate SHA-256 thumbprint, a hash of the X.509 certificate used to verify the JWT signature';
case 'crit':
return '// Critical header parameters that must be understood by the recipient';
// payload claims
case 'iss':
return '// Issuer of the JWT, typically the authorization server';
case 'aud':
return '// Recipient(s) for which the JWT is intended';
case 'iat':
return '// ' + convertEpoch(value) + 'Issued at time, in seconds since epoch';
case 'exp':
return '// ' + convertEpoch(value) + 'Expiration time, in seconds since epoch';
case 'nbf':
return '// ' + convertEpoch(value) + 'Not before time, in seconds since epoch';
case 'jti':
return '// JWT ID, a unique identifier for the JWT';
case 'at_hash':
return '// Hash of the access token, used to verify the integrity of the access token';
case 'c_hash':
return '// Hash of the authorization code, used to verify the integrity of the authorization code';
case 'nonce':
return '// Nonce (number used only once), a unique value used to associate a client session with an ID Token, preventing replay attacks';
case 'acr':
return '// Authentication Context Class Reference, indicating the authentication method used';
case 'amr':
return '// Authentication Methods References, indicating the methods used for authentication';
// OIDC claims
case 'sub':
return '// Subject identifier';
case 'name':
return '// Display name of the user';
case 'given_name':
return '// Given name(s) or first name(s) of the user';
case 'family_name':
return '// Surname(s) or last name(s) of the user';
case 'middle_name':
return '// Middle name(s) of the user';
case 'nickname':
return '// Casual name of the user';
case 'preferred_username':
return '// Preferred username of the user, often used for login';
case 'birthdate':
return '// Birthdate of the user, typically in ISO 8601 format (YYYY-MM-DD)';
case 'gender':
return '// Gender of the user';
case 'email':
return '// Email address of the user';
case 'email_verified':
return '// Indicates whether the email address has been verified (true/false)';
case 'phone_number':
return '// Phone number of the user';
case 'phone_number_verified':
return '// Indicates whether the phone number has been verified (true/false)';
case 'address':
return '// Address of the user, typically an object with street, city, state, postal code, and country';
case 'locale':
return '// Locale of the user, typically a language code like "en-US"';
case 'zoneinfo':
return '// Time zone of the user, typically a string like "America/New_York"';
case 'profile':
return '// URL of the user\'s profile, often a link to their social media or personal page';
case 'picture':
return '// URL of the user\'s profile picture';
case 'website':
return '// URL of the user\'s personal website or profile';
}
return undefined;
}
function explainAlgorithm(alg) {
switch (alg) {
case 'RS256':
return 'RSA with SHA-256. ';
case 'RS384':
return 'RSA with SHA-384. ';
case 'RS512':
return 'RSA with SHA-512. ';
case 'ES256':
return 'ECDSA with P-256 curve. ';
case 'ES384':
return 'ECDSA with P-384 curve. ';
case 'ES512':
return 'ECDSA with P-521 curve. ';
case 'PS256':
return 'RSA-PSS with SHA-256. ';
case 'PS384':
return 'RSA-PSS with SHA-384. ';
case 'PS512':
return 'RSA-PSS with SHA-512. ';
case 'HS256':
return 'HMAC with SHA-256 shared secret. ';
case 'HS384':
return 'HMAC with SHA-384 shared secret. ';
case 'HS512':
return 'HMAC with SHA-512 shared secret. ';
case 'none':
return 'No signature algorithm. This JWT is unsigned and should not be trusted. ';
default:
return 'Unknown algorithm. ';
}
}
function explainTokenType(type) {
switch (type.toLowerCase()) {
case 'jwt':
case 'http://openid.net/specs/jwt/1.0':
return 'JSON Web Token';
case 'jws':
return 'JSON Web Signature, a signed JWT';
case 'jwe':
return 'JSON Web Encryption, an encrypted JWT';
case 'at+jwt':
return 'Access Token';
case 'token-introspection+jwt':
return 'JWT response from the Introspection endpoint';
case 'secevent+jwt':
return 'Security Event Token';
default:
return type;
}
}
function convertEpoch(epoch) {
if (typeof epoch === 'number') {
const date = new Date(epoch * 1000);
return date.toLocaleString() + '. ';
}
return '';
}
$(document).ready(initializeJwtDecoder);
function readSettingsFromStorage() {
try {
const settings = window.localStorage.getItem(optionsKey);
if (settings) {
options = JSON.parse(settings);
}
$('#explainClaims').prop('checked', options.explainClaims);
$('#togglePresenterMode').prop('checked', options.presenterMode);
setPresenterMode(options.presenterMode);
}
catch (e) {}
}
function saveSettingsToStorage() {
window.localStorage.setItem(optionsKey, JSON.stringify({
explainClaims: options.explainClaims,
presenterMode: options.presenterMode
}));
}
function setPresenterMode(enabled) {
if (enabled) {
$('.row-jwt').removeClass('align-items-stretch');
$('.col-jwt').removeClass('col-md-6');
$('#jwt-input').parent().removeClass('flex-grow-1');
$('#intro').addClass('d-none');
}
else {
$('.row-jwt').addClass('align-items-stretch');
$('.col-jwt').addClass('col-md-6');
$('#jwt-input').parent().addClass('flex-grow-1');
$('#intro').removeClass('d-none');
}
}
async function initializeJwtDecoder() {
await readSettingsFromStorage();
$('#explainClaims').on('change', async function() {
options.explainClaims = this.checked;
await saveSettingsToStorage();
updateClaimsExplanation();
});
$('#togglePresenterMode').on('change', async function() {
options.presenterMode = this.checked;
await saveSettingsToStorage();
setPresenterMode(options.presenterMode);
});
// Little helper to track if the JWKS URL field is pristine (not modified).
// While it is pristine or empty, we will use the 'iss' claim from the JWT payload to load JWKs.
const jwksUrlField = $('#jwks-url');
jwksUrlField.on('input', function() {
const val = $(this).val();
if (val === '' || val === null || val === undefined) {
jwksUrlField.data('pristine', true);
} else {
jwksUrlField.data('pristine', false);
}
});
const jwtInput = $('#jwt-input');
jwtInput.on('paste', function(e) {
e.preventDefault();
const data = (e.originalEvent.clipboardData || window.clipboardData).getData('text');
jwtInput.text(data);
jwtInput.trigger('input');
});
let debounceTimeout;
jwtInput.on('input', function() {
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(async () => await parseJwt.call(this), 100); // 100ms debounce
});
@if (!string.IsNullOrEmpty(Model.View?.Token))
{
@:jwtInput.trigger('input'); // Trigger input event to decode the JWT if it was provided
}
else
{
@:await showDecodedJwt(null, null, '', '', ' ');
}
}
async function parseJwt() {
decodedJwt = {
header: null,
payload: null,
signature: null
};
// Clear previous state before attempting to parse a new JWT
await showDecodedJwt(null, null, '', '', ' ');
const jwt = $(this).text();
if (jwt) {
try {
const parts = jwt.indexOf('.') === -1 ? [jwt] : jwt.split('.');
const headerInfo = parseJwtPart(parts, 0);
const payloadInfo = parseJwtPart(parts, 1);
const signature = parts.length > 2 ? parts[2] : '';
decodedJwt = {
header: headerInfo.length > 0 ? headerInfo[0] : null,
encodedHeader: headerInfo.length > 1 ? headerInfo[1] : '',
payload: payloadInfo.length > 0 ? payloadInfo[0] : null,
encodedPayload: payloadInfo.length > 1 ? payloadInfo[1] : '',
signature: signature
};
colorJwtInput($(this), parts, decodedJwt.encodedHeader, decodedJwt.encodedPayload, decodedJwt.signature);
await showDecodedJwt(decodedJwt.header, decodedJwt.payload, decodedJwt.encodedHeader, decodedJwt.encodedPayload, signature);
if (parts.length !== 3) {
showError('Invalid JWT format. A JWT should have three parts separated by dots.');
}
} catch (e) {
showError('Error decoding JWT: ' + e.message);
}
} else {
await showDecodedJwt(null, null, '', '', ' ');
}
}
function parseJwtPart(parts, index) {
if (index < 0 || index >= parts.length) {
return [];
}
const part = parts[index];
if (!part) {
return [];
}
// Find the base64 marker for a JSON object to start parsing
let jsonStartPos = 0;
while (jsonStartPos < part.length && part.substring(jsonStartPos, jsonStartPos + 3) !== 'eyJ') {
jsonStartPos++;
}
if (jsonStartPos >= part.length) {
return []; // No JSON object found
}
/* Finding a valid ending for base64 URL safe encoded JSON object is a bit trickier, as the encoded version
is different for JSON objects ending with ']' to close an array, '"' for ending a string value,
a number value or a boolean value.
*/
let jsonEndPos = part.length;
let encodedPart = part.substring(jsonStartPos, jsonEndPos);
let decodedPart = '';
let json = null;
do {
try {
decodedPart = decodeBase64UrlSafe(encodedPart);
json = JSON.parse(decodedPart);
if (json && typeof json === 'object') {
// If we successfully parsed a JSON object, we can return it
return [json, encodedPart];
}
}
catch {
// If decoding fails, we need to reduce the end position until we find a valid JSON object
jsonEndPos--;
encodedPart = part.substring(jsonStartPos, jsonEndPos);
}
}
while (jsonEndPos > jsonStartPos);
return []; // No valid JSON object found
}
function colorJwtInput(target, originalParts, encodedHeader, encodedPayload, signature) {
let html = '';
if (encodedHeader) {
const originalHeader = originalParts[0];
if (originalHeader === encodedHeader) {
html += `<span class="text-danger">${encodedHeader}</span>`;
}
else {
// Show the additional characters before and after the "encodedHeader" part that are found in originalHeader
const start = originalHeader.indexOf(encodedHeader);
const end = start + encodedHeader.length;
if (start > 0) {
html += `<span class="skipped">${originalHeader.substring(0, start)}</span>`;
}
html += `<span class="text-danger">${encodedHeader}</span>`;
if (end < originalHeader.length) {
html += `<span class="skipped">${originalHeader.substring(end)}</span>`;
}
}
}
else if (originalParts.length > 1) {
html += `<span class="skipped">${originalParts[0]}</span>`;
}
html += '<span class="jwt-divider">.</span>';
if (encodedPayload) {
const originalPayload = originalParts[1];
if (originalPayload === encodedPayload) {
html += `<span class="text-success">${encodedPayload}</span>`;
}
else {
// Show the additional characters before and after the "encodedPayload" part that are found in originalPayload
const start = originalPayload.indexOf(encodedPayload);
const end = start + encodedPayload.length;
if (start > 0) {
html += `<span class="skipped">${originalPayload.substring(0, start)}</span>`;
}
html += `<span class="text-success">${encodedPayload}</span>`;
if (end < originalPayload.length) {
html += `<span class="skipped">${originalPayload.substring(end)}</span>`;
}
}
}
else if (originalParts.length > 2) {
html += `<span class="skipped">${originalParts[1]}</span>`;
}
html += '<span class="jwt-divider">.</span>';
if (signature) {
html += `<span class="text-warning">${signature}</span>`;
}
target.html(html);
}
async function showDecodedJwt(header, payload, encodedHeader, encodedPayload, signature) {
clearError();
hideSignatureValidationResults();
writeJson($('#jwt-header'), header);
writeJson($('#jwt-payload'), payload);
$('#jwt-signature').text(signature || ' ');
if (encodedHeader && encodedPayload && signature) {
await attemptSignatureValidation(header, payload, encodedHeader, encodedPayload, signature);
}
}
function updateClaimsExplanation() {
if (!decodedJwt.payload) {
return;
}
writeJson($('#jwt-header'), decodedJwt.header);
writeJson($('#jwt-payload'), decodedJwt.payload);
}
function writeJson(target, data) {
if (data === null || data === undefined || !data) {
target.html(' '); // Empty space
return;
}
try {
const jsonContent = buildJsonHtmlContent(data);
target.empty();
target.append(jsonContent);
} catch (e) {
target.html(' '); // Empty space
showError('Error formatting JSON: ' + e.message);
}
}
function buildJsonHtmlContent(data) {
const jsonContent = $('<div class="json-content"></div>');
if (Array.isArray(data)) {
jsonContent.append('<span class="json-array-begin">[</span>');
data.forEach((item, index, arr) => {
const itemDiv = $(`<div class="json-item" style="padding-left: 1em"></div>`);
itemDiv.append(buildJsonValueHtml(item, null, index === arr.length - 1, false));
jsonContent.append(itemDiv);
});
jsonContent.append('<span class="json-array-end">]</span>');
} else if (typeof data === 'object') {
jsonContent.append('<span class="json-object-begin">{</span>');
Object.keys(data).forEach((key, index, arr) => {
const itemDiv = $(`<div class="json-item" style="padding-left: 1em"></div>`);
itemDiv.append(`<span class="json-key">"${key}"</span>: `);
itemDiv.append(buildJsonValueHtml(data[key], key, index === arr.length - 1, true));
jsonContent.append(itemDiv);
});
jsonContent.append('<span class="json-object-end">}</span>');
} else {
jsonContent.text(data);
}
return jsonContent;
}
function buildJsonValueHtml(value, key, isLastItem = false, explain = true) {
let contents = $('<span class="json-value"></span>');
if (Array.isArray(value)) {
contents = $('<span class="json-array-begin">[</span>');
value.forEach((item, index, arr) => {
const itemDiv = $(`<div class="json-item" style="padding-left: 1em"></div>`);
itemDiv.append(buildJsonValueHtml(item, null, index === arr.length - 1, false));
contents.append(itemDiv);
});
contents.append(`<span class="json-array-end">]${(isLastItem ? '' : ',')}</span>`);
}
else if (typeof value === 'object') {
contents = $('<span class="json-object-begin">{</span>');
Object.keys(value).forEach((key, index, arr) => {
const itemDiv = $('<div class="json-item" style="padding-left: 1em"></div>');
itemDiv.append(`<span class="json-key">"${key}"</span>: `);
itemDiv.append(buildJsonValueHtml(value[key], key, index === arr.length - 1, false)); // disable explanation for nested objects
contents.append(itemDiv);
});
contents.append(`<span class="json-object-end">}${(isLastItem ? '' : ',')}</span>`);
} else if (typeof value === 'string') {
const text = JSON.stringify(value);
contents.text(text);
contents.addClass('json-string');
if (!isLastItem) {
contents.append('<span class="json-structure">,</span>');
}
} else if (typeof value === 'number') {
const text = value;
contents.text(text);
contents.addClass('json-number');
if (!isLastItem) {
contents.append('<span class="json-structure">,</span>');
}
} else if (typeof value === 'boolean') {
const text = value ? 'true' : 'false';
contents.text(text);
contents.addClass('json-boolean');
if (!isLastItem) {
contents.append('<span class="json-structure">,</span>');
}
} else {
const text = String(value);
contents.text(text);
contents.addClass('json-unknown');
if (!isLastItem) {
contents.append('<span class="json-structure">,</span>');
}
}
if (options.explainClaims && key && explain) {
const explanation = explainJwtClaim(key, value);
if (explanation) {
contents.append(`<span class="json-explanation"> ${explanation}</span>`);
}
}
return contents;
}
async function attemptSignatureValidation(header, payload, encodedHeader, encodedPayload, signature) {
const jwksUrlField = $('#jwks-url');
const isPristine = jwksUrlField.data('pristine') !== false;
let jwksUrl = jwksUrlField.val().trim();
if ((!jwksUrl || isPristine) && payload && payload.iss) {
// If no JWKs URL is provided (or previously set from a different token's issuer), use the issuer from the payload.
jwksUrl = appendDiscoveryPath(payload.iss);
jwksUrlField.val(jwksUrl);
}
if (jwksUrl) {
await loadJwks(jwksUrl);
const headerAndPayload = encodedHeader + '.' + encodedPayload;
if (jwks.keys.length === 0) {
if (signature) {
showSignatureValidationResult('warning', 'The JWT has a signature, but no JWKs could be loaded to verify whether the signature is valid.');
}
else {
showSignatureValidationResult('warning', 'No JWKs loaded and no signature to validate.');
}
return;
}
const result = await validateSignature(header, headerAndPayload, signature, jwks.keys);
if (result.signatureValidated) {
if (result.isValid) {
showSignatureValidationResult('success');
} else {
showSignatureValidationResult('danger');
}
}
else {
showSignatureValidationResult('warning', result.errorMessage || 'Signature validation failed.');
}
}
}
async function validateSignature(header, headerAndPayload, signature, keys) {
try {
if (!header || !header.alg) {
return { signatureValidated: false, isValid: false, errorMessage: 'JWT header does not contain an algorithm.' };
}
if (!header.kid) {
return { signatureValidated: false, isValid: false, errorMessage: 'JWT kid is missing.' };
}
const key = keys.find(k => k.kid && k.kid === header.kid);
if (!key) {
return { signatureValidated: false, isValid: false, errorMessage: `No matching key found for kid: ${header.kid}` };
}
if (key.kty !== 'RSA' && key.kty !== 'EC') {
return { signatureValidated: false, isValid: false, errorMessage: `Unsupported key type: ${key.kty}. Only RSA and EC keys are supported.` };
}
const algorithmType = header.alg;
// algorithmType can be RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384, PS512, etc.
if (!algorithmType || (key.kty === 'RSA' && !algorithmType.startsWith('RS')) && (key.kty === 'EC' && !algorithmType.startsWith('ES'))) {
return { signatureValidated: false, isValid: false, errorMessage: `Unsupported algorithm: ${algorithmType}. Expected RS* or PS* for RSA, or ES* for EC keys.` };
}
const algorithmName =
algorithmType.startsWith('RS') ? 'RSASSA-PKCS1-v1_5' :
algorithmType.startsWith('PS') ? 'RSA-PSS' :
algorithmType.startsWith('ES') ? 'ECDSA' : null;
let algorithm = { name: algorithmName };
switch (algorithmType) {
case 'RS256':
case 'RS384':
case 'RS512':
algorithm.hash = { name: 'SHA-' + algorithmType.slice(2) };
break;
case 'PS256':
case 'PS384':
case 'PS512':
algorithm.hash = { name: 'SHA-' + algorithmType.slice(2) };
// Salt length is either 0 or the length of the digest algorithm that was selected when this key was created.
algorithm.saltLength = algorithmType === 'PS256' ? 32 : (algorithmType === 'PS384' ? 48 : 64);
break;
case 'ES256':
algorithm.namedCurve = 'P-256';
break;
case 'ES384':
algorithm.namedCurve = 'P-384';
break;
case 'ES512':
algorithm.namedCurve = 'P-521';
break;
default:
return { signatureValidated: false, isValid: false, errorMessage: `Unsupported algorithm: ${algorithmType}` };
}
const subtle = window.crypto.subtle;
const publicKey = await subtle.importKey(
'jwk',
key,
algorithm,
false,
['verify']
);
const binarySignature = decodeBase64UrlSafe(signature);
const signatureBuffer = Uint8Array.from(binarySignature, c => c.charCodeAt(0));
const isValid = await subtle.verify(algorithm, publicKey, signatureBuffer, new TextEncoder().encode(headerAndPayload));
return { signatureValidated: true, isValid: isValid };
} catch (error) {
return { signatureValidated: false, isValid: false, errorMessage: 'Error validating signature: ' + error.message };
}
}
async function loadJwks(jwksUrl) {
if (jwks.loadedFrom === jwksUrl && jwks.keys.length > 0) {
return; // Already loaded
}
jwks.loadedFrom = null;
jwks.keys = [];
try {
const keys = await fetchJwks(jwksUrl);
if (keys === undefined || keys === null) {
return;
}
jwks.keys = keys;
jwks.loadedFrom = jwksUrl;
console.log(`JWKs loaded from: ${jwksUrl}`, jwks.keys);
} catch (error) {
showError('Error loading JWKs: ' + error.message);
}
}
function appendDiscoveryPath(url) {
return url + (url.slice(-1) === '/' ? '' : '/') + '.well-known/openid-configuration';
}
async function fetchJwks(url) {
const response = await fetch(url);
if (!response.ok) {
return null;
}
const contentType = response.headers.get('Content-Type');
if (!contentType || !contentType.startsWith('application/json')) {
if (url.toLowerCase().indexOf('.well-known') !== -1 || url.toLowerCase().endsWith('.json')) {
showError('The provided JWKs URL does not return a valid JSON response.');
return null;
}
else {
// retry with a discovery document
return await fetchJwks(appendDiscoveryPath(url));
}
}
// Response is most likely JSON, but could be a discovery document.
const json = await response.json();
if (json.keys && Array.isArray(json.keys)) {
return json.keys;
} else if (json['jwks_uri']) {
// If it's a discovery document, retry using the jwks_uri.
return await fetchJwks(json['jwks_uri']);
} else {
showError('The provided URL does not contain valid JWKs or a JWKs URI.');
}
return null;
}
function showError(message) {
$('#jwt-decoder-error-message').text(message);
$('.jwt-decoder-error').removeClass('d-none');
}
function clearError() {
$('#jwt-decoder-error-message').text('');
$('.jwt-decoder-error').addClass('d-none');
}
function showSignatureValidationResult(type, message) {
hideSignatureValidationResults();
const resultElement = $('.jwt-signature-validation-result.alert-' + type);
resultElement.removeClass('d-none').addClass('d-flex');
if (message) {
resultElement.find('.result-message').text(message);
}
}
function hideSignatureValidationResults() {
$('.jwt-signature-validation-result').removeClass('d-flex').addClass('d-none');
}
function decodeBase64UrlSafe(base64Data) {
return atob(base64Data.replace(/-/g, '+').replace(/_/g, '/'));
}
</script>
}