-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJwtsTest.groovy
1765 lines (1465 loc) · 60.5 KB
/
JwtsTest.groovy
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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2014 jsonwebtoken.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jsonwebtoken
import io.jsonwebtoken.SignatureAlgorithm
import io.jsonwebtoken.impl.*
import io.jsonwebtoken.impl.compression.GzipCompressionAlgorithm
import io.jsonwebtoken.impl.io.Streams
import io.jsonwebtoken.impl.lang.Bytes
import io.jsonwebtoken.impl.lang.Services
import io.jsonwebtoken.impl.security.*
import io.jsonwebtoken.io.CompressionAlgorithm
import io.jsonwebtoken.io.Decoders
import io.jsonwebtoken.io.Deserializer
import io.jsonwebtoken.io.Encoders
import io.jsonwebtoken.io.Serializer
import io.jsonwebtoken.lang.Strings
import io.jsonwebtoken.security.*
import org.junit.Test
import javax.crypto.Mac
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import java.security.Key
import java.security.KeyPair
import java.security.PrivateKey
import java.security.PublicKey
import java.security.interfaces.ECPublicKey
import java.security.interfaces.RSAPublicKey
import static org.junit.Assert.*
class JwtsTest {
private static Date dateWithOnlySecondPrecision(long millis) {
long seconds = (millis / 1000) as long
long secondOnlyPrecisionMillis = seconds * 1000
return new Date(secondOnlyPrecisionMillis)
}
private static Date now() {
Date date = dateWithOnlySecondPrecision(System.currentTimeMillis())
return date
}
private static int later() {
def date = laterDate(10000)
def seconds = date.getTime() / 1000
return seconds as int
}
private static Date laterDate(int seconds) {
def millis = seconds * 1000L
def time = System.currentTimeMillis() + millis
return dateWithOnlySecondPrecision(time)
}
protected static String base64Url(String s) {
byte[] bytes = s.getBytes(Strings.UTF_8)
return Encoders.BASE64URL.encode(bytes)
}
static def toJson(def o) {
def serializer = Services.get(Serializer)
def out = new ByteArrayOutputStream()
serializer.serialize(o, out)
return Strings.utf8(out.toByteArray())
}
@Test
void testPrivateCtor() { // for code coverage only
//noinspection GroovyAccessibility
new Jwts()
}
@Test
void testHeaderWithNoArgs() {
def header = Jwts.header().build()
assertTrue header instanceof DefaultHeader
}
@Test
void testHeaderWithMapArg() {
def header = Jwts.header().add([alg: "HS256"]).build()
assertTrue header instanceof DefaultJwsHeader
assertEquals 'HS256', header.getAlgorithm()
assertEquals 'HS256', header.alg
}
@Test
void testClaims() {
Claims claims = Jwts.claims().build()
assertNotNull claims
}
@Test
void testClaimsWithMapArg() {
Claims claims = Jwts.claims([sub: 'Joe'])
assertNotNull claims
assertEquals 'Joe', claims.getSubject()
}
/**
* @since 0.12.0
*/
@Test
void testParseMalformedHeader() {
def headerString = '{"jku":42}' // cannot be parsed as a URI --> malformed header
def claimsString = '{"sub":"joe"}'
def encodedHeader = base64Url(headerString)
def encodedClaims = base64Url(claimsString)
def compact = encodedHeader + '.' + encodedClaims + '.AAD='
try {
Jwts.parser().build().parseSignedClaims(compact)
fail()
} catch (MalformedJwtException e) {
String expected = 'Invalid protected header: Invalid JWS header \'jku\' (JWK Set URL) value: 42. ' +
'Values must be either String or java.net.URI instances. Value type found: java.lang.Integer.'
assertEquals expected, e.getMessage()
}
}
/**
* @since 0.12.0
*/
@Test
void testParseMalformedClaims() {
def key = TestKeys.HS256
def h = base64Url('{"alg":"HS256"}')
def c = base64Url('{"sub":"joe","exp":"-42-"}')
def data = Strings.utf8(("$h.$c" as String))
def payload = Streams.of(data)
def request = new DefaultSecureRequest<>(payload, null, null, key)
def result = Jwts.SIG.HS256.digest(request)
def sig = Encoders.BASE64URL.encode(result)
def compact = "$h.$c.$sig" as String
try {
Jwts.parser().setSigningKey(key).build().parseSignedClaims(compact)
fail()
} catch (MalformedJwtException e) {
String expected = 'Invalid claims: Invalid JWT Claims \'exp\' (Expiration Time) value: -42-. ' +
'String value is not a JWT NumericDate, nor is it ISO-8601-formatted. All heuristics exhausted. ' +
'Cause: Unparseable date: "-42-"'
assertEquals expected, e.getMessage()
}
}
@Test
void testContentJwtString() {
// Assert exact output per example at https://www.rfc-editor.org/rfc/rfc7519.html#section-6.1
String encodedBody = 'eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ'
String payload = new String(Decoders.BASE64URL.decode(encodedBody), StandardCharsets.UTF_8)
String val = Jwts.builder().setPayload(payload).compact()
String RFC_VALUE = 'eyJhbGciOiJub25lIn0.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.'
assertEquals RFC_VALUE, val
}
@Test
void testContentWithContentType() {
String s = 'Hello JJWT'
String cty = 'text/plain'
String compact = Jwts.builder().content(s, cty).compact()
def jwt = Jwts.parser().unsecured().build().parseUnsecuredContent(compact)
assertEquals cty, jwt.header.getContentType()
assertEquals s, new String(jwt.payload, StandardCharsets.UTF_8)
}
@Test
void testContentBytesWithContentType() {
String s = 'Hello JJWT'
byte[] content = Strings.utf8(s)
String cty = 'text/plain'
String compact = Jwts.builder().content(content, cty).compact()
def jwt = Jwts.parser().unsecured().build().parseUnsecuredContent(compact)
assertEquals cty, jwt.header.getContentType()
assertEquals s, new String(jwt.payload, StandardCharsets.UTF_8)
}
@Test
void testContentStreamWithContentType() {
String s = 'Hello JJWT'
InputStream content = Streams.of(Strings.utf8(s))
String cty = 'text/plain'
String compact = Jwts.builder().content(content, cty).compact()
def jwt = Jwts.parser().unsecured().build().parseUnsecuredContent(compact)
assertEquals cty, jwt.header.getContentType()
assertEquals s, new String(jwt.payload, StandardCharsets.UTF_8)
}
@Test
void testContentStreamWithoutContentType() {
String s = 'Hello JJWT'
InputStream content = Streams.of(Strings.utf8(s))
String compact = Jwts.builder().content(content).compact()
def jwt = Jwts.parser().unsecured().build().parseUnsecuredContent(compact)
assertNull jwt.header.getContentType()
assertEquals s, new String(jwt.payload, StandardCharsets.UTF_8)
}
@Test
void testContentStreamNull() {
String compact = Jwts.builder().content((InputStream) null).compact()
def jwt = Jwts.parser().unsecured().build().parseUnsecuredContent(compact)
assertEquals 'none', jwt.header.getAlgorithm()
assertTrue Bytes.isEmpty(jwt.getPayload())
}
@Test
void testContentWithApplicationContentType() {
String s = 'Hello JJWT'
String subtype = 'foo'
String cty = "application/$subtype"
String compact = Jwts.builder().content(s, cty).compact()
def jwt = Jwts.parser().unsecured().build().parseUnsecuredContent(compact)
// assert raw value is compact form:
assertEquals subtype, jwt.header.get('cty')
// assert getter reflects normalized form per https://www.rfc-editor.org/rfc/rfc7515.html#section-4.1.10:
assertEquals cty, jwt.header.getContentType()
assertEquals s, new String(jwt.payload, StandardCharsets.UTF_8)
}
@Test
void testContentWithNonCompactApplicationContentType() {
String s = 'Hello JJWT'
String subtype = 'foo'
String cty = "application/$subtype;part=1/2"
String compact = Jwts.builder().content(s, cty).compact()
def jwt = Jwts.parser().unsecured().build().parseUnsecuredContent(compact)
assertEquals cty, jwt.header.getContentType() // two slashes, can't compact
assertEquals s, new String(jwt.payload, StandardCharsets.UTF_8)
}
@Test
void testParseContentToken() {
def claims = [iss: 'joe', exp: later(), 'https://example.com/is_root': true]
String jwt = Jwts.builder().claims().add(claims).and().compact()
def token = Jwts.parser().unsecured().build().parse(jwt)
//noinspection GrEqualsBetweenInconvertibleTypes
assert token.payload == claims
}
@Test(expected = IllegalArgumentException)
void testParseNull() {
Jwts.parser().build().parse(null)
}
@Test(expected = IllegalArgumentException)
void testParseEmptyString() {
Jwts.parser().build().parse('')
}
@Test(expected = IllegalArgumentException)
void testParseWhitespaceString() {
Jwts.parser().build().parse(' ')
}
@Test
void testParseClaimsWithLeadingAndTrailingWhitespace() {
String whitespaceChars = ' \t \n \r '
String claimsJson = whitespaceChars + '{"sub":"joe"}' + whitespaceChars
String header = Encoders.BASE64URL.encode('{"alg":"none"}'.getBytes(StandardCharsets.UTF_8))
String claims = Encoders.BASE64URL.encode(claimsJson.getBytes(StandardCharsets.UTF_8))
String compact = header + '.' + claims + '.'
def jwt = Jwts.parser().unsecured().build().parseUnsecuredClaims(compact)
assertEquals 'none', jwt.header.getAlgorithm()
assertEquals 'joe', jwt.payload.getSubject()
}
@Test
void testParseWithNoPeriods() {
try {
Jwts.parser().build().parse('foo')
fail()
} catch (MalformedJwtException e) {
//noinspection GroovyAccessibility
String expected = JwtTokenizer.DELIM_ERR_MSG_PREFIX + '0'
assertEquals expected, e.message
}
}
@Test
void testParseWithOnePeriodOnly() {
try {
Jwts.parser().build().parse('.')
fail()
} catch (MalformedJwtException e) {
//noinspection GroovyAccessibility
String expected = JwtTokenizer.DELIM_ERR_MSG_PREFIX + '1'
assertEquals expected, e.message
}
}
@Test
void testParseWithTwoPeriodsOnly() {
try {
Jwts.parser().build().parse('..')
fail()
} catch (MalformedJwtException e) {
String msg = 'Compact JWT strings MUST always have a Base64Url protected header per ' +
'https://tools.ietf.org/html/rfc7519#section-7.2 (steps 2-4).'
assertEquals msg, e.message
}
}
@Test
void testParseWithHeaderOnly() {
String unsecuredJwt = base64Url("{\"alg\":\"none\"}") + ".."
Jwt jwt = Jwts.parser().unsecured().build().parse(unsecuredJwt)
assertEquals "none", jwt.getHeader().get("alg")
}
@Test
void testParseWithSignatureOnly() {
try {
Jwts.parser().build().parse('..bar')
fail()
} catch (MalformedJwtException e) {
assertEquals 'Compact JWT strings MUST always have a Base64Url protected header per https://tools.ietf.org/html/rfc7519#section-7.2 (steps 2-4).', e.message
}
}
@Test
void testParseWithMissingRequiredSignature() {
Key key = Jwts.SIG.HS256.key().build()
String compact = Jwts.builder().setSubject('foo').signWith(key).compact()
int i = compact.lastIndexOf('.')
String missingSig = compact.substring(0, i + 1)
try {
Jwts.parser().unsecured().setSigningKey(key).build().parseSignedClaims(missingSig)
fail()
} catch (MalformedJwtException expected) {
String s = String.format(DefaultJwtParser.MISSING_JWS_DIGEST_MSG_FMT, 'HS256')
assertEquals s, expected.getMessage()
}
}
@Test
void testWithInvalidCompressionAlgorithm() {
try {
Jwts.builder().header().add('zip', 'CUSTOM').and().id("andId").compact()
} catch (CompressionException e) {
assertEquals "Unsupported compression algorithm 'CUSTOM'", e.getMessage()
}
}
@Test
void testConvenienceIssuer() {
String compact = Jwts.builder().setIssuer("Me").compact()
Claims claims = Jwts.parser().unsecured().build().parse(compact).payload as Claims
assertEquals 'Me', claims.getIssuer()
compact = Jwts.builder().setSubject("Joe")
.setIssuer("Me") //set it
.setIssuer(null) //null should remove it
.compact()
claims = Jwts.parser().unsecured().build().parse(compact).payload as Claims
assertNull claims.getIssuer()
}
@Test
void testConvenienceSubject() {
String compact = Jwts.builder().setSubject("Joe").compact()
Claims claims = Jwts.parser().unsecured().build().parse(compact).payload as Claims
assertEquals 'Joe', claims.getSubject()
compact = Jwts.builder().setIssuer("Me")
.setSubject("Joe") //set it
.setSubject(null) //null should remove it
.compact()
claims = Jwts.parser().unsecured().build().parse(compact).payload as Claims
assertNull claims.getSubject()
}
@Test
void testConvenienceAudience() {
String compact = Jwts.builder().setAudience("You").compact()
Claims claims = Jwts.parser().unsecured().build().parse(compact).payload as Claims
assertEquals 'You', claims.getAudience().iterator().next()
compact = Jwts.builder().setIssuer("Me")
.setAudience("You") //set it
.setAudience(null) //null should remove it
.compact()
claims = Jwts.parser().unsecured().build().parse(compact).payload as Claims
assertNull claims.getAudience()
}
@Test
void testConvenienceExpiration() {
Date then = laterDate(10000)
String compact = Jwts.builder().setExpiration(then).compact()
Claims claims = Jwts.parser().unsecured().build().parse(compact).payload as Claims
def claimedDate = claims.getExpiration()
assertEquals then, claimedDate
compact = Jwts.builder().setIssuer("Me")
.setExpiration(then) //set it
.setExpiration(null) //null should remove it
.compact()
claims = Jwts.parser().unsecured().build().parse(compact).payload as Claims
assertNull claims.getExpiration()
}
@Test
void testConvenienceNotBefore() {
Date now = now() //jwt exp only supports *seconds* since epoch:
String compact = Jwts.builder().setNotBefore(now).compact()
Claims claims = Jwts.parser().unsecured().build().parse(compact).payload as Claims
def claimedDate = claims.getNotBefore()
assertEquals now, claimedDate
compact = Jwts.builder().setIssuer("Me")
.setNotBefore(now) //set it
.setNotBefore(null) //null should remove it
.compact()
claims = Jwts.parser().unsecured().build().parse(compact).payload as Claims
assertNull claims.getNotBefore()
}
@Test
void testConvenienceIssuedAt() {
Date now = now() //jwt exp only supports *seconds* since epoch:
String compact = Jwts.builder().setIssuedAt(now).compact()
Claims claims = Jwts.parser().unsecured().build().parse(compact).payload as Claims
def claimedDate = claims.getIssuedAt()
assertEquals now, claimedDate
compact = Jwts.builder().setIssuer("Me")
.setIssuedAt(now) //set it
.setIssuedAt(null) //null should remove it
.compact()
claims = Jwts.parser().unsecured().build().parse(compact).payload as Claims
assertNull claims.getIssuedAt()
}
@Test
void testConvenienceId() {
String id = UUID.randomUUID().toString()
String compact = Jwts.builder().setId(id).compact()
Claims claims = Jwts.parser().unsecured().build().parse(compact).payload as Claims
assertEquals id, claims.getId()
compact = Jwts.builder().setIssuer("Me")
.setId(id) //set it
.setId(null) //null should remove it
.compact()
claims = Jwts.parser().unsecured().build().parse(compact).payload as Claims
assertNull claims.getId()
}
@Test
void testUncompressedJwt() {
def alg = Jwts.SIG.HS256
SecretKey key = alg.key().build()
String id = UUID.randomUUID().toString()
String compact = Jwts.builder().id(id).issuer("an issuer").signWith(key, alg)
.claim("state", "hello this is an amazing jwt").compact()
def jws = Jwts.parser().verifyWith(key).build().parseSignedClaims(compact)
Claims claims = jws.payload
assertNull jws.header.getCompressionAlgorithm()
assertEquals id, claims.getId()
assertEquals "an issuer", claims.getIssuer()
assertEquals "hello this is an amazing jwt", claims.state
}
@Test
void testCompressedJwtWithDeflate() {
def alg = Jwts.SIG.HS256
SecretKey key = alg.key().build()
String id = UUID.randomUUID().toString()
String compact = Jwts.builder().id(id).issuer("an issuer").signWith(key, alg)
.claim("state", "hello this is an amazing jwt").compressWith(Jwts.ZIP.DEF).compact()
def jws = Jwts.parser().verifyWith(key).build().parseSignedClaims(compact)
Claims claims = jws.payload
assertEquals "DEF", jws.header.getCompressionAlgorithm()
assertEquals id, claims.getId()
assertEquals "an issuer", claims.getIssuer()
assertEquals "hello this is an amazing jwt", claims.state
}
@Test
void testCompressedJwtWithGZIP() {
def alg = Jwts.SIG.HS256
SecretKey key = alg.key().build()
String id = UUID.randomUUID().toString()
String compact = Jwts.builder().id(id).issuer("an issuer").signWith(key, alg)
.claim("state", "hello this is an amazing jwt").compressWith(Jwts.ZIP.GZIP).compact()
def jws = Jwts.parser().verifyWith(key).build().parseSignedClaims(compact)
Claims claims = jws.payload
assertEquals "GZIP", jws.header.getCompressionAlgorithm()
assertEquals id, claims.getId()
assertEquals "an issuer", claims.getIssuer()
assertEquals "hello this is an amazing jwt", claims.state
}
@Test
void testCompressedWithCustomResolver() {
def alg = Jwts.SIG.HS256
SecretKey key = alg.key().build()
String id = UUID.randomUUID().toString()
String compact = Jwts.builder().id(id).issuer("an issuer").signWith(key, alg)
.claim("state", "hello this is an amazing jwt").compressWith(new GzipCompressionAlgorithm() {
@Override
String getId() {
return "CUSTOM"
}
}).compact()
def jws = Jwts.parser().verifyWith(key).setCompressionCodecResolver(new CompressionCodecResolver() {
@Override
CompressionCodec resolveCompressionCodec(Header header) throws CompressionException {
String algorithm = header.getCompressionAlgorithm()
//noinspection ChangeToOperator
if ("CUSTOM".equals(algorithm)) {
return Jwts.ZIP.GZIP as CompressionCodec
} else {
return null
}
}
}).build().parseSignedClaims(compact)
Claims claims = jws.payload
assertEquals "CUSTOM", jws.header.getCompressionAlgorithm()
assertEquals id, claims.getId()
assertEquals "an issuer", claims.getIssuer()
assertEquals "hello this is an amazing jwt", claims.state
}
@Test(expected = UnsupportedJwtException.class)
void testCompressedJwtWithUnrecognizedHeader() {
def alg = Jwts.SIG.HS256
SecretKey key = alg.key().build()
String id = UUID.randomUUID().toString()
String compact = Jwts.builder().setId(id).setAudience("an audience").signWith(key, alg)
.claim("state", "hello this is an amazing jwt").compressWith(new GzipCompressionAlgorithm() {
@Override
String getId() {
return "CUSTOM"
}
}).compact()
Jwts.parser().setSigningKey(key).build().parseSignedClaims(compact)
}
@Test
void testCompressStringPayloadWithDeflate() {
def alg = Jwts.SIG.HS256
SecretKey key = alg.key().build()
String payload = "this is my test for a payload"
String compact = Jwts.builder().setPayload(payload).signWith(key, alg)
.compressWith(Jwts.ZIP.DEF).compact()
def jws = Jwts.parser().setSigningKey(key).build().parseSignedContent(compact)
assertEquals "DEF", jws.header.getCompressionAlgorithm()
assertEquals "this is my test for a payload", new String(jws.payload, StandardCharsets.UTF_8)
}
@Test
void testHS256() {
testHmac(Jwts.SIG.HS256)
}
@Test
void testHS384() {
testHmac(Jwts.SIG.HS384)
}
@Test
void testHS512() {
testHmac(Jwts.SIG.HS512)
}
@Test
void testRS256() {
testRsa(Jwts.SIG.RS256)
}
@Test
void testRS384() {
testRsa(Jwts.SIG.RS384)
}
@Test
void testRS512() {
testRsa(Jwts.SIG.RS512)
}
@Test
void testPS256() {
testRsa(Jwts.SIG.PS256)
}
@Test
void testPS384() {
testRsa(Jwts.SIG.PS384)
}
@Test
void testPS512() {
testRsa(Jwts.SIG.PS512)
}
@Test
void testES256() {
testEC(Jwts.SIG.ES256)
}
@Test
void testES384() {
testEC(Jwts.SIG.ES384)
}
@Test
void testES512() {
testEC(Jwts.SIG.ES512)
}
@Test
void testEdDSA() {
testEC(Jwts.SIG.EdDSA)
}
@Test
void testEd25519() {
testEC(Jwts.SIG.EdDSA, TestKeys.forAlgorithm(Jwks.CRV.Ed25519).pair)
}
@Test
void testEd448() {
testEC(Jwts.SIG.EdDSA, TestKeys.forAlgorithm(Jwks.CRV.Ed448).pair)
}
@Test
void testES256WithPrivateKeyValidation() {
def alg = Jwts.SIG.ES256
try {
testEC(alg, true)
fail("EC private keys cannot be used to validate EC signatures.")
} catch (IllegalArgumentException e) {
assertEquals DefaultJwtParser.PRIV_KEY_VERIFY_MSG, e.getMessage()
}
}
@Test(expected = WeakKeyException)
void testparseSignedClaimsWithWeakHmacKey() {
def alg = Jwts.SIG.HS384
def key = alg.key().build()
def weakKey = Jwts.SIG.HS256.key().build()
String jws = Jwts.builder().setSubject("Foo").signWith(key, alg).compact()
Jwts.parser().setSigningKey(weakKey).build().parseSignedClaims(jws)
fail('parseSignedClaims must fail for weak keys')
}
/**
* @since 0.11.5
*/
@Test
void testBuilderWithEcdsaPublicKey() {
def builder = Jwts.builder().setSubject('foo')
def pair = TestKeys.ES256.pair
try {
builder.signWith(pair.public, SignatureAlgorithm.ES256) //public keys can't be used to create signatures
} catch (InvalidKeyException expected) {
String msg = "ECDSA signing keys must be PrivateKey instances."
assertEquals msg, expected.getMessage()
}
}
/**
* @since 0.11.5 as part of testing guards against JVM CVE-2022-21449
*/
@Test
void testBuilderWithMismatchedEllipticCurveKeyAndAlgorithm() {
def builder = Jwts.builder().setSubject('foo')
def pair = TestKeys.ES384.pair
try {
builder.signWith(pair.private, SignatureAlgorithm.ES256)
//ES384 keys can't be used to create ES256 signatures
} catch (InvalidKeyException expected) {
String msg = "EllipticCurve key has a field size of 48 bytes (384 bits), but ES256 requires a " +
"field size of 32 bytes (256 bits) per [RFC 7518, Section 3.4 (validation)]" +
"(https://www.rfc-editor.org/rfc/rfc7518.html#section-3.4)."
assertEquals msg, expected.getMessage()
}
}
/**
* @since 0.11.5 as part of testing guards against JVM CVE-2022-21449
*/
@Test
void testParserWithMismatchedEllipticCurveKeyAndAlgorithm() {
def pair = TestKeys.ES256.pair
def jws = Jwts.builder().setSubject('foo').signWith(pair.private).compact()
def parser = Jwts.parser().setSigningKey(TestKeys.ES384.pair.public).build()
try {
parser.parseSignedClaims(jws)
} catch (UnsupportedJwtException expected) {
String msg = 'The parsed JWT indicates it was signed with the \'ES256\' signature algorithm, but ' +
'the provided sun.security.ec.ECPublicKeyImpl key may not be used to verify ES256 signatures. ' +
'Because the specified key reflects a specific and expected algorithm, and the JWT does not ' +
'reflect this algorithm, it is likely that the JWT was not expected and therefore should not ' +
'be trusted. Another possibility is that the parser was provided the incorrect signature ' +
'verification key, but this cannot be assumed for security reasons.'
assertEquals msg, expected.getMessage()
}
}
/**
* @since 0.11.5 as part of testing guards against JVM CVE-2022-21449
*/
@Test(expected = io.jsonwebtoken.security.SignatureException)
void testEcdsaInvalidSignatureValue() {
def withoutSignature = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ZXN0IjoidGVzdCIsImlhdCI6MTQ2NzA2NTgyN30"
def invalidEncodedSignature = "_____wAAAAD__________7zm-q2nF56E87nKwvxjJVH_____AAAAAP__________vOb6racXnoTzucrC_GMlUQ"
String jws = withoutSignature + '.' + invalidEncodedSignature
def keypair = Jwts.SIG.ES256.keyPair().build()
Jwts.parser().setSigningKey(keypair.public).build().parseSignedClaims(jws)
}
//Asserts correct/expected behavior discussed in https://github.com/jwtk/jjwt/issues/20
@Test
void testparseSignedClaimsWithUnsignedJwt() {
//create random signing key for testing:
def alg = Jwts.SIG.HS256
SecretKey key = alg.key().build()
String notSigned = Jwts.builder().setSubject("Foo").compact()
try {
Jwts.parser().unsecured().setSigningKey(key).build().parseSignedClaims(notSigned)
fail('parseSignedClaims must fail for unsigned JWTs')
} catch (UnsupportedJwtException expected) {
assertEquals 'Unexpected unsecured Claims JWT.', expected.message
}
}
/**
* @since 0.12.0
*/
@Test
void testParseJweMissingAlg() {
def h = base64Url('{"enc":"A128GCM"}')
def c = base64Url('{"sub":"joe"}')
def compact = h + '.ecek.iv.' + c + '.tag'
try {
Jwts.parser().build().parseEncryptedClaims(compact)
fail()
} catch (MalformedJwtException e) {
assertEquals DefaultJwtParser.MISSING_JWE_ALG_MSG, e.getMessage()
}
}
/**
* @since 0.12.0
*/
@Test
void testParseJweEmptyAlg() {
def h = base64Url('{"alg":"","enc":"A128GCM"}')
def c = base64Url('{"sub":"joe"}')
def compact = h + '.ecek.iv.' + c + '.tag'
try {
Jwts.parser().build().parseEncryptedClaims(compact)
fail()
} catch (MalformedJwtException e) {
assertEquals DefaultJwtParser.MISSING_JWE_ALG_MSG, e.getMessage()
}
}
/**
* @since 0.12.0
*/
@Test
void testParseJweWhitespaceAlg() {
def h = base64Url('{"alg":" ","enc":"A128GCM"}')
def c = base64Url('{"sub":"joe"}')
def compact = h + '.ecek.iv.' + c + '.tag'
try {
Jwts.parser().build().parseEncryptedClaims(compact)
fail()
} catch (MalformedJwtException e) {
assertEquals DefaultJwtParser.MISSING_JWE_ALG_MSG, e.getMessage()
}
}
/**
* @since 0.12.0
*/
@Test
void testParseJweWithNoneAlg() {
def h = base64Url('{"alg":"none","enc":"A128GCM"}')
def c = base64Url('{"sub":"joe"}')
def compact = h + '.ecek.iv.' + c + '.tag'
try {
Jwts.parser().build().parseEncryptedClaims(compact)
fail()
} catch (MalformedJwtException e) {
assertEquals DefaultJwtParser.JWE_NONE_MSG, e.getMessage()
}
}
/**
* @since 0.12.0
*/
@Test
void testParseJweWithMissingAadTag() {
def h = base64Url('{"alg":"dir","enc":"A128GCM"}')
def c = base64Url('{"sub":"joe"}')
def compact = h + '.ecek.iv.' + c + '.'
try {
Jwts.parser().build().parseEncryptedClaims(compact)
fail()
} catch (MalformedJwtException e) {
String expected = String.format(DefaultJwtParser.MISSING_JWE_DIGEST_MSG_FMT, 'dir')
assertEquals expected, e.getMessage()
}
}
/**
* @since 0.12.0
*/
@Test
void testParseJweWithEmptyAadTag() {
def h = base64Url('{"alg":"dir","enc":"A128GCM"}')
def c = base64Url('{"sub":"joe"}')
// our decoder skips invalid Base64Url characters, so this decodes to empty which is not allowed:
def tag = '&'
def compact = h + '.IA==.IA==.' + c + '.' + tag
try {
Jwts.parser().build().parseEncryptedClaims(compact)
fail()
} catch (MalformedJwtException e) {
String expected = 'Compact JWE strings must always contain an AAD Authentication Tag.'
assertEquals expected, e.getMessage()
}
}
/**
* @since 0.12.0
*/
@Test
void testParseJweWithMissingRequiredBody() {
def h = base64Url('{"alg":"dir","enc":"A128GCM"}')
def compact = h + '.ecek.iv..tag'
try {
Jwts.parser().build().parseEncryptedClaims(compact)
fail()
} catch (MalformedJwtException e) {
String expected = 'Compact JWE strings MUST always contain a payload (ciphertext).'
assertEquals expected, e.getMessage()
}
}
/**
* @since 0.12.0
*/
@Test
void testParseJweWithEmptyEncryptedKey() {
def h = base64Url('{"alg":"dir","enc":"A128GCM"}')
def c = base64Url('{"sub":"joe"}')
// our decoder skips invalid Base64Url characters, so this decodes to empty which is not allowed:
def encodedKey = '&'
def compact = h + '.' + encodedKey + '.iv.' + c + '.tag'
try {
Jwts.parser().build().parseEncryptedClaims(compact)
fail()
} catch (MalformedJwtException e) {
String expected = 'Compact JWE string represents an encrypted key, but the key is empty.'
assertEquals expected, e.getMessage()
}
}
/**
* @since 0.12.0
*/
@Test
void testParseJweWithMissingInitializationVector() {
def h = base64Url('{"alg":"dir","enc":"A128GCM"}')
def c = base64Url('{"sub":"joe"}')
def compact = h + '.IA==..' + c + '.tag'
try {
Jwts.parser().build().parseEncryptedClaims(compact)
fail()
} catch (MalformedJwtException e) {
String expected = 'Compact JWE strings must always contain an Initialization Vector.'
assertEquals expected, e.getMessage()
}
}
/**
* @since 0.12.0
*/
@Test
void testParseJweWithMissingEncHeader() {
def h = base64Url('{"alg":"dir"}')
def c = base64Url('{"sub":"joe"}')
def ekey = 'IA=='
def iv = 'IA=='
def tag = 'IA=='
def compact = "$h.$ekey.$iv.$c.$tag" as String
try {
Jwts.parser().build().parseEncryptedClaims(compact)
fail()
} catch (MalformedJwtException e) {
assertEquals DefaultJwtParser.MISSING_ENC_MSG, e.getMessage()
}
}
/**
* @since 0.12.0
*/
@Test
void testParseJweWithUnrecognizedEncValue() {
def h = base64Url('{"alg":"dir","enc":"foo"}')
def c = base64Url('{"sub":"joe"}')
def ekey = 'IA=='
def iv = 'IA=='
def tag = 'IA=='
def compact = "$h.$ekey.$iv.$c.$tag" as String
try {
Jwts.parser().build().parseEncryptedClaims(compact)
fail()
} catch (UnsupportedJwtException e) {
String expected = "Unrecognized JWE 'enc' (Encryption Algorithm) header value: foo"
assertEquals expected, e.getMessage()
}
}
/**
* @since 0.12.0
*/
@Test
void testParseJweWithUnrecognizedAlgValue() {
def h = base64Url('{"alg":"bar","enc":"A128GCM"}')