|
| 1 | +package com.baeldung.jwt.replace_deprecated_jwt_parser; |
| 2 | + |
| 3 | +import static org.junit.Assert.assertEquals; |
| 4 | + |
| 5 | +import java.util.Date; |
| 6 | + |
| 7 | +import javax.crypto.SecretKey; |
| 8 | + |
| 9 | +import org.junit.jupiter.api.Assertions; |
| 10 | +import org.junit.jupiter.api.BeforeEach; |
| 11 | +import org.junit.jupiter.api.Test; |
| 12 | + |
| 13 | +import io.jsonwebtoken.Claims; |
| 14 | +import io.jsonwebtoken.Jws; |
| 15 | +import io.jsonwebtoken.JwtParser; |
| 16 | +import io.jsonwebtoken.Jwts; |
| 17 | +import io.jsonwebtoken.SignatureAlgorithm; |
| 18 | +import io.jsonwebtoken.security.Keys; |
| 19 | + |
| 20 | +class DeprecatedParserUnitTest { |
| 21 | + |
| 22 | + private SecretKey key; |
| 23 | + private String token; |
| 24 | + |
| 25 | + @BeforeEach |
| 26 | + public void setup() { |
| 27 | + key = Keys.secretKeyFor(SignatureAlgorithm.HS256); |
| 28 | + token = Jwts.builder() |
| 29 | + .setSubject("baeldung") |
| 30 | + .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60)) |
| 31 | + .signWith(key) |
| 32 | + .compact(); |
| 33 | + } |
| 34 | + |
| 35 | + @Test |
| 36 | + void givenDeprecatedParser_whenParsingTokenInMultipleThreads_thenMayNotBeThreadSafe() { |
| 37 | + |
| 38 | + JwtParser parser = Jwts.parser() |
| 39 | + .setSigningKey(key); |
| 40 | + |
| 41 | + Runnable parseTask = () -> { |
| 42 | + Jws<Claims> claimsJws = parser.parseClaimsJws(token); |
| 43 | + Claims claims = claimsJws.getBody(); |
| 44 | + assertEquals("baeldung", claims.getSubject()); |
| 45 | + }; |
| 46 | + |
| 47 | + Thread thread1 = new Thread(parseTask); |
| 48 | + Thread thread2 = new Thread(parseTask); |
| 49 | + |
| 50 | + thread1.start(); |
| 51 | + thread2.start(); |
| 52 | + |
| 53 | + try { |
| 54 | + thread1.join(); |
| 55 | + thread2.join(); |
| 56 | + } catch (InterruptedException e) { |
| 57 | + Assertions.fail("Thread execution was interrupted"); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + @Test |
| 62 | + void givenDeprecatedParser_whenRequiringSpecificClaim_thenShouldParseSuccessfully() { |
| 63 | + JwtParser parser = Jwts.parser() |
| 64 | + .setSigningKey(key); |
| 65 | + |
| 66 | + Claims claims = parser.parseClaimsJws(token) |
| 67 | + .getBody(); |
| 68 | + |
| 69 | + Assertions.assertEquals("baeldung", claims.getSubject()); |
| 70 | + } |
| 71 | + |
| 72 | + @Test |
| 73 | + public void givenDeprecatedParser_whenRequiringNonExistentClaim_thenShouldFail() { |
| 74 | + |
| 75 | + JwtParser parser = Jwts.parser() |
| 76 | + .setSigningKey(key); |
| 77 | + |
| 78 | + try { |
| 79 | + Claims claims = parser.parseClaimsJws(token) |
| 80 | + .getBody(); |
| 81 | + Assertions.assertEquals(null, claims.get("non-existent-claim")); |
| 82 | + } catch (Exception e) { |
| 83 | + Assertions.assertEquals("JWT claims string is empty.", e.getMessage()); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | +} |
0 commit comments