JwtHmac implements JwtMac { @Override public Jwt verifyCompact(String compact, JwtValidator validator) throws GeneralSecurityException { String[] parts = compact.split("\\.", -1); if (parts.length != 3) { throw new JwtInvalidException( "only tokens in JWS compact serialization format are supported"); } String input = parts[0] + "." + parts[1]; byte[] expectedTag = Base64.urlSafeDecode(parts[2]); mac.verifyMac(expectedTag, input.getBytes(ASCII)); ToBeSignedJwt token = new ToBeSignedJwt.Builder(input).build(); return validator.validate(this.algo, token); } JwtHmac(String algo, java.security.Key key); @Override String createCompact(ToBeSignedJwt token); @Override Jwt verifyCompact(String compact, JwtValidator validator);  }
@Test public void verifyCompact_rfc7515TestVector_shouldThrow() throws Exception { String key = "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"; String compact = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9." + "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ." + "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; String algo = "HS256"; SecretKey secretKey = new SecretKeySpec(Base64.urlSafeDecode(key), "HMAC"); JwtHmac mac = new JwtHmac(algo, secretKey); JwtValidator validator = new JwtValidator.Builder().build(); assertThrows(JwtExpiredException.class, () -> mac.verifyCompact(compact, validator)); }
@Test public void verifyCompact_rfc7515TestVector_fixedClock_success() throws Exception { String key = "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"; String compact = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9." + "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ." + "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; String algo = "HS256"; SecretKey secretKey = new SecretKeySpec(Base64.urlSafeDecode(key), "HMAC"); JwtHmac mac = new JwtHmac(algo, secretKey); String instant = "2011-03-22T18:42:00Z"; Clock clock = Clock.fixed(Instant.parse(instant), ZoneOffset.UTC); JwtValidator validator = new JwtValidator.Builder().setClock(clock).build(); Jwt token = mac.verifyCompact(compact, validator); assertThat(token.getAlgorithm()).isEqualTo(algo); assertThat(token.getType()).isEqualTo("JWT"); assertThat(token.getIssuer()).isEqualTo("joe"); boolean value = (boolean) token.getClaim("http: assertThat(value).isTrue(); }