diff --git a/lib/build.gradle b/lib/build.gradle index 2a7694c..b4294d9 100644 --- a/lib/build.gradle +++ b/lib/build.gradle @@ -37,6 +37,12 @@ dependencies { compile 'com.fasterxml.jackson.core:jackson-databind:2.9.2' compile 'commons-codec:commons-codec:1.11' compile 'com.google.code.gson:gson:2.8.2' + compile 'com.auth0:jwks-rsa:0.3.0' + compile 'com.nimbusds:nimbus-jose-jwt:2.19.1' + compile 'org.apache.httpcomponents:httpcore:4.4.1' + compile 'org.apache.httpcomponents:httpclient:4.5' + compile group: 'org.slf4j', name:'slf4j-api', version: '1.7.2' + compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1' testCompile 'org.bouncycastle:bcprov-jdk15on:1.58' testCompile 'junit:junit:4.12' testCompile 'net.jodah:concurrentunit:0.4.3' @@ -61,4 +67,4 @@ test { task clean(type: Delete) { delete rootProject.buildDir delete 'CHANGELOG.md.release' -} +} \ No newline at end of file diff --git a/lib/jwksRSA.json b/lib/jwksRSA.json new file mode 100644 index 0000000..875992e --- /dev/null +++ b/lib/jwksRSA.json @@ -0,0 +1 @@ +{"keys":[{"alg":"RS256","kty":"RSA","use":"sig","x5c":["MIIDDTCCAfWgAwIBAgIJAJVkuSv2H8mDMA0GCSqGSIb3DQEBBQUAMB0xGzAZBgNVBAMMEnNhbmRyaW5vLmF1dGgwLmNvbTAeFw0xNDA1MTQyMTIyMjZaFw0yODAxMjEyMTIyMjZaMB0xGzAZBgNVBAMMEnNhbmRyaW5vLmF1dGgwLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL6jWASkHhXz5Ug6t5BsYBrXDIgrWu05f3oq2fE+5J5REKJiY0Ddc+Kda34ZwOptnUoef3JwKPDAckTJQDugweNNZPwOmFMRKj4xqEpxEkIX8C+zHs41Q6x54ZZy0xU+WvTGcdjzyZTZ/h0iOYisswFQT/s6750tZG0BOBtZ5qS/80tmWH7xFitgewdWteJaASE/eO1qMtdNsp9fxOtN5U/pZDUyFm3YRfOcODzVqp3wOz+dcKb7cdZN11EYGZOkjEekpcedzHCo9H4aOmdKCpytqL/9FXoihcBMg39s1OW3cfwfgf5/kvOJdcqR4PoATQTfsDVoeMWVB4XLGR6SC5kCAwEAAaNQME4wHQYDVR0OBBYEFHDYn9BQdup1CoeoFi0Rmf5xn/W9MB8GA1UdIwQYMBaAFHDYn9BQdup1CoeoFi0Rmf5xn/W9MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAGLpQZdd2ICVnGjc6CYfT3VNoujKYWk7E0shGaCXFXptrZ8yaryfo6WAizTfgOpQNJH+Jz+QsCjvkRt6PBSYX/hb5OUDU2zNJN48/VOw57nzWdjI70H2Ar4oJLck36xkIRs/+QX+mSNCjZboRwh0LxanXeALHSbCgJkbzWbjVnfJEQUP9P/7NGf0MkO5I95C/Pz9g91y8gU+R3imGppLy9Zx+OwADFwKAEJak4JrNgcjHBQenakAXnXP6HG4hHH4MzO8LnLiKv8ZkKVL67da/80PcpO0miMNPaqBBMd2Cy6GzQYE0ag6k0nk+DMIFn7K+o21gjUuOEJqIbAvhbf2KcM="],"n":"vqNYBKQeFfPlSDq3kGxgGtcMiCta7Tl_eirZ8T7knlEQomJjQN1z4p1rfhnA6m2dSh5_cnAo8MByRMlAO6DB401k_A6YUxEqPjGoSnESQhfwL7MezjVDrHnhlnLTFT5a9MZx2PPJlNn-HSI5iKyzAVBP-zrvnS1kbQE4G1nmpL_zS2ZYfvEWK2B7B1a14loBIT947Woy102yn1_E603lT-lkNTIWbdhF85w4PNWqnfA7P51wpvtx1k3XURgZk6SMR6Slx53McKj0fho6Z0oKnK2ov_0VeiKFwEyDf2zU5bdx_B-B_n-S84l1ypHg-gBNBN-wNWh4xZUHhcsZHpILmQ","e":"AQAB","kid":"8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI","x5t":"RkI5MjI5OUY5ODc1N0Q4QzM0OUYzNkVGMTJDOUEzQkFCOTU3NjE2Rg"}]} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/JWTDecoder.java b/lib/src/main/java/com/auth0/jwt/JWTDecoder.java index 7a967fb..e6a25aa 100644 --- a/lib/src/main/java/com/auth0/jwt/JWTDecoder.java +++ b/lib/src/main/java/com/auth0/jwt/JWTDecoder.java @@ -20,23 +20,26 @@ package com.auth0.jwt; import com.auth0.jwt.creators.EncodeType; -import com.auth0.jwt.creators.JWTCreator; -import com.auth0.jwt.exceptions.JWTDecodeException; +import com.auth0.jwt.creators.FbJwtCreator; +import com.auth0.jwt.creators.GoogleJwtCreator; +import com.auth0.jwt.creators.GoogleOrFbJwtCreator; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.impl.JWTParser; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Header; import com.auth0.jwt.interfaces.Payload; -import org.apache.commons.codec.binary.Base32; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.binary.Hex; -import org.apache.commons.codec.binary.StringUtils; - +import com.auth0.jwt.utils.TokenUtils; +import com.google.common.base.Strings; import java.net.URLDecoder; -import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.List; import java.util.Map; +import org.apache.commons.codec.binary.Base32; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.codec.binary.Hex; +import org.apache.commons.codec.binary.StringUtils; /** * The JWTDecoder class holds the decode method to parse a given JWT token into it's JWT representation. @@ -47,6 +50,8 @@ public final class JWTDecoder implements DecodedJWT { private final String[] parts; private final Header header; private final Payload payload; + private static final String ISSUER_FACEBOOK = "facebook"; + private static final String ISSUER_GOOGLE = "google"; public JWTDecoder(String jwt, EncodeType encodeType) throws Exception { parts = TokenUtils.splitToken(jwt); @@ -55,13 +60,13 @@ public JWTDecoder(String jwt, EncodeType encodeType) throws Exception { String payloadJson = null; switch (encodeType) { case Base16: - headerJson = URLDecoder.decode(new String(Hex.decodeHex(parts[0])), "UTF-8"); - payloadJson = URLDecoder.decode(new String(Hex.decodeHex(parts[1])), "UTF-8"); + headerJson = URLDecoder.decode(new String(Hex.decodeHex(parts[0])), StandardCharsets.UTF_8.name()); + payloadJson = URLDecoder.decode(new String(Hex.decodeHex(parts[1])), StandardCharsets.UTF_8.name()); break; case Base32: Base32 base32 = new Base32(); - headerJson = URLDecoder.decode(new String(base32.decode(parts[0]), "UTF-8")); - payloadJson = URLDecoder.decode(new String(base32.decode(parts[1]), "UTF-8")); + headerJson = URLDecoder.decode(new String(base32.decode(parts[0]), StandardCharsets.UTF_8.name())); + payloadJson = URLDecoder.decode(new String(base32.decode(parts[1]), StandardCharsets.UTF_8.name())); break; case Base64: headerJson = StringUtils.newStringUtf8(Base64.decodeBase64(parts[0])); @@ -161,4 +166,39 @@ public String getSignature() { public String getToken() { return String.format("%s.%s.%s", parts[0], parts[1], parts[2]); } + + public GoogleOrFbJwtCreator decodeJWT(DecodedJWT jwt) { + Map claims = jwt.getClaims(); + Claim issuerClaim = claims.get(Claims.ISSUER); + if(issuerClaim == null) { + throw new IllegalArgumentException("null issuer claim"); + } + String issuer = issuerClaim.asString(); + GoogleOrFbJwtCreator googleOrFbJwtCreator = null; + if(Strings.isNullOrEmpty(issuer)) { + throw new IllegalArgumentException("null or empty issuer"); + } + if(ISSUER_FACEBOOK.contains(issuer)) { + googleOrFbJwtCreator = FbJwtCreator.build() + .withExp(claims.get(Claims.EXPIRES_AT).asDate()) + .withIat(claims.get(Claims.ISSUED_AT).asDate()) + .withAppId(claims.get(Claims.APP_ID).asString()) + .withUserId(claims.get(Claims.USER_ID).asString()); + } else if(ISSUER_GOOGLE.contains(issuer)) { + googleOrFbJwtCreator = GoogleJwtCreator.build() + .withPicture(claims.get(Claims.PICTURE).asString()) + .withEmail(claims.get(Claims.EMAIL).asString()) + .withIssuer(claims.get(Claims.ISSUER).asString()) + .withSubject(claims.get(Claims.SUBJECT).asString()) + .withAudience(claims.get(Claims.AUDIENCE).asString()) + .withExp(claims.get(Claims.EXPIRES_AT).asDate()) + .withIat(claims.get(Claims.ISSUED_AT).asDate()) + .withName(claims.get(Claims.NAME).asString()); + } else { + throw new IllegalArgumentException("Not from a Facebook or Google issuer"); + } + + return googleOrFbJwtCreator; + } + } diff --git a/lib/src/main/java/com/auth0/jwt/algorithms/Algorithm.java b/lib/src/main/java/com/auth0/jwt/algorithms/Algorithm.java index a63c454..2420fa5 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/Algorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/Algorithm.java @@ -25,9 +25,14 @@ import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.ECDSAKeyProvider; import com.auth0.jwt.interfaces.RSAKeyProvider; - import java.io.UnsupportedEncodingException; -import java.security.interfaces.*; +import java.security.interfaces.ECKey; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.ECPublicKey; +import java.security.interfaces.RSAKey; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; + /** * The Algorithm class represents an algorithm to be used in the Signing or Verification process of a Token. @@ -385,6 +390,15 @@ public String toString() { */ public abstract void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception; + /** + * Verify the given token including x509 functionality + * @param jwt the already decoded JWT that it's going to be verified. + * @param jwksFile + * @param pemFile + * @throws Exception + */ + public abstract void verifyWithX509(DecodedJWT jwt, String jwksFile, String pemFile) throws Exception; + /** * Sign the given content using this Algorithm instance. * @@ -406,4 +420,4 @@ public boolean equals(Object algorithmParam) { Algorithm algorithm = (Algorithm) algorithmParam; return this.description.equals(algorithm.description) && this.name.equals(algorithm.name); } -} +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/algorithms/CryptoHelper.java b/lib/src/main/java/com/auth0/jwt/algorithms/CryptoHelper.java index 43b6f82..271f817 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/CryptoHelper.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/CryptoHelper.java @@ -19,9 +19,15 @@ package com.auth0.jwt.algorithms; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.Signature; +import java.security.SignatureException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; -import java.security.*; class CryptoHelper { diff --git a/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java b/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java index 91a7fef..95b2ef8 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java @@ -24,11 +24,6 @@ import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.ECDSAKeyProvider; -import org.apache.commons.codec.binary.Base32; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.binary.Hex; -import org.apache.commons.codec.binary.StringUtils; - import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; @@ -36,6 +31,9 @@ import java.security.SignatureException; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.ECPublicKey; +import org.apache.commons.codec.binary.Base32; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.codec.binary.Hex; class ECDSAAlgorithm extends Algorithm { @@ -66,12 +64,12 @@ public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { String urlDecoded = null; switch (encodeType) { case Base16: - urlDecoded = URLDecoder.decode(signature, "UTF-8"); + urlDecoded = URLDecoder.decode(signature, StandardCharsets.UTF_8.name()); signatureBytes = Hex.decodeHex(urlDecoded); break; case Base32: Base32 base32 = new Base32(); - urlDecoded = URLDecoder.decode(signature, "UTF-8"); + urlDecoded = URLDecoder.decode(signature, StandardCharsets.UTF_8.name()); signatureBytes = base32.decode(urlDecoded); break; case Base64: @@ -94,6 +92,11 @@ public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { } } + @Override + public void verifyWithX509(DecodedJWT jwt, String jwksFile, String pemFile) throws Exception { + throw new UnsupportedOperationException("X509 is not supported for ECDSA algorithm"); + } + @Override public byte[] sign(byte[] contentBytes) throws SignatureGenerationException { try { @@ -241,6 +244,7 @@ static ECDSAKeyProvider providerForKeys(final ECPublicKey publicKey, final ECPri if (publicKey == null && privateKey == null) { throw new IllegalArgumentException("Both provided Keys cannot be null."); } + return new ECDSAKeyProvider() { @Override public ECPublicKey getPublicKeyById(String keyId) { @@ -258,4 +262,4 @@ public String getPrivateKeyId() { } }; } -} +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/algorithms/HMACAlgorithm.java b/lib/src/main/java/com/auth0/jwt/algorithms/HMACAlgorithm.java index b7ee04a..d18826f 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/HMACAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/HMACAlgorithm.java @@ -20,22 +20,18 @@ package com.auth0.jwt.algorithms; import com.auth0.jwt.creators.EncodeType; -import com.auth0.jwt.creators.JWTCreator; import com.auth0.jwt.exceptions.SignatureGenerationException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; -import org.apache.commons.codec.CharEncoding; -import org.apache.commons.codec.binary.Base32; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.binary.Hex; -import org.apache.commons.codec.binary.StringUtils; - import java.io.UnsupportedEncodingException; import java.net.URLDecoder; -import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; +import org.apache.commons.codec.CharEncoding; +import org.apache.commons.codec.binary.Base32; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.codec.binary.Hex; class HMACAlgorithm extends Algorithm { @@ -76,12 +72,12 @@ public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { String urlDecoded = null; switch (encodeType) { case Base16: - urlDecoded = URLDecoder.decode(signature, "UTF-8"); + urlDecoded = URLDecoder.decode(signature, StandardCharsets.UTF_8.name()); signatureBytes = Hex.decodeHex(urlDecoded); break; case Base32: Base32 base32 = new Base32(); - urlDecoded = URLDecoder.decode(signature, "UTF-8"); + urlDecoded = URLDecoder.decode(signature, StandardCharsets.UTF_8.name()); signatureBytes = base32.decode(urlDecoded); break; case Base64: @@ -99,6 +95,11 @@ public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { } } + @Override + public void verifyWithX509(DecodedJWT jwt, String jwksFile, String pemFile) throws Exception { + throw new UnsupportedOperationException("X509 is not supported for HMAC algorithm"); + } + @Override public byte[] sign(byte[] contentBytes) throws SignatureGenerationException { try { @@ -108,4 +109,4 @@ public byte[] sign(byte[] contentBytes) throws SignatureGenerationException { } } -} +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/algorithms/NoneAlgorithm.java b/lib/src/main/java/com/auth0/jwt/algorithms/NoneAlgorithm.java index 5c7e23a..42712bd 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/NoneAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/NoneAlgorithm.java @@ -23,12 +23,12 @@ import com.auth0.jwt.exceptions.SignatureGenerationException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import org.apache.commons.codec.binary.Base32; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; -import java.net.URLDecoder; - class NoneAlgorithm extends Algorithm { NoneAlgorithm() { @@ -42,12 +42,12 @@ public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { String urlDecoded = null; switch (encodeType) { case Base16: - urlDecoded = URLDecoder.decode(signature, "UTF-8"); + urlDecoded = URLDecoder.decode(signature, StandardCharsets.UTF_8.name()); signatureBytes = Hex.decodeHex(urlDecoded); break; case Base32: Base32 base32 = new Base32(); - urlDecoded = URLDecoder.decode(signature, "UTF-8"); + urlDecoded = URLDecoder.decode(signature, StandardCharsets.UTF_8.name()); signatureBytes = base32.decode(urlDecoded); break; case Base64: @@ -59,8 +59,13 @@ public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { } } + @Override + public void verifyWithX509(DecodedJWT jwt, String jwksFile, String pemFile) throws Exception { + throw new UnsupportedOperationException("X509 is not supported for None algorithm"); + } + @Override public byte[] sign(byte[] contentBytes) throws SignatureGenerationException { return new byte[0]; } -} +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/algorithms/RSAAlgorithm.java b/lib/src/main/java/com/auth0/jwt/algorithms/RSAAlgorithm.java index bc312a2..b9ecbe1 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/RSAAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/RSAAlgorithm.java @@ -19,22 +19,37 @@ package com.auth0.jwt.algorithms; +import com.auth0.jwk.Jwk; +import com.auth0.jwk.JwkProvider; +import com.auth0.jwk.UrlJwkProvider; import com.auth0.jwt.creators.EncodeType; +import com.auth0.jwt.creators.JWTCreator; import com.auth0.jwt.exceptions.SignatureGenerationException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.RSAKeyProvider; -import org.apache.commons.codec.binary.Base32; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.binary.Hex; - +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.OutputStreamWriter; +import java.io.Writer; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; +import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; +import java.security.PublicKey; import java.security.SignatureException; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; +import java.security.spec.X509EncodedKeySpec; +import java.util.Arrays; +import java.util.List; +import org.apache.commons.codec.binary.Base32; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.codec.binary.Hex; +import org.bouncycastle.util.io.pem.PemReader; class RSAAlgorithm extends Algorithm { @@ -55,20 +70,77 @@ class RSAAlgorithm extends Algorithm { this(new CryptoHelper(), id, algorithm, keyProvider); } + @Override + public void verifyWithX509(DecodedJWT jwt, String jwksFile, String pemFile) throws Exception { + List byteArrayList = fetchContentAndSignatureByteArrays(jwt, JWTCreator.Builder.encodeTypeStatic); + byte[] contentBytes = byteArrayList.get(0); + byte[] signatureBytes = byteArrayList.get(1); + try { + PublicKey publicKey; + if(jwksFile != null && !jwksFile.isEmpty() && jwksFile.endsWith(".json")) { + String kid = jwt.getKeyId(); + JwkProvider provider = new UrlJwkProvider(new File(jwksFile).toURI().toURL()); + Jwk jwk = provider.get(kid); + String cert = jwk.getCertificateChain().get(0); + try (Writer writer = new BufferedWriter(new OutputStreamWriter( + new FileOutputStream("./jwks.cert"), StandardCharsets.UTF_8.name()))) { + writer.write("-----BEGIN CERTIFICATE-----"); + writer.append("\n" + cert + "\n"); + writer.append("-----END CERTIFICATE-----"); + } + + FileReader file = new FileReader(pemFile); + PemReader reader = new PemReader(file); + X509EncodedKeySpec caKeySpec = new X509EncodedKeySpec(reader.readPemObject().getContent()); + KeyFactory kf = KeyFactory.getInstance("RSA"); + publicKey = kf.generatePublic(caKeySpec); + } else { + throw new IllegalArgumentException("Not a proper jwks file"); + } + if (publicKey == null) { + throw new IllegalStateException("The given Public Key is null."); + } + boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, contentBytes, signatureBytes); + if (!valid) { + throw new SignatureVerificationException(this); + } + } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalStateException e) { + throw new SignatureVerificationException(this, e); + } + } + @Override public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { - byte[] contentBytes = String.format("%s.%s", jwt.getHeader(), jwt.getPayload()).getBytes(StandardCharsets.UTF_8); + List byteArrayList = fetchContentAndSignatureByteArrays(jwt, encodeType); + byte[] contentBytes = byteArrayList.get(0); + byte[] signatureBytes = byteArrayList.get(1); + try { + PublicKey publicKey = keyProvider.getPublicKeyById(jwt.getKeyId()); + if (publicKey == null) { + throw new IllegalStateException("The given Public Key is null."); + } + boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, contentBytes, signatureBytes); + if (!valid) { + throw new SignatureVerificationException(this); + } + } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalStateException e) { + throw new SignatureVerificationException(this, e); + } + } + + private List fetchContentAndSignatureByteArrays(DecodedJWT jwt, EncodeType encodeType) throws Exception{ + byte[] contentBytes = String.format("%s.%s", jwt.getHeader(), jwt.getPayload()).getBytes(StandardCharsets.UTF_8.name()); byte[] signatureBytes = null; String signature = jwt.getSignature(); String urlDecoded = null; switch (encodeType) { case Base16: - urlDecoded = URLDecoder.decode(signature, "UTF-8"); + urlDecoded = URLDecoder.decode(signature, StandardCharsets.UTF_8.name()); signatureBytes = Hex.decodeHex(urlDecoded); break; case Base32: Base32 base32 = new Base32(); - urlDecoded = URLDecoder.decode(signature, "UTF-8"); + urlDecoded = URLDecoder.decode(signature, StandardCharsets.UTF_8.name()); signatureBytes = base32.decode(urlDecoded); break; case Base64: @@ -76,18 +148,7 @@ public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { break; } - try { - RSAPublicKey publicKey = keyProvider.getPublicKeyById(jwt.getKeyId()); - if (publicKey == null) { - throw new IllegalStateException("The given Public Key is null."); - } - boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, contentBytes, signatureBytes); - if (!valid) { - throw new SignatureVerificationException(this); - } - } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalStateException e) { - throw new SignatureVerificationException(this, e); - } + return Arrays.asList(contentBytes, signatureBytes); } @Override @@ -130,4 +191,4 @@ public String getPrivateKeyId() { } }; } -} +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/algorithms/jwks.pem b/lib/src/main/java/com/auth0/jwt/algorithms/jwks.pem new file mode 100644 index 0000000..d3c6574 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/algorithms/jwks.pem @@ -0,0 +1,3 @@ +-----BEGIN PUBLIC KEY----- +MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAoAVHrlMYnzs/s9/RDJrLqVnTRr8FpjTgiBCtcJ6EGmQLwsQ5f/+l5/0UpZhWhrZrmdvDXW/raY/p3SzYX4fHOGXPbQjG6ZijJjdFHX1CEDbgHXokJhHyCRmMvRUE/MqxmnU2TjyhHU+fxGYUymzwRF+CYqn2HBdDPga9ry1Txv0dMeNuz3vXqd/F3qWQdY+qt8DHdf7PrvcrSX2e3y3VCObVd3qYADPnawcXpUF/UNSccbBoAo/lDO00S3HVt9fyIkdOHbIWTI9TBDAXr7i/4i69y1Ur9LB/xPA+oqmyKOWBYa0GhbcdJtU/db8+teOUXaOyujMWGqZctU8eGH12HG18zFGkIauFfKFREk6qe4hpbg3PjcJi8TXu0OA+x1TbicCbAIXHxvuEUIQo81eRPThgDH0IauFFuW+aH2eKMO1XfGge655X4osn5RfKXRNvY2+w3VZMHyboDd+RvQIqI4VA+HnHvBS9MSAM5mAUuNDnwT47ymnIO2NrEcDvUpEhjLO6hvxnwCESt2UQEFvpbIi+6UeGVwNaciNtnq/tf6lEYlIgmP61gWDAy5MCAFOQi+iErq4FFT0TytU8cVn/Q0a0nrogs3cgRrvIo3yHyyt62xvrtcW6N/yU3T5JBmFvK8CO+zqCwz3cCy+j6U4+y3ulz07fmDwWuTO0LO/JQxECAwEAAQ== +-----END PUBLIC KEY----- \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java b/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java index 4b126c4..3488353 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java @@ -19,66 +19,38 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; -import com.auth0.jwt.jwts.JWT; - +import com.auth0.jwt.impl.Claims; import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; /** * The AccessJwtCreator class holds the sign method to generate a complete Access JWT (with Signature) from a given Header and Payload content. */ -public class AccessJwtCreator { - - protected JWTCreator.Builder jwt; - protected HashMap addedClaims; - protected Set publicClaims; +public class AccessJwtCreator extends Creator{ - public AccessJwtCreator() { - jwt = JWT.create(); - addedClaims = new HashMap() {{ - put("Issuer", false); - put("Subject", false); - put("Iat", false); - }}; - publicClaims = new HashSet() {{ - add(PublicClaims.ISSUER); - add(PublicClaims.SUBJECT); - add(PublicClaims.EXPIRES_AT); - add(PublicClaims.NOT_BEFORE); - add(PublicClaims.ISSUED_AT); - add(PublicClaims.JWT_ID); - add(PublicClaims.AUDIENCE); - }}; + private AccessJwtCreator() { } /** * Add a specific Issuer ("issuer") claim to the Payload. - * Allows for multiple issuers * * @param issuer the Issuer value. * @return this same Builder instance. */ - public AccessJwtCreator withIssuer(String... issuer) { + public AccessJwtCreator withIssuer(String issuer) { jwt.withIssuer(issuer); - addedClaims.put("Issuer", true); + requiredClaimsAccess.put(Claims.ISSUER, true); return this; } /** * Add a specific Subject ("subject") claim to the Payload. - * Allows for multiple subjects * * @param subject the Subject value. * @return this same Builder instance. */ - public AccessJwtCreator withSubject(String... subject) { + public AccessJwtCreator withSubject(String subject) { jwt.withSubject(subject); - addedClaims.put("Subject", true); + requiredClaimsAccess.put(Claims.SUBJECT, true); return this; } @@ -102,7 +74,7 @@ public AccessJwtCreator withAudience(String... audience) { */ public AccessJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - addedClaims.put("Iat", true); + requiredClaimsAccess.put(Claims.ISSUED_AT, true); return this; } @@ -126,7 +98,13 @@ public AccessJwtCreator withExp(Date exp) { * @throws IllegalArgumentException if the name is null. */ public AccessJwtCreator withNonStandardClaim(String name, String value) { - jwt.withNonStandardClaim(name, value); + if("subject".equalsIgnoreCase(name) || Claims.SUBJECT.equalsIgnoreCase(name)) { + withSubject(value); + } else if("issuer".equalsIgnoreCase(name) || Claims.ISSUER.equalsIgnoreCase(name)) { + withIssuer(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -191,7 +169,11 @@ public AccessJwtCreator withNonStandardClaim(String name, Double value) throws I * @throws IllegalArgumentException if the name is null. */ public AccessJwtCreator withNonStandardClaim(String name, Date value) throws IllegalArgumentException { - jwt.withNonStandardClaim(name, value); + if(name.equalsIgnoreCase(Claims.ISSUED_AT) || name.equalsIgnoreCase("issuedAt") || name.equalsIgnoreCase("issued_at")) { + withIat(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -205,8 +187,8 @@ public AccessJwtCreator withNonStandardClaim(String name, Date value) throws Ill */ public AccessJwtCreator withArrayClaim(String name, String... items) throws IllegalArgumentException { jwt.withArrayClaim(name, items); - if(publicClaims.contains(name)) - addedClaims.put(name, true); + if(requiredClaimsAccess.containsKey(name)) + requiredClaimsAccess.put(name, true); return this; } @@ -222,70 +204,6 @@ public AccessJwtCreator setIsNoneAlgorithmAllowed(boolean isNoneAlgorithmAllowed return this; } - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String sign(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm); - verifyClaims(); - return JWS; - } - - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String signBase16Encoding(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm, EncodeType.Base16); - verifyClaims(); - return JWS; - } - - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String signBase32Encoding(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm, EncodeType.Base32); - verifyClaims(); - return JWS; - } - - /** - * Verifies that all the standard claims were provided - * @throws Exception if all the standard claims weren't provided - */ - private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) - throw new Exception("Standard claim: " + claim + " has not been set"); - } - public static AccessJwtCreator build() { return new AccessJwtCreator(); } diff --git a/lib/src/main/java/com/auth0/jwt/creators/Creator.java b/lib/src/main/java/com/auth0/jwt/creators/Creator.java new file mode 100644 index 0000000..459ae46 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/creators/Creator.java @@ -0,0 +1,134 @@ +package com.auth0.jwt.creators; + +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.exceptions.JWTCreationException; +import com.auth0.jwt.exceptions.RequiredClaimException; +import com.auth0.jwt.impl.Claims; +import com.auth0.jwt.jwts.JWT; +import java.util.HashMap; +import java.util.Map; + +public abstract class Creator { + + protected JWTCreator.Builder jwt; + protected Map requiredClaimsImplicit; + protected Map requiredClaimsGoogle; + protected Map requiredClaimsAccess; + protected Map requiredClaimsFB; + protected Map requiredClaimsRisc; + protected Map requiredClaimsScoped; + + protected Creator() { + jwt = JWT.create(); + requiredClaimsImplicit = new HashMap() {{ + put(Claims.ISSUER, false); + put(Claims.SUBJECT, false); + put(Claims.ISSUED_AT, false); + }}; + requiredClaimsGoogle = new HashMap() {{ + put(Claims.NAME, false); + put(Claims.EMAIL, false); + put(Claims.PICTURE, false); + put(Claims.ISSUER, false); + put(Claims.SUBJECT, false); + put(Claims.ISSUED_AT, false); + }}; + requiredClaimsAccess = new HashMap() {{ + put(Claims.ISSUER, false); + put(Claims.SUBJECT, false); + put(Claims.ISSUED_AT, false); + }}; + requiredClaimsFB = new HashMap() {{ + put(Claims.USER_ID, false); + put(Claims.APP_ID, false); + put(Claims.ISSUED_AT, false); + }}; + requiredClaimsRisc = new HashMap() {{ + put(Claims.JWT_ID, false); + put(Claims.ISSUER, false); + put(Claims.SUBJECT, false); + put(Claims.ISSUED_AT, false); + }}; + requiredClaimsScoped = new HashMap() {{ + put(Claims.SCOPE, false); + put(Claims.ISSUER, false); + put(Claims.SUBJECT, false); + put(Claims.ISSUED_AT, false); + }}; + } + /** + * Creates a new JWT and signs it with the given algorithm. + * + * @param algorithm used to sign the JWT + * @return a new JWT token + * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in + * @throws IllegalArgumentException if the provided algorithm is null. + * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. + */ + public String sign(Algorithm algorithm) throws Exception { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { + throw new IllegalAccessException("None algorithm isn't allowed"); + } + verifyClaims(); + String JWS = jwt.sign(algorithm); + return JWS; + } + + /** + * Creates a new JWT and signs it with the given algorithm. + * + * @param algorithm used to sign the JWT + * @return a new JWT token + * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in + * @throws IllegalArgumentException if the provided algorithm is null. + * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. + */ + public String signBase16Encoding(Algorithm algorithm) throws Exception { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { + throw new IllegalAccessException("None algorithm isn't allowed"); + } + verifyClaims(); + String JWS = jwt.sign(algorithm, EncodeType.Base16); + return JWS; + } + + /** + * Creates a new JWT and signs it with the given algorithm. + * + * @param algorithm used to sign the JWT + * @return a new JWT token + * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in + * @throws IllegalArgumentException if the provided algorithm is null. + * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. + */ + public String signBase32Encoding(Algorithm algorithm) throws Exception { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { + throw new IllegalAccessException("None algorithm isn't allowed"); + } + verifyClaims(); + String JWS = jwt.sign(algorithm, EncodeType.Base32); + return JWS; + } + + private void verifyClaims() throws RequiredClaimException { + Map requiredClaims = null; + + if(this instanceof ImplicitJwtCreator) { + requiredClaims = requiredClaimsImplicit; + } else if(this instanceof GoogleJwtCreator) { + requiredClaims = requiredClaimsGoogle; + } else if(this instanceof AccessJwtCreator) { + requiredClaims = requiredClaimsAccess; + } else if(this instanceof FbJwtCreator) { + requiredClaims = requiredClaimsFB; + } else if(this instanceof RiscJwtCreator) { + requiredClaims = requiredClaimsRisc; + } else if(this instanceof ScopedJwtCreator) { + requiredClaims = requiredClaimsScoped; + } + + for(String claim : requiredClaims.keySet()) + if(!requiredClaims.get(claim)) + throw new RequiredClaimException("Standard claim: " + claim + " has not been set"); + } +} diff --git a/lib/src/main/java/com/auth0/jwt/creators/ExtendedJwtCreator.java b/lib/src/main/java/com/auth0/jwt/creators/ExtendedJwtCreator.java index 18e6917..5d6b0a9 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ExtendedJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ExtendedJwtCreator.java @@ -19,9 +19,6 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.exceptions.JWTCreationException; - import java.util.Date; /** @@ -29,7 +26,7 @@ */ public class ExtendedJwtCreator extends GoogleJwtCreator{ - public ExtendedJwtCreator() { + private ExtendedJwtCreator() { super(); } @@ -39,75 +36,11 @@ public ExtendedJwtCreator() { * @param nbf the nbf value. * @return this same Builder instance. */ - public GoogleJwtCreator withNbf(Date nbf) { + public ExtendedJwtCreator withNbf(Date nbf) { jwt.withNotBefore(nbf); return this; } - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String sign(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm); - verifyClaims(); - return JWS; - } - - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String signBase16Encoding(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm, EncodeType.Base16); - verifyClaims(); - return JWS; - } - - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String signBase32Encoding(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm, EncodeType.Base32); - verifyClaims(); - return JWS; - } - - /** - * Verifies that all the standard claims were provided - * @throws Exception if all the standard claims weren't provided - */ - private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) - throw new Exception("Standard claim: " + claim + " has not been set"); - } - public static ExtendedJwtCreator build() { return new ExtendedJwtCreator(); } diff --git a/lib/src/main/java/com/auth0/jwt/creators/FbJwtCreator.java b/lib/src/main/java/com/auth0/jwt/creators/FbJwtCreator.java index e4ff44e..3319974 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/FbJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/FbJwtCreator.java @@ -19,36 +19,15 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; -import com.auth0.jwt.jwts.JWT; - +import com.auth0.jwt.impl.Claims; import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; /** * The FbJwtCreator class holds the sign method to generate a complete FB JWT (with Signature) from a given Header and Payload content. */ -public class FbJwtCreator { - - protected JWTCreator.Builder jwt; - protected HashMap addedClaims; - protected Set publicClaims; +public class FbJwtCreator extends GoogleOrFbJwtCreator { - public FbJwtCreator() { - jwt = JWT.create(); - addedClaims = new HashMap() {{ - put("UserId", false); - put("AppId", false); - put("Iat", false); - }}; - publicClaims = new HashSet() {{ - add(PublicClaims.ISSUED_AT); - add(PublicClaims.EXPIRES_AT); - }}; + private FbJwtCreator() { } /** @@ -59,7 +38,7 @@ public FbJwtCreator() { */ public FbJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - addedClaims.put("Iat", true); + requiredClaimsFB.put(Claims.ISSUED_AT, true); return this; } @@ -81,8 +60,8 @@ public FbJwtCreator withExp(Date exp) { * @return this same Verification instance. */ public FbJwtCreator withUserId(String userId) { - jwt.withNonStandardClaim("userId", userId); - addedClaims.put("UserId", true); + jwt.withNonStandardClaim(Claims.USER_ID, userId); + requiredClaimsFB.put(Claims.USER_ID, true); return this; } @@ -93,8 +72,8 @@ public FbJwtCreator withUserId(String userId) { * @return this same Verification instance. */ public FbJwtCreator withAppId(String appId) { - jwt.withNonStandardClaim("appId", appId); - addedClaims.put("AppId", true); + jwt.withNonStandardClaim(Claims.APP_ID, appId); + requiredClaimsFB.put(Claims.APP_ID, true); return this; } @@ -107,7 +86,13 @@ public FbJwtCreator withAppId(String appId) { * @throws IllegalArgumentException if the name is null. */ public FbJwtCreator withNonStandardClaim(String name, String value) { - jwt.withNonStandardClaim(name, value); + if(Claims.USER_ID.equalsIgnoreCase(name) || "user_id".equalsIgnoreCase(name)) { + withUserId(value); + } else if(Claims.APP_ID.equalsIgnoreCase(name) || "app_id".equalsIgnoreCase(name)) { + withAppId(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -172,7 +157,11 @@ public FbJwtCreator withNonStandardClaim(String name, Double value) throws Illeg * @throws IllegalArgumentException if the name is null. */ public FbJwtCreator withNonStandardClaim(String name, Date value) throws IllegalArgumentException { - jwt.withNonStandardClaim(name, value); + if(Claims.ISSUED_AT.equalsIgnoreCase(name) || "issuedAt".equalsIgnoreCase(name) || "issued_at".equalsIgnoreCase(name)) { + withIat(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -186,8 +175,8 @@ public FbJwtCreator withNonStandardClaim(String name, Date value) throws Illegal */ public FbJwtCreator withArrayClaim(String name, String... items) throws IllegalArgumentException { jwt.withArrayClaim(name, items); - if(publicClaims.contains(name)) - addedClaims.put(name, true); + if(requiredClaimsFB.containsKey(name)) + requiredClaimsFB.put(name, true); return this; } @@ -203,70 +192,6 @@ public FbJwtCreator setIsNoneAlgorithmAllowed(boolean isNoneAlgorithmAllowed) { return this; } - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String sign(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm); - verifyClaims(); - return JWS; - } - - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String signBase16Encoding(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm, EncodeType.Base16); - verifyClaims(); - return JWS; - } - - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String signBase32Encoding(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm, EncodeType.Base32); - verifyClaims(); - return JWS; - } - - /** - * Verifies that all the standard claims were provided - * @throws Exception if all the standard claims weren't provided - */ - private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) - throw new Exception("Standard claim: " + claim + " has not been set"); - } - public static FbJwtCreator build() { return new FbJwtCreator(); } diff --git a/lib/src/main/java/com/auth0/jwt/creators/GoogleJwtCreator.java b/lib/src/main/java/com/auth0/jwt/creators/GoogleJwtCreator.java index ffd9e66..489d968 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/GoogleJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/GoogleJwtCreator.java @@ -19,44 +19,15 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; -import com.auth0.jwt.jwts.JWT; - +import com.auth0.jwt.impl.Claims; import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; /** * The GoogleJwtCreator class holds the sign method to generate a complete Google JWT (with Signature) from a given Header and Payload content. */ -public class GoogleJwtCreator { - - protected JWTCreator.Builder jwt; - protected HashMap addedClaims; - protected Set publicClaims; +public class GoogleJwtCreator extends GoogleOrFbJwtCreator { - public GoogleJwtCreator() { - jwt = JWT.create(); - addedClaims = new HashMap() {{ - put("Name", false); - put("Email", false); - put("Picture", false); - put("Issuer", false); - put("Subject", false); - put("Iat", false); - }}; - publicClaims = new HashSet() {{ - add(PublicClaims.ISSUER); - add(PublicClaims.SUBJECT); - add(PublicClaims.EXPIRES_AT); - add(PublicClaims.NOT_BEFORE); - add(PublicClaims.ISSUED_AT); - add(PublicClaims.JWT_ID); - add(PublicClaims.AUDIENCE); - }}; + protected GoogleJwtCreator() { } @@ -67,8 +38,8 @@ public GoogleJwtCreator() { * @return this same Builder instance. */ public GoogleJwtCreator withName(String name) { - jwt.withNonStandardClaim("name", name); - addedClaims.put("Name", true); + jwt.withNonStandardClaim(Claims.NAME, name); + requiredClaimsGoogle.put(Claims.NAME, true); return this; } @@ -79,8 +50,8 @@ public GoogleJwtCreator withName(String name) { * @return this same Builder instance. */ public GoogleJwtCreator withEmail(String email) { - jwt.withNonStandardClaim("email", email); - addedClaims.put("Email", true); + jwt.withNonStandardClaim(Claims.EMAIL, email); + requiredClaimsGoogle.put(Claims.EMAIL, true); return this; } @@ -91,34 +62,32 @@ public GoogleJwtCreator withEmail(String email) { * @return this same Builder instance. */ public GoogleJwtCreator withPicture(String picture) { - jwt.withNonStandardClaim("picture", picture); - addedClaims.put("Picture", true); + jwt.withNonStandardClaim(Claims.PICTURE, picture); + requiredClaimsGoogle.put(Claims.PICTURE, true); return this; } /** * Add a specific Issuer ("issuer") claim to the Payload. - * Allows for multiple issuers * * @param issuer the Issuer value. * @return this same Builder instance. */ - public GoogleJwtCreator withIssuer(String... issuer) { + public GoogleJwtCreator withIssuer(String issuer) { jwt.withIssuer(issuer); - addedClaims.put("Issuer", true); + requiredClaimsGoogle.put(Claims.ISSUER, true); return this; } /** * Add a specific Subject ("subject") claim to the Payload. - * Allows for multiple subjects * * @param subject the Subject value. * @return this same Builder instance. */ - public GoogleJwtCreator withSubject(String... subject) { + public GoogleJwtCreator withSubject(String subject) { jwt.withSubject(subject); - addedClaims.put("Subject", true); + requiredClaimsGoogle.put(Claims.SUBJECT, true); return this; } @@ -142,7 +111,7 @@ public GoogleJwtCreator withAudience(String... audience) { */ public GoogleJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - addedClaims.put("Iat", true); + requiredClaimsGoogle.put(Claims.ISSUED_AT, true); return this; } @@ -166,7 +135,19 @@ public GoogleJwtCreator withExp(Date exp) { * @throws IllegalArgumentException if the name is null. */ public GoogleJwtCreator withNonStandardClaim(String name, String value) { - jwt.withNonStandardClaim(name, value); + if(Claims.NAME.equalsIgnoreCase(value)) { + withName(value); + } else if(Claims.EMAIL.equalsIgnoreCase(value)) { + withEmail(value); + } else if(Claims.PICTURE.equalsIgnoreCase(value)) { + withPicture(value); + } else if(Claims.ISSUER.equalsIgnoreCase(value) || "issuer".equalsIgnoreCase(value)) { + withIssuer(value); + } else if("subject".equalsIgnoreCase(name) || Claims.SUBJECT.equalsIgnoreCase(name)) { + withSubject(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -231,7 +212,11 @@ public GoogleJwtCreator withNonStandardClaim(String name, Double value) throws I * @throws IllegalArgumentException if the name is null. */ public GoogleJwtCreator withNonStandardClaim(String name, Date value) throws IllegalArgumentException { - jwt.withNonStandardClaim(name, value); + if(Claims.ISSUED_AT.equalsIgnoreCase(name) || "issuedAt".equalsIgnoreCase(name) || "issued_at".equalsIgnoreCase(name)) { + withIat(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -245,8 +230,8 @@ public GoogleJwtCreator withNonStandardClaim(String name, Date value) throws Ill */ public GoogleJwtCreator withArrayClaim(String name, String... items) throws IllegalArgumentException { jwt.withArrayClaim(name, items); - if(publicClaims.contains(name)) - addedClaims.put(name, true); + if(requiredClaimsGoogle.containsKey(name)) + requiredClaimsGoogle.put(name, true); return this; } @@ -262,70 +247,6 @@ public GoogleJwtCreator setIsNoneAlgorithmAllowed(boolean isNoneAlgorithmAllowed return this; } - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String sign(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm); - verifyClaims(); - return JWS; - } - - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String signBase16Encoding(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm, EncodeType.Base16); - verifyClaims(); - return JWS; - } - - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String signBase32Encoding(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm, EncodeType.Base32); - verifyClaims(); - return JWS; - } - - /** - * Verifies that all the standard claims were provided - * @throws Exception if all the standard claims weren't provided - */ - private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) - throw new Exception("Standard claim: " + claim + " has not been set"); - } - public static GoogleJwtCreator build() { return new GoogleJwtCreator(); } diff --git a/lib/src/main/java/com/auth0/jwt/creators/GoogleOrFbJwtCreator.java b/lib/src/main/java/com/auth0/jwt/creators/GoogleOrFbJwtCreator.java new file mode 100644 index 0000000..c239224 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/creators/GoogleOrFbJwtCreator.java @@ -0,0 +1,4 @@ +package com.auth0.jwt.creators; + +public abstract class GoogleOrFbJwtCreator extends Creator{ +} diff --git a/lib/src/main/java/com/auth0/jwt/creators/ImplicitJwtCreator.java b/lib/src/main/java/com/auth0/jwt/creators/ImplicitJwtCreator.java index 0130e4e..8dfad41 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ImplicitJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ImplicitJwtCreator.java @@ -19,63 +19,38 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; -import com.auth0.jwt.jwts.JWT; - +import com.auth0.jwt.impl.Claims; import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; /** * The ImplicitJwtCreator class holds the sign method to generate a complete Implicit JWT (with Signature) from a given Header and Payload content. */ -public class ImplicitJwtCreator { - - protected JWTCreator.Builder jwt; - protected HashMap addedClaims; - protected Set publicClaims; +public class ImplicitJwtCreator extends Creator{ - public ImplicitJwtCreator() { - jwt = JWT.create(); - addedClaims = new HashMap() {{ - put("Issuer", false); - put("Subject", false); - put("Iat", false); - }}; - publicClaims = new HashSet() {{ - add(PublicClaims.ISSUER); - add(PublicClaims.SUBJECT); - add(PublicClaims.ISSUED_AT); - add(PublicClaims.AUDIENCE); - }}; + private ImplicitJwtCreator() { } /** * Add a specific Issuer ("issuer") claim to the Payload. - * Allows for multiple issuers * * @param issuer the Issuer value. * @return this same Builder instance. */ - public ImplicitJwtCreator withIssuer(String... issuer) { + public ImplicitJwtCreator withIssuer(String issuer) { jwt.withIssuer(issuer); - addedClaims.put("Issuer", true); + requiredClaimsImplicit.put(Claims.ISSUER, true); return this; } /** * Add a specific Subject ("subject") claim to the Payload. - * Allows for multiple subjects * * @param subject the Subject value. * @return this same Builder instance. */ - public ImplicitJwtCreator withSubject(String... subject) { + public ImplicitJwtCreator withSubject(String subject) { jwt.withSubject(subject); - addedClaims.put("Subject", true); + requiredClaimsImplicit.put(Claims.SUBJECT, true); return this; } @@ -99,7 +74,7 @@ public ImplicitJwtCreator withAudience(String... audience) { */ public ImplicitJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - addedClaims.put("Iat", true); + requiredClaimsImplicit.put(Claims.ISSUED_AT, true); return this; } @@ -112,7 +87,13 @@ public ImplicitJwtCreator withIat(Date iat) { * @throws IllegalArgumentException if the name is null. */ public ImplicitJwtCreator withNonStandardClaim(String name, String value) { - jwt.withNonStandardClaim(name, value); + if("subject".equalsIgnoreCase(name) || Claims.SUBJECT.equalsIgnoreCase(name)) { + withSubject(value); + } else if("issuer".equalsIgnoreCase(name) || Claims.ISSUER.equalsIgnoreCase(name)) { + withIssuer(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -177,7 +158,11 @@ public ImplicitJwtCreator withNonStandardClaim(String name, Double value) throws * @throws IllegalArgumentException if the name is null. */ public ImplicitJwtCreator withNonStandardClaim(String name, Date value) throws IllegalArgumentException { - jwt.withNonStandardClaim(name, value); + if(Claims.ISSUED_AT.equalsIgnoreCase(name) || "issuedAt".equalsIgnoreCase(name) || "issued_at".equalsIgnoreCase(name)) { + withIat(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -191,8 +176,8 @@ public ImplicitJwtCreator withNonStandardClaim(String name, Date value) throws I */ public ImplicitJwtCreator withArrayClaim(String name, String... items) throws IllegalArgumentException { jwt.withArrayClaim(name, items); - if(publicClaims.contains(name)) - addedClaims.put(name, true); + if(requiredClaimsImplicit.containsKey(name)) + requiredClaimsImplicit.put(name, true); return this; } @@ -208,70 +193,6 @@ public ImplicitJwtCreator setIsNoneAlgorithmAllowed(boolean isNoneAlgorithmAllow return this; } - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String sign(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm); - verifyClaims(); - return JWS; - } - - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String signBase16Encoding(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm, EncodeType.Base16); - verifyClaims(); - return JWS; - } - - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String signBase32Encoding(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm, EncodeType.Base32); - verifyClaims(); - return JWS; - } - - /** - * Verifies that all the standard claims were provided - * @throws Exception if all the standard claims weren't provided - */ - private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) - throw new Exception("Standard claim: " + claim + " has not been set"); - } - public static ImplicitJwtCreator build() { return new ImplicitJwtCreator(); } diff --git a/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java b/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java index 54e4f13..02c5633 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java @@ -22,26 +22,22 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; import com.auth0.jwt.exceptions.SignatureGenerationException; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.impl.ClaimsHolder; import com.auth0.jwt.impl.PayloadSerializer; -import com.auth0.jwt.impl.PublicClaims; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; -import org.apache.commons.codec.Encoder; -import org.apache.commons.codec.binary.Base32; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.binary.Hex; -import org.apache.commons.codec.binary.StringUtils; - -import java.io.*; -import java.net.URLDecoder; +import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.HashMap; import java.util.Map; +import org.apache.commons.codec.binary.Base32; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.codec.binary.Hex; /** * The JWTCreator class holds the sign method to generate a complete JWT (with Signature) from a given Header and Payload content. @@ -85,6 +81,7 @@ public static class Builder { private final Map payloadClaims; private Map headerClaims; private boolean isNoneAlgorithmAllowed; + public static EncodeType encodeTypeStatic = null; Builder() { this.payloadClaims = new HashMap<>(); @@ -111,31 +108,29 @@ public Builder withHeader(Map headerClaims) { * @return this same Builder instance. */ public Builder withKeyId(String keyId) { - this.headerClaims.put(PublicClaims.KEY_ID, keyId); + this.headerClaims.put(Claims.KEY_ID, keyId); return this; } /** * Add a specific Issuer ("iss") claim to the Payload. - * Allows for multiple issuers * * @param issuer the Issuer value. * @return this same Builder instance. */ - public Builder withIssuer(String... issuer) { - addClaim(PublicClaims.ISSUER, issuer); + public Builder withIssuer(String issuer) { + addClaim(Claims.ISSUER, issuer); return this; } /** * Add a specific Subject ("sub") claim to the Payload. - * Allows for multiple subjects * * @param subject the Subject value. * @return this same Builder instance. */ - public Builder withSubject(String... subject) { - addClaim(PublicClaims.SUBJECT, subject); + public Builder withSubject(String subject) { + addClaim(Claims.SUBJECT, subject); return this; } @@ -147,7 +142,7 @@ public Builder withSubject(String... subject) { * @return this same Builder instance. */ public Builder withAudience(String... audience) { - addClaim(PublicClaims.AUDIENCE, audience); + addClaim(Claims.AUDIENCE, audience); return this; } @@ -158,7 +153,7 @@ public Builder withAudience(String... audience) { * @return this same Builder instance. */ public Builder withExpiresAt(Date expiresAt) { - addClaim(PublicClaims.EXPIRES_AT, expiresAt); + addClaim(Claims.EXPIRES_AT, expiresAt); return this; } @@ -169,7 +164,7 @@ public Builder withExpiresAt(Date expiresAt) { * @return this same Builder instance. */ public Builder withNotBefore(Date notBefore) { - addClaim(PublicClaims.NOT_BEFORE, notBefore); + addClaim(Claims.NOT_BEFORE, notBefore); return this; } @@ -180,7 +175,7 @@ public Builder withNotBefore(Date notBefore) { * @return this same Builder instance. */ public Builder withIssuedAt(Date issuedAt) { - addClaim(PublicClaims.ISSUED_AT, issuedAt); + addClaim(Claims.ISSUED_AT, issuedAt); return this; } @@ -191,7 +186,7 @@ public Builder withIssuedAt(Date issuedAt) { * @return this same Builder instance. */ public Builder withJWTId(String jwtId) { - addClaim(PublicClaims.JWT_ID, jwtId); + addClaim(Claims.JWT_ID, jwtId); return this; } @@ -366,8 +361,8 @@ public String sign(Algorithm algorithm, EncodeType encodeType) throws Exception if(encodeType == null) { throw new IllegalArgumentException("Encodetype cannot be null."); } - headerClaims.put(PublicClaims.ALGORITHM, algorithm.getName()); - headerClaims.put(PublicClaims.TYPE, "JWT"); + headerClaims.put(Claims.ALGORITHM, algorithm.getName()); + headerClaims.put(Claims.TYPE, "JWT"); String signingKeyId = algorithm.getSigningKeyId(); if (signingKeyId != null) { withKeyId(signingKeyId); @@ -377,12 +372,15 @@ public String sign(Algorithm algorithm, EncodeType encodeType) throws Exception switch (encodeType) { case Base16: token = jwtCreator.signBase16Encoding(); + encodeTypeStatic = EncodeType.Base16; break; case Base32: token = jwtCreator.signBase32Encoding(); + encodeTypeStatic = EncodeType.Base32; break; case Base64: token = jwtCreator.defaultSign(); + encodeTypeStatic = EncodeType.Base64; break; } @@ -405,38 +403,38 @@ private void addClaim(String name, Object value) { } private String signBase16Encoding() throws UnsupportedEncodingException { - String header = URLEncoder.encode(headerJson, "UTF-8"); - String payload = URLEncoder.encode(payloadJson, "UTF-8"); + String header = URLEncoder.encode(headerJson, StandardCharsets.UTF_8.name()); + String payload = URLEncoder.encode(payloadJson, StandardCharsets.UTF_8.name()); - byte[] bHeader = header.getBytes("UTF-8"); + byte[] bHeader = header.getBytes(StandardCharsets.UTF_8.name()); String encodedHeader = Hex.encodeHexString(bHeader); - byte[] bPayload = payload.getBytes("UTF-8"); + byte[] bPayload = payload.getBytes(StandardCharsets.UTF_8.name()); String encodedPayload = Hex.encodeHexString(bPayload); String content = String.format("%s.%s", encodedHeader, encodedPayload); byte[] signatureBytes = algorithm.sign(content.getBytes(StandardCharsets.UTF_8)); String signature = Hex.encodeHexString(signatureBytes); - String signatureFinal = URLEncoder.encode(signature, "UTF-8"); + String signatureFinal = URLEncoder.encode(signature, StandardCharsets.UTF_8.name()); return String.format("%s.%s", content, signatureFinal); } private String signBase32Encoding() throws UnsupportedEncodingException{ Base32 base32 = new Base32(); - String header = URLEncoder.encode(headerJson, "UTF-8"); - String payload = URLEncoder.encode(payloadJson, "UTF-8"); + String header = URLEncoder.encode(headerJson, StandardCharsets.UTF_8.name()); + String payload = URLEncoder.encode(payloadJson, StandardCharsets.UTF_8.name()); - byte[] bHeader = header.getBytes("UTF-8"); + byte[] bHeader = header.getBytes(StandardCharsets.UTF_8.name()); String encodedHeader = base32.encodeAsString(bHeader); - byte[] bPayload = payload.getBytes("UTF-8"); + byte[] bPayload = payload.getBytes(StandardCharsets.UTF_8.name()); String encodedPayload = base32.encodeAsString(bPayload); String content = String.format("%s.%s", encodedHeader, encodedPayload); byte[] signatureBytes = algorithm.sign(content.getBytes(StandardCharsets.UTF_8)); String signature = base32.encodeAsString(signatureBytes); - String signatureFinal = URLEncoder.encode(signature, "UTF-8"); + String signatureFinal = URLEncoder.encode(signature, StandardCharsets.UTF_8.name()); return String.format("%s.%s", content, signatureFinal); } @@ -448,7 +446,6 @@ private String defaultSign() throws SignatureGenerationException { byte[] signatureBytes = algorithm.sign(content.getBytes(StandardCharsets.UTF_8)); String signature = Base64.encodeBase64URLSafeString(signatureBytes); - return String.format("%s.%s", content, signature); } -} +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/creators/Message.java b/lib/src/main/java/com/auth0/jwt/creators/Message.java index 45d252c..1672912 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/Message.java +++ b/lib/src/main/java/com/auth0/jwt/creators/Message.java @@ -22,22 +22,22 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; - import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; public class Message { public String toUrlEncoded(String json) throws UnsupportedEncodingException { - return URLEncoder.encode(json, "UTF-8"); + return URLEncoder.encode(json, StandardCharsets.UTF_8.name()); } public String toUrlDecoded(String urlEncoded) throws UnsupportedEncodingException { - return URLDecoder.decode(urlEncoded, "UTF-8"); + return URLDecoder.decode(urlEncoded, StandardCharsets.UTF_8.name()); } public String toJSON(HashMap hashMap) { diff --git a/lib/src/main/java/com/auth0/jwt/creators/RiscJwtCreator.java b/lib/src/main/java/com/auth0/jwt/creators/RiscJwtCreator.java index 61e9dd8..2f4a1b0 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/RiscJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/RiscJwtCreator.java @@ -19,43 +19,15 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; -import com.auth0.jwt.interfaces.Verification; -import com.auth0.jwt.jwts.JWT; - +import com.auth0.jwt.impl.Claims; import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; /** * The RiscJwtCreator class holds the sign method to generate a complete Risc JWT (with Signature) from a given Header and Payload content. */ -public class RiscJwtCreator { - - protected JWTCreator.Builder jwt; - protected HashMap addedClaims; - protected Set publicClaims; +public class RiscJwtCreator extends Creator{ - public RiscJwtCreator() { - jwt = JWT.create(); - addedClaims = new HashMap() {{ - put("Jti", false); - put("Issuer", false); - put("Subject", false); - put("Iat", false); - }}; - publicClaims = new HashSet() {{ - add(PublicClaims.ISSUER); - add(PublicClaims.SUBJECT); - add(PublicClaims.EXPIRES_AT); - add(PublicClaims.NOT_BEFORE); - add(PublicClaims.ISSUED_AT); - add(PublicClaims.JWT_ID); - add(PublicClaims.AUDIENCE); - }}; + private RiscJwtCreator() { } /** @@ -66,33 +38,31 @@ public RiscJwtCreator() { */ public RiscJwtCreator withJWTId(String jwtId) { jwt.withJWTId(jwtId); - addedClaims.put("Jti", true); + requiredClaimsRisc.put(Claims.JWT_ID, true); return this; } /** * Add a specific Issuer ("issuer") claim to the Payload. - * Allows for multiple issuers * * @param issuer the Issuer value. * @return this same Builder instance. */ - public RiscJwtCreator withIssuer(String... issuer) { + public RiscJwtCreator withIssuer(String issuer) { jwt.withIssuer(issuer); - addedClaims.put("Issuer", true); + requiredClaimsRisc.put(Claims.ISSUER, true); return this; } /** * Add a specific Subject ("subject") claim to the Payload. - * Allows for multiple subjects * * @param subject the Subject value. * @return this same Builder instance. */ - public RiscJwtCreator withSubject(String... subject) { + public RiscJwtCreator withSubject(String subject) { jwt.withSubject(subject); - addedClaims.put("Subject", true); + requiredClaimsRisc.put(Claims.SUBJECT, true); return this; } @@ -116,7 +86,7 @@ public RiscJwtCreator withAudience(String... audience) { */ public RiscJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - addedClaims.put("Iat", true); + requiredClaimsRisc.put(Claims.ISSUED_AT, true); return this; } @@ -151,7 +121,15 @@ public RiscJwtCreator withNbf(Date nbf) { * @throws IllegalArgumentException if the name is null. */ public RiscJwtCreator withNonStandardClaim(String name, String value) { - jwt.withNonStandardClaim(name, value); + if("subject".equalsIgnoreCase(name) || Claims.SUBJECT.equalsIgnoreCase(name)) { + withSubject(value); + } else if("issuer".equalsIgnoreCase(name) || Claims.ISSUER.equalsIgnoreCase(name)) { + withIssuer(value); + } else if(Claims.JWT_ID.equalsIgnoreCase(name) || "jwtId".equalsIgnoreCase(name) || "jwt_id".equalsIgnoreCase(name)) { + withJWTId(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -216,7 +194,11 @@ public RiscJwtCreator withNonStandardClaim(String name, Double value) throws Ill * @throws IllegalArgumentException if the name is null. */ public RiscJwtCreator withNonStandardClaim(String name, Date value) throws IllegalArgumentException { - jwt.withNonStandardClaim(name, value); + if(Claims.ISSUED_AT.equalsIgnoreCase(name) || "issuedAt".equalsIgnoreCase(name) || "issued_at".equalsIgnoreCase(name)) { + withIat(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -230,8 +212,8 @@ public RiscJwtCreator withNonStandardClaim(String name, Date value) throws Illeg */ public RiscJwtCreator withArrayClaim(String name, String... items) throws IllegalArgumentException { jwt.withArrayClaim(name, items); - if(publicClaims.contains(name)) - addedClaims.put(name, true); + if(requiredClaimsRisc.containsKey(name)) + requiredClaimsRisc.put(name, true); return this; } @@ -247,70 +229,6 @@ public RiscJwtCreator setIsNoneAlgorithmAllowed(boolean isNoneAlgorithmAllowed) return this; } - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String sign(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm); - verifyClaims(); - return JWS; - } - - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String signBase16Encoding(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm, EncodeType.Base16); - verifyClaims(); - return JWS; - } - - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String signBase32Encoding(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm, EncodeType.Base32); - verifyClaims(); - return JWS; - } - - /** - * Verifies that all the standard claims were provided - * @throws Exception if all the standard claims weren't provided - */ - private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) - throw new Exception("Standard claim: " + claim + " has not been set"); - } - public static RiscJwtCreator build() { return new RiscJwtCreator(); } diff --git a/lib/src/main/java/com/auth0/jwt/creators/ScopedJwtCreator.java b/lib/src/main/java/com/auth0/jwt/creators/ScopedJwtCreator.java index f27c8cb..c2e0925 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ScopedJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ScopedJwtCreator.java @@ -19,42 +19,15 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; -import com.auth0.jwt.jwts.JWT; - +import com.auth0.jwt.impl.Claims; import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; /** * The ScopedJwtCreator class holds the sign method to generate a complete Scoped JWT (with Signature) from a given Header and Payload content. */ -public class ScopedJwtCreator{ - - protected JWTCreator.Builder jwt; - protected HashMap addedClaims; - protected Set publicClaims; +public class ScopedJwtCreator extends Creator{ - public ScopedJwtCreator() { - jwt = JWT.create(); - addedClaims = new HashMap() {{ - put("Scope", false); - put("Issuer", false); - put("Subject", false); - put("Iat", false); - }}; - publicClaims = new HashSet() {{ - add(PublicClaims.ISSUER); - add(PublicClaims.SUBJECT); - add(PublicClaims.EXPIRES_AT); - add(PublicClaims.NOT_BEFORE); - add(PublicClaims.ISSUED_AT); - add(PublicClaims.JWT_ID); - add(PublicClaims.AUDIENCE); - }}; + private ScopedJwtCreator() { } /** @@ -65,34 +38,32 @@ public ScopedJwtCreator() { * @return this same Builder instance. */ public ScopedJwtCreator withScope(String scope) { - jwt.withNonStandardClaim("scope", scope); - addedClaims.put("Scope", true); + jwt.withNonStandardClaim(Claims.SCOPE, scope); + requiredClaimsScoped.put(Claims.SCOPE, true); return this; } /** * Add a specific Issuer ("issuer") claim to the Payload. - * Allows for multiple issuers * * @param issuer the Issuer value. * @return this same Builder instance. */ - public ScopedJwtCreator withIssuer(String... issuer) { + public ScopedJwtCreator withIssuer(String issuer) { jwt.withIssuer(issuer); - addedClaims.put("Issuer", true); + requiredClaimsScoped.put(Claims.ISSUER, true); return this; } /** * Add a specific Subject ("subject") claim to the Payload. - * Allows for multiple subjects * * @param subject the Subject value. * @return this same Builder instance. */ - public ScopedJwtCreator withSubject(String... subject) { + public ScopedJwtCreator withSubject(String subject) { jwt.withSubject(subject); - addedClaims.put("Subject", true); + requiredClaimsScoped.put(Claims.SUBJECT, true); return this; } @@ -116,7 +87,7 @@ public ScopedJwtCreator withAudience(String... audience) { */ public ScopedJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - addedClaims.put("Iat", true); + requiredClaimsScoped.put(Claims.ISSUED_AT, true); return this; } @@ -140,7 +111,15 @@ public ScopedJwtCreator withExp(Date exp) { * @throws IllegalArgumentException if the name is null. */ public ScopedJwtCreator withNonStandardClaim(String name, String value) { - jwt.withNonStandardClaim(name, value); + if("subject".equalsIgnoreCase(name) || Claims.SUBJECT.equalsIgnoreCase(name)) { + withSubject(value); + } else if("issuer".equalsIgnoreCase(name) || Claims.ISSUER.equalsIgnoreCase(name)) { + withIssuer(value); + } else if(Claims.SCOPE.equalsIgnoreCase(name)) { + withScope(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -205,7 +184,11 @@ public ScopedJwtCreator withNonStandardClaim(String name, Double value) throws I * @throws IllegalArgumentException if the name is null. */ public ScopedJwtCreator withNonStandardClaim(String name, Date value) throws IllegalArgumentException { - jwt.withNonStandardClaim(name, value); + if(Claims.ISSUED_AT.equalsIgnoreCase(name) || "issuedAt".equalsIgnoreCase(name) || "issued_at".equalsIgnoreCase(name)) { + withIat(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -219,8 +202,8 @@ public ScopedJwtCreator withNonStandardClaim(String name, Date value) throws Ill */ public ScopedJwtCreator withArrayClaim(String name, String... items) throws IllegalArgumentException { jwt.withArrayClaim(name, items); - if(publicClaims.contains(name)) - addedClaims.put(name, true); + if(requiredClaimsScoped.containsKey(name)) + requiredClaimsScoped.put(name, true); return this; } @@ -236,70 +219,6 @@ public ScopedJwtCreator setIsNoneAlgorithmAllowed(boolean isNoneAlgorithmAllowed return this; } - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String sign(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm); - verifyClaims(); - return JWS; - } - - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String signBase16Encoding(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm, EncodeType.Base16); - verifyClaims(); - return JWS; - } - - /** - * Creates a new JWT and signs it with the given algorithm. - * - * @param algorithm used to sign the JWT - * @return a new JWT token - * @throws IllegalAccessException if the developer didn't want NONE algorithm to be allowed and it was passed in - * @throws IllegalArgumentException if the provided algorithm is null. - * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. - */ - public String signBase32Encoding(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { - throw new IllegalAccessException("None algorithm isn't allowed"); - } - String JWS = jwt.sign(algorithm, EncodeType.Base32); - verifyClaims(); - return JWS; - } - - /** - * Verifies that all the standard claims were provided - * @throws Exception if all the standard claims weren't provided - */ - private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) - throw new Exception("Standard claim: " + claim + " has not been set"); - } - public static ScopedJwtCreator build() { return new ScopedJwtCreator(); } diff --git a/lib/src/main/java/com/auth0/jwt/exceptions/RequiredClaimException.java b/lib/src/main/java/com/auth0/jwt/exceptions/RequiredClaimException.java new file mode 100644 index 0000000..527cb56 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/exceptions/RequiredClaimException.java @@ -0,0 +1,7 @@ +package com.auth0.jwt.exceptions; + +public class RequiredClaimException extends JWTVerificationException { + public RequiredClaimException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/impl/PublicClaims.java b/lib/src/main/java/com/auth0/jwt/impl/Claims.java similarity index 87% rename from lib/src/main/java/com/auth0/jwt/impl/PublicClaims.java rename to lib/src/main/java/com/auth0/jwt/impl/Claims.java index b7594e1..bf05c17 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/PublicClaims.java +++ b/lib/src/main/java/com/auth0/jwt/impl/Claims.java @@ -20,7 +20,7 @@ package com.auth0.jwt.impl; -public interface PublicClaims { +public interface Claims { //Header String ALGORITHM = "alg"; @@ -37,4 +37,12 @@ public interface PublicClaims { String JWT_ID = "jti"; String AUDIENCE = "aud"; + //Nonstandard + String USER_ID = "userId"; + String APP_ID = "appId"; + String NAME = "name"; + String EMAIL = "email"; + String PICTURE = "picture"; + String SCOPE = "scope"; + } diff --git a/lib/src/main/java/com/auth0/jwt/impl/HeaderDeserializer.java b/lib/src/main/java/com/auth0/jwt/impl/HeaderDeserializer.java index 2c2b916..73c15f8 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/HeaderDeserializer.java +++ b/lib/src/main/java/com/auth0/jwt/impl/HeaderDeserializer.java @@ -47,10 +47,10 @@ public BasicHeader deserialize(JsonParser p, DeserializationContext ctxt) throws throw new JWTDecodeException("Parsing the Header's JSON resulted on a Null map"); } - String algorithm = getString(tree, PublicClaims.ALGORITHM); - String type = getString(tree, PublicClaims.TYPE); - String contentType = getString(tree, PublicClaims.CONTENT_TYPE); - String keyId = getString(tree, PublicClaims.KEY_ID); + String algorithm = getString(tree, Claims.ALGORITHM); + String type = getString(tree, Claims.TYPE); + String contentType = getString(tree, Claims.CONTENT_TYPE); + String keyId = getString(tree, Claims.KEY_ID); return new BasicHeader(algorithm, type, contentType, keyId, tree); } diff --git a/lib/src/main/java/com/auth0/jwt/impl/PayloadDeserializer.java b/lib/src/main/java/com/auth0/jwt/impl/PayloadDeserializer.java index babc935..2002b9a 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/PayloadDeserializer.java +++ b/lib/src/main/java/com/auth0/jwt/impl/PayloadDeserializer.java @@ -28,9 +28,12 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; - import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Map; class PayloadDeserializer extends StdDeserializer { @@ -50,13 +53,13 @@ public Payload deserialize(JsonParser p, DeserializationContext ctxt) throws IOE throw new JWTDecodeException("Parsing the Payload's JSON resulted on a Null map"); } - List issuer = getStringOrArray(tree, PublicClaims.ISSUER); - List subject = getStringOrArray(tree, PublicClaims.SUBJECT); - List audience = getStringOrArray(tree, PublicClaims.AUDIENCE); - Date expiresAt = getDateFromSeconds(tree, PublicClaims.EXPIRES_AT); - Date notBefore = getDateFromSeconds(tree, PublicClaims.NOT_BEFORE); - Date issuedAt = getDateFromSeconds(tree, PublicClaims.ISSUED_AT); - String jwtId = getString(tree, PublicClaims.JWT_ID); + List issuer = getStringOrArray(tree, Claims.ISSUER); + List subject = getStringOrArray(tree, Claims.SUBJECT); + List audience = getStringOrArray(tree, Claims.AUDIENCE); + Date expiresAt = getDateFromSeconds(tree, Claims.EXPIRES_AT); + Date notBefore = getDateFromSeconds(tree, Claims.NOT_BEFORE); + Date issuedAt = getDateFromSeconds(tree, Claims.ISSUED_AT); + String jwtId = getString(tree, Claims.JWT_ID); return new PayloadImpl(issuer, subject, audience, expiresAt, notBefore, issuedAt, jwtId, tree); } diff --git a/lib/src/main/java/com/auth0/jwt/impl/PayloadImpl.java b/lib/src/main/java/com/auth0/jwt/impl/PayloadImpl.java index a732416..5800585 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/PayloadImpl.java +++ b/lib/src/main/java/com/auth0/jwt/impl/PayloadImpl.java @@ -19,13 +19,16 @@ package com.auth0.jwt.impl; +import static com.auth0.jwt.impl.JsonNodeClaim.extractClaim; + import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.Payload; import com.fasterxml.jackson.databind.JsonNode; - -import java.util.*; - -import static com.auth0.jwt.impl.JsonNodeClaim.extractClaim; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * The PayloadImpl class implements the Payload interface. diff --git a/lib/src/main/java/com/auth0/jwt/impl/PayloadSerializer.java b/lib/src/main/java/com/auth0/jwt/impl/PayloadSerializer.java index 09915f8..b64331e 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/PayloadSerializer.java +++ b/lib/src/main/java/com/auth0/jwt/impl/PayloadSerializer.java @@ -43,7 +43,7 @@ public void serialize(ClaimsHolder holder, JsonGenerator gen, SerializerProvider HashMap safePayload = new HashMap<>(); for (Map.Entry e : holder.getClaims().entrySet()) { switch (e.getKey()) { - case PublicClaims.AUDIENCE: + case Claims.AUDIENCE: if (e.getValue() instanceof String) { safePayload.put(e.getKey(), e.getValue()); break; @@ -55,9 +55,9 @@ public void serialize(ClaimsHolder holder, JsonGenerator gen, SerializerProvider safePayload.put(e.getKey(), audArray); } break; - case PublicClaims.EXPIRES_AT: - case PublicClaims.ISSUED_AT: - case PublicClaims.NOT_BEFORE: + case Claims.EXPIRES_AT: + case Claims.ISSUED_AT: + case Claims.NOT_BEFORE: safePayload.put(e.getKey(), dateToSeconds((Date) e.getValue())); break; default: diff --git a/lib/src/main/java/com/auth0/jwt/interfaces/ExtendedVerification.java b/lib/src/main/java/com/auth0/jwt/interfaces/ExtendedVerification.java deleted file mode 100644 index 433a2b2..0000000 --- a/lib/src/main/java/com/auth0/jwt/interfaces/ExtendedVerification.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2017 The Authors of 'JWTS for Java' -// -// Permission is hereby granted, free of charge, to any person obtaining a copy of -// this software and associated documentation files (the "Software"), to deal in -// the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software is furnished to do so, -// subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -package com.auth0.jwt.interfaces; - -public interface ExtendedVerification { -} diff --git a/lib/src/main/java/com/auth0/jwt/jwts/AccessJWT.java b/lib/src/main/java/com/auth0/jwt/jwts/AccessJWT.java index aa58cee..3b8aa51 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/AccessJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/AccessJWT.java @@ -26,7 +26,7 @@ import java.util.List; -public class AccessJWT extends JWT.BaseVerification implements Verification { +public class AccessJWT extends JWT.BaseVerification { AccessJWT(Algorithm algorithm) throws IllegalArgumentException { super(algorithm); diff --git a/lib/src/main/java/com/auth0/jwt/jwts/ExtendedJWT.java b/lib/src/main/java/com/auth0/jwt/jwts/ExtendedJWT.java index 4887dcd..bd6900e 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/ExtendedJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/ExtendedJWT.java @@ -25,7 +25,7 @@ import java.util.List; -public class ExtendedJWT extends GoogleJWT implements GoogleVerification{ +public class ExtendedJWT extends GoogleJWT { ExtendedJWT(Algorithm algorithm) throws IllegalArgumentException { super(algorithm); diff --git a/lib/src/main/java/com/auth0/jwt/jwts/FbJWT.java b/lib/src/main/java/com/auth0/jwt/jwts/FbJWT.java index 83d746f..be32623 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/FbJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/FbJWT.java @@ -21,10 +21,11 @@ import com.auth0.jwt.ClockImpl; import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.interfaces.Clock; import com.auth0.jwt.interfaces.Verification; -public class FbJWT extends JWT.BaseVerification implements Verification{ +public class FbJWT extends JWT.BaseVerification{ FbJWT(Algorithm algorithm) throws IllegalArgumentException { super(algorithm); @@ -47,7 +48,7 @@ public Verification createVerifierForFb(String userId, String appId) { * @return this same Verification instance. */ public Verification withUserId(String userId) { - requireClaim("userId", userId); + requireClaim(Claims.USER_ID, userId); return this; } @@ -58,7 +59,7 @@ public Verification withUserId(String userId) { * @return this same Verification instance. */ public Verification withAppId(String appId) { - requireClaim("appId", appId); + requireClaim(Claims.APP_ID, appId); return this; } diff --git a/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java b/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java index 1aaf574..f94bdad 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java @@ -21,6 +21,7 @@ import com.auth0.jwt.ClockImpl; import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.interfaces.Clock; import com.auth0.jwt.interfaces.GoogleVerification; import com.auth0.jwt.interfaces.Verification; @@ -56,7 +57,7 @@ public Verification createVerifierForGoogle(String picture, String email, List issuer, List audience, String name, long nbf, long expLeeway, long iatLeeway) { - throw new UnsupportedOperationException("you shouldn't be calling this method"); + throw new UnsupportedOperationException("this method has not been implemented"); } /** diff --git a/lib/src/main/java/com/auth0/jwt/jwts/ImplicitJWT.java b/lib/src/main/java/com/auth0/jwt/jwts/ImplicitJWT.java index 91eb070..546f5c9 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/ImplicitJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/ImplicitJWT.java @@ -26,7 +26,7 @@ import java.util.List; -public class ImplicitJWT extends JWT.BaseVerification implements Verification{ +public class ImplicitJWT extends JWT.BaseVerification { ImplicitJWT(Algorithm algorithm) throws IllegalArgumentException { super(algorithm); diff --git a/lib/src/main/java/com/auth0/jwt/jwts/JWT.java b/lib/src/main/java/com/auth0/jwt/jwts/JWT.java index 4557a67..516d31a 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/JWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/JWT.java @@ -20,18 +20,25 @@ package com.auth0.jwt.jwts; import com.auth0.jwt.ClockImpl; -import com.auth0.jwt.creators.EncodeType; -import com.auth0.jwt.creators.JWTCreator; import com.auth0.jwt.JWTDecoder; import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.exceptions.*; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.creators.EncodeType; +import com.auth0.jwt.creators.JWTCreator; +import com.auth0.jwt.exceptions.AlgorithmMismatchException; +import com.auth0.jwt.exceptions.InvalidClaimException; +import com.auth0.jwt.exceptions.SignatureVerificationException; +import com.auth0.jwt.exceptions.TokenExpiredException; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.interfaces.Clock; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; import com.auth0.jwt.verification.VerificationAndAssertion; - -import java.util.*; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @SuppressWarnings("WeakerAccess") public class JWT { @@ -66,6 +73,28 @@ public DecodedJWT decode(String token) throws Exception { return jwt; } + /** + * Convert the given token to a DecodedJWT + *

+ * Note that this method doesn't verify the token's signature! Use it only if you trust the token or you already verified it. + * + * @param token with jwt format as string. + * @param jwksFile + * @param pemFile + * @return a decoded JWT. + * @throws AlgorithmMismatchException if the algorithm stated in the token's header it's not equal to the one defined in the {@link JWT}. + * @throws SignatureVerificationException if the signature is invalid. + * @throws TokenExpiredException if the token has expired. + * @throws InvalidClaimException if a claim contained a different value than the expected one. + */ + public DecodedJWT decodeWithX509(String token, String jwksFile, String pemFile) throws Exception { + DecodedJWT jwt = new JWTDecoder(token, EncodeType.Base64); + VerificationAndAssertion.verifyAlgorithm(jwt, algorithm); + algorithm.verifyWithX509(jwt, jwksFile, pemFile); + VerificationAndAssertion.verifyClaims(clock, jwt, claims); + return jwt; + } + /** * Convert the given token to a DecodedJWT *

@@ -86,6 +115,28 @@ public DecodedJWT decode16Bytes(String token) throws Exception { return jwt; } + /** + * Convert the given token to a DecodedJWT + *

+ * Note that this method doesn't verify the token's signature! Use it only if you trust the token or you already verified it. + * + * @param token with jwt format as string. + * @param jwksFile + * @param pemFile + * @return a decoded JWT. + * @throws AlgorithmMismatchException if the algorithm stated in the token's header it's not equal to the one defined in the {@link JWT}. + * @throws SignatureVerificationException if the signature is invalid. + * @throws TokenExpiredException if the token has expired. + * @throws InvalidClaimException if a claim contained a different value than the expected one. + */ + public DecodedJWT decode16BytesWithX509(String token, String jwksFile, String pemFile) throws Exception { + DecodedJWT jwt = new JWTDecoder(token, EncodeType.Base16); + VerificationAndAssertion.verifyAlgorithm(jwt, algorithm); + algorithm.verifyWithX509(jwt, jwksFile, pemFile); + VerificationAndAssertion.verifyClaims(clock, jwt, claims); + return jwt; + } + /** * Convert the given token to a DecodedJWT *

@@ -106,6 +157,28 @@ public DecodedJWT decode32Bytes(String token) throws Exception { return jwt; } + /** + * Convert the given token to a DecodedJWT + *

+ * Note that this method doesn't verify the token's signature! Use it only if you trust the token or you already verified it. + * + * @param token with jwt format as string. + * @param jwksFile + * @param pemFile + * @return a decoded JWT. + * @throws AlgorithmMismatchException if the algorithm stated in the token's header it's not equal to the one defined in the {@link JWT}. + * @throws SignatureVerificationException if the signature is invalid. + * @throws TokenExpiredException if the token has expired. + * @throws InvalidClaimException if a claim contained a different value than the expected one. + */ + public DecodedJWT decode32BytesWithX509(String token, String jwksFile, String pemFile) throws Exception { + DecodedJWT jwt = new JWTDecoder(token, EncodeType.Base32); + VerificationAndAssertion.verifyAlgorithm(jwt, algorithm); + algorithm.verifyWithX509(jwt, jwksFile, pemFile); + VerificationAndAssertion.verifyClaims(clock, jwt, claims); + return jwt; + } + /** * Returns a {Verification} to be used to validate token signature. * @@ -114,7 +187,7 @@ public DecodedJWT decode32Bytes(String token) throws Exception { * @throws IllegalArgumentException if the provided algorithm is null. */ public static Verification require(Algorithm algorithm) { - return JWT.init(algorithm); + return new JWT.BaseVerification(algorithm); } /** @@ -128,17 +201,6 @@ public static JWTCreator.Builder create() { //----------------this is from JWTVerifier-------- - /** - * Initialize a Verification instance using the given Algorithm. - * - * @param algorithm the Algorithm to use on the JWT verification. - * @return a JWT.BaseVerification instance to configure. - * @throws IllegalArgumentException if the provided algorithm is null. - */ - static Verification init(Algorithm algorithm) throws IllegalArgumentException { - return new JWT.BaseVerification(algorithm); - } - /** * The Verification class holds the Claims required by a JWT to be valid. */ @@ -159,43 +221,43 @@ public static class BaseVerification implements Verification { @Override public Verification withNbf(long nbf) { - throw new UnsupportedOperationException("you shouldn't be calling this method"); + throw new UnsupportedOperationException("this method has not been implemented"); } @Override public Verification createVerifierForRisc(String jti, List issuer, List audience, long iatLeeway, long expLeeway, long nbf) { - throw new UnsupportedOperationException("you shouldn't be calling this method"); + throw new UnsupportedOperationException("this method has not been implemented"); } @Override public Verification createVerifierForScoped(String scope, List issuer, List audience, long expLeeway, long iatLeeway) { - throw new UnsupportedOperationException("you shouldn't be calling this method"); + throw new UnsupportedOperationException("this method has not been implemented"); } @Override public Verification createVerifierForImplicit(List issuer, List audience, long iatLeeway) { - throw new UnsupportedOperationException("you shouldn't be calling this method"); + throw new UnsupportedOperationException("this method has not been implemented"); } @Override public Verification createVerifierForFb(String userId, String appId) { - throw new UnsupportedOperationException("you shouldn't be calling this method"); + throw new UnsupportedOperationException("this method has not been implemented"); } @Override public Verification withUserId(String userId) { - throw new UnsupportedOperationException("you shouldn't be calling this method"); + throw new UnsupportedOperationException("this method has not been implemented"); } @Override public Verification withAppId(String appId) { - throw new UnsupportedOperationException("you shouldn't be calling this method"); + throw new UnsupportedOperationException("this method has not been implemented"); } @Override public Verification createVerifierForAccess(List issuer, List audience, long expLeeway, long iatLeeway) { - throw new UnsupportedOperationException("you shouldn't be calling this method"); + throw new UnsupportedOperationException("this method has not been implemented"); } /** @@ -207,7 +269,7 @@ public Verification createVerifierForAccess(List issuer, List au */ @Override public Verification withIssuer(String... issuer) { - requireClaim(PublicClaims.ISSUER, Arrays.asList(issuer)); + requireClaim(Claims.ISSUER, Arrays.asList(issuer)); return this; } @@ -220,7 +282,7 @@ public Verification withIssuer(String... issuer) { */ @Override public Verification withSubject(String... subject) { - requireClaim(PublicClaims.SUBJECT, Arrays.asList(subject)); + requireClaim(Claims.SUBJECT, Arrays.asList(subject)); return this; } @@ -233,7 +295,7 @@ public Verification withSubject(String... subject) { */ @Override public Verification withAudience(String... audience) { - requireClaim(PublicClaims.AUDIENCE, Arrays.asList(audience)); + requireClaim(Claims.AUDIENCE, Arrays.asList(audience)); return this; } @@ -263,7 +325,7 @@ public Verification acceptLeeway(long leeway) throws IllegalArgumentException { @Override public Verification acceptExpiresAt(long leeway) throws IllegalArgumentException { VerificationAndAssertion.assertPositive(leeway); - requireClaim(PublicClaims.EXPIRES_AT, leeway); + requireClaim(Claims.EXPIRES_AT, leeway); return this; } @@ -278,7 +340,7 @@ public Verification acceptExpiresAt(long leeway) throws IllegalArgumentException @Override public Verification acceptNotBefore(long leeway) throws IllegalArgumentException { VerificationAndAssertion.assertPositive(leeway); - requireClaim(PublicClaims.NOT_BEFORE, leeway); + requireClaim(Claims.NOT_BEFORE, leeway); return this; } @@ -293,7 +355,7 @@ public Verification acceptNotBefore(long leeway) throws IllegalArgumentException @Override public Verification acceptIssuedAt(long leeway) throws IllegalArgumentException { VerificationAndAssertion.assertPositive(leeway); - requireClaim(PublicClaims.ISSUED_AT, leeway); + requireClaim(Claims.ISSUED_AT, leeway); return this; } @@ -305,7 +367,7 @@ public Verification acceptIssuedAt(long leeway) throws IllegalArgumentException */ @Override public Verification withJWTId(String jwtId) { - requireClaim(PublicClaims.JWT_ID, jwtId); + requireClaim(Claims.JWT_ID, jwtId); return this; } @@ -452,14 +514,14 @@ public JWT build(Clock clock) { } protected void addLeewayToDateClaims() { - if (!claims.containsKey(PublicClaims.EXPIRES_AT)) { - claims.put(PublicClaims.EXPIRES_AT, defaultLeeway); + if (!claims.containsKey(Claims.EXPIRES_AT)) { + claims.put(Claims.EXPIRES_AT, defaultLeeway); } - if (!claims.containsKey(PublicClaims.NOT_BEFORE)) { - claims.put(PublicClaims.NOT_BEFORE, defaultLeeway); + if (!claims.containsKey(Claims.NOT_BEFORE)) { + claims.put(Claims.NOT_BEFORE, defaultLeeway); } - if (!claims.containsKey(PublicClaims.ISSUED_AT)) { - claims.put(PublicClaims.ISSUED_AT, defaultLeeway); + if (!claims.containsKey(Claims.ISSUED_AT)) { + claims.put(Claims.ISSUED_AT, defaultLeeway); } } @@ -471,4 +533,4 @@ protected void requireClaim(String name, Object value) { claims.put(name, value); } } -} +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/jwts/RiscJWT.java b/lib/src/main/java/com/auth0/jwt/jwts/RiscJWT.java index 5d126b8..03690e4 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/RiscJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/RiscJWT.java @@ -26,7 +26,7 @@ import java.util.List; -public class RiscJWT extends JWT.BaseVerification implements Verification { +public class RiscJWT extends JWT.BaseVerification { RiscJWT(Algorithm algorithm) throws IllegalArgumentException { super(algorithm); diff --git a/lib/src/main/java/com/auth0/jwt/jwts/ScopedJWT.java b/lib/src/main/java/com/auth0/jwt/jwts/ScopedJWT.java index 0354502..71402f6 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/ScopedJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/ScopedJWT.java @@ -21,12 +21,13 @@ import com.auth0.jwt.ClockImpl; import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.interfaces.Clock; import com.auth0.jwt.interfaces.Verification; import java.util.List; -public class ScopedJWT extends JWT.BaseVerification implements Verification{ +public class ScopedJWT extends JWT.BaseVerification { ScopedJWT(Algorithm algorithm) throws IllegalArgumentException { super(algorithm); @@ -52,7 +53,7 @@ public Verification createVerifierForScoped(String scope, List issuer, * @return this same Verification instance. */ public Verification withScope(String scope) { - requireClaim("scope", scope); + requireClaim(Claims.SCOPE, scope); return this; } diff --git a/lib/src/main/java/com/auth0/jwt/TokenUtils.java b/lib/src/main/java/com/auth0/jwt/utils/TokenUtils.java similarity index 98% rename from lib/src/main/java/com/auth0/jwt/TokenUtils.java rename to lib/src/main/java/com/auth0/jwt/utils/TokenUtils.java index ed691be..ede2577 100644 --- a/lib/src/main/java/com/auth0/jwt/TokenUtils.java +++ b/lib/src/main/java/com/auth0/jwt/utils/TokenUtils.java @@ -17,7 +17,7 @@ // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -package com.auth0.jwt; +package com.auth0.jwt.utils; import com.auth0.jwt.exceptions.JWTDecodeException; diff --git a/lib/src/main/java/com/auth0/jwt/verification/VerificationAndAssertion.java b/lib/src/main/java/com/auth0/jwt/verification/VerificationAndAssertion.java index f8fff86..8cfba4c 100644 --- a/lib/src/main/java/com/auth0/jwt/verification/VerificationAndAssertion.java +++ b/lib/src/main/java/com/auth0/jwt/verification/VerificationAndAssertion.java @@ -23,7 +23,7 @@ import com.auth0.jwt.exceptions.AlgorithmMismatchException; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.Clock; import com.auth0.jwt.interfaces.DecodedJWT; @@ -56,27 +56,26 @@ public static void verifyAlgorithm(DecodedJWT jwt, Algorithm expectedAlgorithm) public static void verifyClaims(Clock clock, DecodedJWT jwt, Map claims) throws TokenExpiredException, InvalidClaimException { for (Map.Entry entry : claims.entrySet()) { switch (entry.getKey()) { - case PublicClaims.AUDIENCE: - //noinspection unchecked - VerificationAndAssertion.assertValidAudienceClaim(jwt.getAudience(), (List) entry.getValue()); + case Claims.AUDIENCE: + assertValidAudienceClaim(jwt.getAudience(), (List) entry.getValue()); break; - case PublicClaims.EXPIRES_AT: + case Claims.EXPIRES_AT: assertValidDateClaim(clock, jwt.getExpiresAt(), (Long) entry.getValue(), true); break; - case PublicClaims.ISSUED_AT: + case Claims.ISSUED_AT: assertValidDateClaim(clock, jwt.getIssuedAt(), (Long) entry.getValue(), false); break; - case PublicClaims.NOT_BEFORE: + case Claims.NOT_BEFORE: assertValidDateClaim(clock, jwt.getNotBefore(), (Long) entry.getValue(), false); break; - case PublicClaims.ISSUER: - VerificationAndAssertion.assertValidIssuerClaim(jwt.getIssuer(), (List) entry.getValue()); + case Claims.ISSUER: + assertValidIssuerClaim(jwt.getIssuer(), (List) entry.getValue()); break; - case PublicClaims.JWT_ID: - VerificationAndAssertion.assertValidStringClaim(entry.getKey(), jwt.getId(), (String) entry.getValue()); + case Claims.JWT_ID: + assertValidStringClaim(entry.getKey(), jwt.getId(), (String) entry.getValue()); break; default: - VerificationAndAssertion.assertValidClaim(jwt.getClaim(entry.getKey()), entry.getKey(), entry.getValue()); + assertValidClaim(jwt.getClaim(entry.getKey()), entry.getKey(), entry.getValue()); break; } } @@ -137,14 +136,14 @@ private static void assertDateIsPast(Date date, long leeway, Date today) { } } - private static void assertValidAudienceClaim(List audience, List value) { - if (audience == null || !audience.containsAll(value) || audience.size() != value.size()) { + private static void assertValidAudienceClaim(List actual, List expected) { + if (actual == null || !actual.containsAll(expected)) { throw new InvalidClaimException("The Claim 'aud' value doesn't contain the required audience."); } } - private static void assertValidIssuerClaim(List issuer, List value) { - if (issuer == null || !issuer.containsAll(value) || issuer.size() != value.size()) { + private static void assertValidIssuerClaim(List actual, List expected) { + if (actual == null || !actual.containsAll(expected)) { throw new InvalidClaimException("The Claim 'iss' value doesn't match the required one."); } } diff --git a/lib/src/test/java/com/auth0/jwt/ClockImplTest.java b/lib/src/test/java/com/auth0/jwt/ClockImplTest.java index 6fdb01b..e869115 100644 --- a/lib/src/test/java/com/auth0/jwt/ClockImplTest.java +++ b/lib/src/test/java/com/auth0/jwt/ClockImplTest.java @@ -19,14 +19,13 @@ package com.auth0.jwt; -import com.auth0.jwt.interfaces.Clock; -import org.junit.Test; - -import java.util.Date; - import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.*; +import static org.junit.Assert.assertThat; + +import com.auth0.jwt.interfaces.Clock; +import java.util.Date; +import org.junit.Test; public class ClockImplTest { diff --git a/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java b/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java index 64120dd..f155c1f 100644 --- a/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java +++ b/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java @@ -19,9 +19,20 @@ package com.auth0.jwt; +import static com.auth0.jwt.PemUtils.readPublicKeyFromFile; + import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.jwts.JWT; +import java.security.interfaces.ECKey; +import java.security.interfaces.RSAKey; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import net.jodah.concurrentunit.Waiter; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -29,14 +40,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import java.security.interfaces.ECKey; -import java.security.interfaces.RSAKey; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.*; - -import static com.auth0.jwt.PemUtils.readPublicKeyFromFile; - //@Ignore("Skipping concurrency tests") public class ConcurrentVerifyTest { diff --git a/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java b/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java index 8ff3844..977d1ee 100644 --- a/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java +++ b/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java @@ -19,27 +19,32 @@ package com.auth0.jwt; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTDecodeException; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.jwts.JWT; +import java.nio.charset.StandardCharsets; +import java.util.Date; +import java.util.Map; import org.apache.commons.codec.binary.Base64; import org.hamcrest.collection.IsCollectionWithSize; import org.hamcrest.core.IsCollectionContaining; import org.junit.Assert; -import static org.junit.Assert.assertTrue; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.nio.charset.StandardCharsets; -import java.util.Date; -import java.util.Map; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; - public class JWTDecoderTest { @Rule @@ -48,7 +53,7 @@ public class JWTDecoderTest { @Test public void getSubject() throws Exception { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).withNonStandardClaim("admin", true).withNonStandardClaim("name", "John Doe").build(); + JWT jwt = JWT.require(Algorithm.HMAC256("secret")).withNonStandardClaim("admin", true).withNonStandardClaim(Claims.NAME, "John Doe").build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT.getSubject(), is(notNullValue())); assertTrue(decodedJWT.getSubject().contains("1234567890")); @@ -59,7 +64,7 @@ public void getSubject() throws Exception { public void shouldThrowIfLessThan3Parts() throws Exception { exception.expect(JWTDecodeException.class); exception.expectMessage("The token was expected to have 3 parts, but got 2."); - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).withNonStandardClaim("admin", true).withNonStandardClaim("name", "John Doe").build(); + JWT jwt = JWT.require(Algorithm.HMAC256("secret")).withNonStandardClaim("admin", true).withNonStandardClaim(Claims.NAME, "John Doe").build(); DecodedJWT decodedJWT = jwt.decode("two.parts"); } @@ -67,7 +72,7 @@ public void shouldThrowIfLessThan3Parts() throws Exception { public void shouldThrowIfMoreThan3Parts() throws Exception { exception.expect(JWTDecodeException.class); exception.expectMessage("The token was expected to have 3 parts, but got 4."); - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).withNonStandardClaim("admin", true).withNonStandardClaim("name", "John Doe").build(); + JWT jwt = JWT.require(Algorithm.HMAC256("secret")).withNonStandardClaim("admin", true).withNonStandardClaim(Claims.NAME, "John Doe").build(); DecodedJWT decodedJWT = jwt.decode("this.has.four.parts"); } @@ -128,7 +133,7 @@ public void shouldGetSignature() throws Exception { assertThat(decodedJWT.getSignature(), is("XmNK3GpH3Ys_7wsYBfq4C3M6goz71I7dTgUkuIa5lyQ")); } - // Public PublicClaims + // Public Claims @Test public void shouldGetIssuer() throws Exception { @@ -243,7 +248,7 @@ public void shouldGetAlgorithm() throws Exception { assertThat(decodedJWT.getAlgorithm(), is("HS256")); } - //Private PublicClaims + //Private Claims @Test @@ -273,7 +278,7 @@ public void shouldGetCustomClaimOfTypeInteger() throws Exception { JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); DecodedJWT decodedJWT = jwt.decode(token); Assert.assertThat(decodedJWT, is(notNullValue())); - Assert.assertThat(decodedJWT.getClaim("name").asInt(), is(123)); + Assert.assertThat(decodedJWT.getClaim(Claims.NAME).asInt(), is(123)); } @Test @@ -282,7 +287,7 @@ public void shouldGetCustomClaimOfTypeDouble() throws Exception { JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); DecodedJWT decodedJWT = jwt.decode(token); Assert.assertThat(decodedJWT, is(notNullValue())); - Assert.assertThat(decodedJWT.getClaim("name").asDouble(), is(23.45)); + Assert.assertThat(decodedJWT.getClaim(Claims.NAME).asDouble(), is(23.45)); } @Test @@ -291,7 +296,7 @@ public void shouldGetCustomClaimOfTypeBoolean() throws Exception { JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); DecodedJWT decodedJWT = jwt.decode(token); Assert.assertThat(decodedJWT, is(notNullValue())); - Assert.assertThat(decodedJWT.getClaim("name").asBoolean(), is(true)); + Assert.assertThat(decodedJWT.getClaim(Claims.NAME).asBoolean(), is(true)); } @Test @@ -301,7 +306,7 @@ public void shouldGetCustomClaimOfTypeDate() throws Exception { DecodedJWT decodedJWT = jwt.decode(token); Date date = new Date(1478891521000L); Assert.assertThat(decodedJWT, is(notNullValue())); - Assert.assertThat(decodedJWT.getClaim("name").asDate().getTime(), is(date.getTime())); + Assert.assertThat(decodedJWT.getClaim(Claims.NAME).asDate().getTime(), is(date.getTime())); } @Test @@ -310,7 +315,7 @@ public void shouldGetCustomArrayClaimOfTypeString() throws Exception { JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); DecodedJWT decodedJWT = jwt.decode(token); Assert.assertThat(decodedJWT, is(notNullValue())); - Assert.assertThat(decodedJWT.getClaim("name").asArray(String.class), arrayContaining("text", "123", "true")); + Assert.assertThat(decodedJWT.getClaim(Claims.NAME).asArray(String.class), arrayContaining("text", "123", "true")); } @Test @@ -319,7 +324,7 @@ public void shouldGetCustomArrayClaimOfTypeInteger() throws Exception { JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); DecodedJWT decodedJWT = jwt.decode(token); Assert.assertThat(decodedJWT, is(notNullValue())); - Assert.assertThat(decodedJWT.getClaim("name").asArray(Integer.class), arrayContaining(1, 2, 3)); + Assert.assertThat(decodedJWT.getClaim(Claims.NAME).asArray(Integer.class), arrayContaining(1, 2, 3)); } @Test @@ -328,7 +333,7 @@ public void shouldGetCustomMapClaim() throws Exception { JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); DecodedJWT decodedJWT = jwt.decode(token); Assert.assertThat(decodedJWT, is(notNullValue())); - Map map = decodedJWT.getClaim("name").asMap(); + Map map = decodedJWT.getClaim(Claims.NAME).asMap(); Assert.assertThat(map, hasEntry("string", (Object) "value")); Assert.assertThat(map, hasEntry("number", (Object) 1)); Assert.assertThat(map, hasEntry("boolean", (Object) true)); @@ -346,7 +351,7 @@ public void shouldGetAvailableClaims() throws Exception { assertThat(claims.get("exp"), is(notNullValue())); assertThat(claims.get("iat"), is(notNullValue())); assertThat(claims.get("nbf"), is(notNullValue())); - assertThat(claims.get("jti"), is(notNullValue())); + assertThat(claims.get(Claims.JWT_ID), is(notNullValue())); assertThat(claims.get("aud"), is(notNullValue())); assertThat(claims.get("sub"), is(notNullValue())); assertThat(claims.get("iss"), is(notNullValue())); diff --git a/lib/src/test/java/com/auth0/jwt/JWTTest.java b/lib/src/test/java/com/auth0/jwt/JWTTest.java index b368d43..74598da 100644 --- a/lib/src/test/java/com/auth0/jwt/JWTTest.java +++ b/lib/src/test/java/com/auth0/jwt/JWTTest.java @@ -20,26 +20,12 @@ package com.auth0.jwt; import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.interfaces.Clock; -import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.jwts.JWT; -import org.apache.commons.codec.binary.Base64; -import org.hamcrest.collection.IsCollectionWithSize; -import org.hamcrest.core.IsCollectionContaining; +import java.util.Date; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.nio.charset.StandardCharsets; -import java.security.interfaces.ECKey; -import java.security.interfaces.RSAKey; -import java.util.Date; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class JWTTest { @Rule @@ -48,56 +34,56 @@ public class JWTTest { @Test public void testWithNbf() { thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("you shouldn't be calling this method"); + thrown.expectMessage("this method has not been implemented"); JWT.require(Algorithm.none()).withNbf(5); } @Test public void testCreateVerifierForRisc() { thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("you shouldn't be calling this method"); + thrown.expectMessage("this method has not been implemented"); JWT.require(Algorithm.none()).createVerifierForRisc(null, null, null, 5, 5, 5); } @Test public void testCreateVerifierForScoped() { thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("you shouldn't be calling this method"); + thrown.expectMessage("this method has not been implemented"); JWT.require(Algorithm.none()).createVerifierForScoped(null, null, null, 5, 5); } @Test public void testCreateVerifierForImplicit() { thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("you shouldn't be calling this method"); + thrown.expectMessage("this method has not been implemented"); JWT.require(Algorithm.none()).createVerifierForImplicit(null, null, 5); } @Test public void testCreateVerifierForFB() { thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("you shouldn't be calling this method"); + thrown.expectMessage("this method has not been implemented"); JWT.require(Algorithm.none()).createVerifierForFb(null, null); } @Test public void testCreateVerifierForAccess() { thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("you shouldn't be calling this method"); + thrown.expectMessage("this method has not been implemented"); JWT.require(Algorithm.none()).createVerifierForAccess(null, null, 5, 5); } @Test public void testWithUserId() { thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("you shouldn't be calling this method"); + thrown.expectMessage("this method has not been implemented"); JWT.require(Algorithm.none()).withUserId(null); } @Test public void testWithAppId() { thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("you shouldn't be calling this method"); + thrown.expectMessage("this method has not been implemented"); JWT.require(Algorithm.none()).withAppId(null); } diff --git a/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java b/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java index bc298eb..4ea8edc 100644 --- a/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java +++ b/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java @@ -21,25 +21,25 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static java.util.Arrays.asList; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.creators.GoogleJwtCreator; import com.auth0.jwt.creators.GoogleJwtCreatorTest; import com.auth0.jwt.exceptions.InvalidClaimException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.GoogleVerification; import com.auth0.jwt.jwts.GoogleJWT; import com.auth0.jwt.jwts.JWT; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertTrue; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - import java.util.Date; import java.util.List; import java.util.Map; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; public class MainTestSignatures { @@ -90,30 +90,28 @@ public void testConfigurableToMultipleKeys() throws Exception { String token = GoogleJwtCreator.build() .withPicture(GoogleJwtCreatorTest.PICTURE) .withEmail(GoogleJwtCreatorTest.EMAIL) - .withSubject("subject", "subject2") + .withSubject("subject") .withAudience("audience", "audience2") .withExp(exp) .withIat(iat) .withName(GoogleJwtCreatorTest.NAME) - .withIssuer("issuer", "issuer2") + .withIssuer("issuer") .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(GoogleJwtCreatorTest.PICTURE, GoogleJwtCreatorTest.EMAIL, asList("issuer", "issuer2"), asList("audience", "audience2"), + JWT verifier = verification.createVerifierForGoogle(GoogleJwtCreatorTest.PICTURE, GoogleJwtCreatorTest.EMAIL, asList("issuer", "issuer2"), asList("audience", "audience2", "audience3"), GoogleJwtCreatorTest.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); assertTrue(claims.get(GoogleJwtCreatorTest.PICTURE).asString().equals(GoogleJwtCreatorTest.PICTURE)); assertTrue(claims.get(GoogleJwtCreatorTest.EMAIL).asString().equals(GoogleJwtCreatorTest.EMAIL)); - List issuers = claims.get(PublicClaims.ISSUER).asList(String.class); - assertTrue(issuers.get(0).equals("issuer")); - assertTrue(issuers.get(1).equals("issuer2")); - List subjects = claims.get(PublicClaims.SUBJECT).asList(String.class); - assertTrue(subjects.get(0).equals("subject")); - assertTrue(subjects.get(1).equals("subject2")); - List audience = claims.get(PublicClaims.AUDIENCE).asList(String.class); + String issuer = claims.get(Claims.ISSUER).asString(); + assertTrue(issuer.equals("issuer")); + String subject = claims.get(Claims.SUBJECT).asString(); + assertTrue(subject.equals("subject")); + List audience = claims.get(Claims.AUDIENCE).asList(String.class); assertTrue(audience.get(0).equals("audience")); assertTrue(audience.get(1).equals("audience2")); - assertTrue(claims.get(PublicClaims.EXPIRES_AT).asDate().toString().equals(exp.toString())); + assertTrue(claims.get(Claims.EXPIRES_AT).asDate().toString().equals(exp.toString())); assertTrue(claims.get(GoogleJwtCreatorTest.NAME).asString().equals(GoogleJwtCreatorTest.NAME)); } @@ -123,16 +121,15 @@ public void testConfigurableToIncorrectNumberMultipleKeysForAudience() throws Ex thrown.expectMessage("The Claim 'aud' value doesn't contain the required audience."); Algorithm algorithm = Algorithm.HMAC256("secret"); - String[] arr = {"accounts.fake.com", "subject"}; String token = GoogleJwtCreator.build() .withPicture(GoogleJwtCreatorTest.PICTURE) .withEmail(GoogleJwtCreatorTest.EMAIL) - .withSubject("subject", "subject2") + .withSubject("subject") .withAudience("audience", "audience2") .withExp(exp) .withIat(iat) .withName(GoogleJwtCreatorTest.NAME) - .withIssuer("issuer", "issuer2") + .withIssuer("issuer") .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); JWT verifier = verification.createVerifierForGoogle(GoogleJwtCreatorTest.PICTURE, GoogleJwtCreatorTest.EMAIL, asList("issuer", "issuer2"), asList("audience"), @@ -146,16 +143,15 @@ public void testConfigurableToIncorrectValueMultipleKeysForAudience() throws Exc thrown.expectMessage("The Claim 'aud' value doesn't contain the required audience."); Algorithm algorithm = Algorithm.HMAC256("secret"); - String[] arr = {"accounts.fake.com", "subject"}; String token = GoogleJwtCreator.build() .withPicture(GoogleJwtCreatorTest.PICTURE) .withEmail(GoogleJwtCreatorTest.EMAIL) - .withSubject("subject", "subject2") + .withSubject("subject") .withAudience("audience", "audience2") .withExp(exp) .withIat(iat) .withName(GoogleJwtCreatorTest.NAME) - .withIssuer("issuer", "issuer2") + .withIssuer("issuer") .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); JWT verifier = verification.createVerifierForGoogle(GoogleJwtCreatorTest.PICTURE, GoogleJwtCreatorTest.EMAIL, asList("issuer", "issuer2"), asList("audience", "audience3"), diff --git a/lib/src/test/java/com/auth0/jwt/TokenUtilsTest.java b/lib/src/test/java/com/auth0/jwt/TokenUtilsTest.java index c0f375e..de39f1b 100644 --- a/lib/src/test/java/com/auth0/jwt/TokenUtilsTest.java +++ b/lib/src/test/java/com/auth0/jwt/TokenUtilsTest.java @@ -19,14 +19,18 @@ package com.auth0.jwt; +import static org.hamcrest.Matchers.arrayWithSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + import com.auth0.jwt.exceptions.JWTDecodeException; +import com.auth0.jwt.utils.TokenUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; - public class TokenUtilsTest { @Rule diff --git a/lib/src/test/java/com/auth0/jwt/algorithms/AlgorithmTest.java b/lib/src/test/java/com/auth0/jwt/algorithms/AlgorithmTest.java index 048a712..5aea893 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/AlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/AlgorithmTest.java @@ -19,20 +19,26 @@ package com.auth0.jwt.algorithms; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.withSettings; + import com.auth0.jwt.interfaces.ECDSAKeyProvider; import com.auth0.jwt.interfaces.RSAKeyProvider; +import java.nio.charset.StandardCharsets; +import java.security.interfaces.ECKey; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.ECPublicKey; +import java.security.interfaces.RSAKey; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.nio.charset.StandardCharsets; -import java.security.interfaces.*; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.withSettings; - public class AlgorithmTest { @Rule diff --git a/lib/src/test/java/com/auth0/jwt/algorithms/ECDSAAlgorithmTest.java b/lib/src/test/java/com/auth0/jwt/algorithms/ECDSAAlgorithmTest.java index ef3f917..8d2f8e7 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/ECDSAAlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/ECDSAAlgorithmTest.java @@ -19,13 +19,36 @@ package com.auth0.jwt.algorithms; -import com.auth0.jwt.creators.EncodeType; +import static com.auth0.jwt.PemUtils.readPrivateKeyFromFile; +import static com.auth0.jwt.PemUtils.readPublicKeyFromFile; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.isA; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.auth0.jwt.exceptions.AlgorithmMismatchException; import com.auth0.jwt.exceptions.SignatureGenerationException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.ECDSAKeyProvider; import com.auth0.jwt.jwts.JWT; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.SignatureException; +import java.security.interfaces.ECKey; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.ECPublicKey; +import java.util.Arrays; import org.apache.commons.codec.binary.Base64; import org.hamcrest.Matchers; import org.hamcrest.collection.IsIn; @@ -34,24 +57,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import java.nio.charset.StandardCharsets; -import java.security.*; -import java.security.interfaces.ECKey; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.util.Arrays; - -import static com.auth0.jwt.PemUtils.readPrivateKeyFromFile; -import static com.auth0.jwt.PemUtils.readPublicKeyFromFile; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; -import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - @SuppressWarnings("deprecation") public class ECDSAAlgorithmTest { @@ -85,7 +90,6 @@ public void shouldPassECDSA256VerificationWithJOSESignature() throws Exception { Algorithm algorithm = Algorithm.ECDSA256(key); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -100,7 +104,6 @@ public void shouldThrowOnECDSA256VerificationWithDERSignature() throws Exception Algorithm algorithm = Algorithm.ECDSA256(key); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -109,7 +112,6 @@ public void shouldPassECDSA256VerificationWithJOSESignatureWithBothKeys() throws Algorithm algorithm = Algorithm.ECDSA256((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -123,7 +125,6 @@ public void shouldThrowOnECDSA256VerificationWithDERSignatureWithBothKeys() thro Algorithm algorithm = Algorithm.ECDSA256((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -135,7 +136,6 @@ public void shouldPassECDSA256VerificationWithProvidedPublicKey() throws Excepti Algorithm algorithm = Algorithm.ECDSA256(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -150,7 +150,6 @@ public void shouldFailECDSA256VerificationWhenProvidedPublicKeyIsNull() throws E Algorithm algorithm = Algorithm.ECDSA256(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -161,7 +160,6 @@ public void shouldFailECDSA256VerificationWithInvalidPublicKey() throws Exceptio Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_256, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -174,7 +172,6 @@ public void shouldFailECDSA256VerificationWhenUsingPrivateKey() throws Exception Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -191,7 +188,6 @@ public void shouldFailECDSA256VerificationOnInvalidJOSESignatureLength() throws Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_256, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -206,7 +202,6 @@ public void shouldFailECDSA256VerificationOnInvalidJOSESignature() throws Except Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_256, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -222,7 +217,6 @@ public void shouldFailECDSA256VerificationOnInvalidDERSignature() throws Excepti Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_256, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -232,7 +226,6 @@ public void shouldPassECDSA384VerificationWithJOSESignature() throws Exception { Algorithm algorithm = Algorithm.ECDSA384(key); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -247,7 +240,6 @@ public void shouldThrowOnECDSA384VerificationWithDERSignature() throws Exception Algorithm algorithm = Algorithm.ECDSA384(key); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -256,7 +248,6 @@ public void shouldPassECDSA384VerificationWithJOSESignatureWithBothKeys() throws Algorithm algorithm = Algorithm.ECDSA384((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_384, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -270,7 +261,6 @@ public void shouldThrowOnECDSA384VerificationWithDERSignatureWithBothKeys() thro Algorithm algorithm = Algorithm.ECDSA384((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_384, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -282,7 +272,6 @@ public void shouldPassECDSA384VerificationWithProvidedPublicKey() throws Excepti Algorithm algorithm = Algorithm.ECDSA384(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -297,7 +286,6 @@ public void shouldFailECDSA384VerificationWhenProvidedPublicKeyIsNull() throws E Algorithm algorithm = Algorithm.ECDSA384(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -308,7 +296,6 @@ public void shouldFailECDSA384VerificationWithInvalidPublicKey() throws Exceptio Algorithm algorithm = Algorithm.ECDSA384((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_384, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -321,7 +308,6 @@ public void shouldFailECDSA384VerificationWhenUsingPrivateKey() throws Exception Algorithm algorithm = Algorithm.ECDSA384((ECKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_384, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -336,7 +322,6 @@ public void shouldFailECDSA384VerificationOnInvalidJOSESignatureLength() throws Algorithm algorithm = Algorithm.ECDSA384((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_384, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -351,7 +336,6 @@ public void shouldFailECDSA384VerificationOnInvalidJOSESignature() throws Except Algorithm algorithm = Algorithm.ECDSA384((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_384, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -367,7 +351,6 @@ public void shouldFailECDSA384VerificationOnInvalidDERSignature() throws Excepti Algorithm algorithm = Algorithm.ECDSA384((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_384, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -377,7 +360,6 @@ public void shouldPassECDSA512VerificationWithJOSESignature() throws Exception { Algorithm algorithm = Algorithm.ECDSA512(key); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -392,7 +374,6 @@ public void shouldThrowOnECDSA512VerificationWithDERSignature() throws Exception Algorithm algorithm = Algorithm.ECDSA512(key); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -401,7 +382,6 @@ public void shouldPassECDSA512VerificationWithJOSESignatureWithBothKeys() throws Algorithm algorithm = Algorithm.ECDSA512((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -415,7 +395,6 @@ public void shouldThrowECDSA512VerificationWithDERSignatureWithBothKeys() throws Algorithm algorithm = Algorithm.ECDSA512((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -427,7 +406,6 @@ public void shouldPassECDSA512VerificationWithProvidedPublicKey() throws Excepti Algorithm algorithm = Algorithm.ECDSA512(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -442,7 +420,6 @@ public void shouldFailECDSA512VerificationWhenProvidedPublicKeyIsNull() throws E Algorithm algorithm = Algorithm.ECDSA512(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -453,7 +430,6 @@ public void shouldFailECDSA512VerificationWithInvalidPublicKey() throws Exceptio Algorithm algorithm = Algorithm.ECDSA512((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_512, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -466,7 +442,6 @@ public void shouldFailECDSA512VerificationWhenUsingPrivateKey() throws Exception Algorithm algorithm = Algorithm.ECDSA512((ECKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -481,7 +456,6 @@ public void shouldFailECDSA512VerificationOnInvalidJOSESignatureLength() throws Algorithm algorithm = Algorithm.ECDSA512((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_512, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -496,7 +470,6 @@ public void shouldFailECDSA512VerificationOnInvalidJOSESignature() throws Except Algorithm algorithm = Algorithm.ECDSA512((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_512, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -512,7 +485,6 @@ public void shouldFailECDSA512VerificationOnInvalidDERSignature() throws Excepti Algorithm algorithm = Algorithm.ECDSA512((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_512, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -533,7 +505,6 @@ public void shouldFailJOSEToDERConversionOnInvalidJOSESignatureLength() throws E Algorithm algorithm = new ECDSAAlgorithm("ES256", "SHA256withECDSA", 128, provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -552,7 +523,6 @@ public void shouldThrowOnVerifyWhenSignatureAlgorithmDoesNotExists() throws Exce String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g"; JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -571,7 +541,6 @@ public void shouldThrowOnVerifyWhenThePublicKeyIsInvalid() throws Exception { String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g"; JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -590,7 +559,6 @@ public void shouldThrowOnVerifyWhenTheSignatureIsNotPrepared() throws Exception String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g"; JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } //Sign @@ -612,7 +580,6 @@ public void shouldDoECDSA256Signing() throws Exception { assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithmVerify).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithmVerify.verify(decoded, EncodeType.Base64); } @Test @@ -627,7 +594,6 @@ public void shouldDoECDSA256SigningWithBothKeys() throws Exception { assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -647,7 +613,6 @@ public void shouldDoECDSA256SigningWithProvidedPrivateKey() throws Exception { assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -687,7 +652,6 @@ public void shouldDoECDSA384Signing() throws Exception { assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithmVerify).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithmVerify.verify(decoded, EncodeType.Base64); } @Test @@ -702,7 +666,6 @@ public void shouldDoECDSA384SigningWithBothKeys() throws Exception { assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -722,7 +685,6 @@ public void shouldDoECDSA384SigningWithProvidedPrivateKey() throws Exception { assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -762,7 +724,6 @@ public void shouldDoECDSA512Signing() throws Exception { assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithmVerify).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithmVerify.verify(decoded, EncodeType.Base64); } @Test @@ -777,7 +738,6 @@ public void shouldDoECDSA512SigningWithBothKeys() throws Exception { assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @@ -798,7 +758,6 @@ public void shouldDoECDSA512SigningWithProvidedPrivateKey() throws Exception { assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -965,7 +924,6 @@ public void shouldSignAndVerifyWithECDSA256() throws Exception { String token = content256 + "." + signature256; JWT jwt = JWT.require(algorithm256).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm256.verify(decoded, EncodeType.Base64); } } @@ -981,7 +939,6 @@ public void shouldSignAndVerifyWithECDSA384() throws Exception { String token = content384 + "." + signature384; JWT jwt = JWT.require(algorithm384).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm384.verify(decoded, EncodeType.Base64); } } @@ -997,7 +954,6 @@ public void shouldSignAndVerifyWithECDSA512() throws Exception { String token = content512 + "." + signature512; JWT jwt = JWT.require(algorithm512).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm512.verify(decoded, EncodeType.Base64); } } diff --git a/lib/src/test/java/com/auth0/jwt/algorithms/ECDSABouncyCastleProviderTests.java b/lib/src/test/java/com/auth0/jwt/algorithms/ECDSABouncyCastleProviderTests.java index d6a37c7..729ab80 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/ECDSABouncyCastleProviderTests.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/ECDSABouncyCastleProviderTests.java @@ -19,6 +19,24 @@ package com.auth0.jwt.algorithms; +import static com.auth0.jwt.PemUtils.readPrivateKeyFromFile; +import static com.auth0.jwt.PemUtils.readPublicKeyFromFile; +import static com.auth0.jwt.algorithms.ECDSAAlgorithmTest.assertValidDERSignature; +import static com.auth0.jwt.algorithms.ECDSAAlgorithmTest.assertValidJOSESignature; +import static com.auth0.jwt.algorithms.ECDSAAlgorithmTest.createDERSignature; +import static com.auth0.jwt.algorithms.ECDSAAlgorithmTest.createJOSESignature; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.isA; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.auth0.jwt.creators.EncodeType; import com.auth0.jwt.exceptions.AlgorithmMismatchException; import com.auth0.jwt.exceptions.SignatureGenerationException; @@ -26,6 +44,18 @@ import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.ECDSAKeyProvider; import com.auth0.jwt.jwts.JWT; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.Provider; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.Security; +import java.security.SignatureException; +import java.security.interfaces.ECKey; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.ECPublicKey; import org.apache.commons.codec.binary.Base64; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.junit.AfterClass; @@ -34,24 +64,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import java.nio.charset.StandardCharsets; -import java.security.*; -import java.security.interfaces.ECKey; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; - -import static com.auth0.jwt.PemUtils.readPrivateKeyFromFile; -import static com.auth0.jwt.PemUtils.readPublicKeyFromFile; -import static com.auth0.jwt.algorithms.ECDSAAlgorithmTest.*; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; -import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class ECDSABouncyCastleProviderTests { diff --git a/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java b/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java index 043c8f7..d574bef 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java @@ -19,29 +19,30 @@ package com.auth0.jwt.algorithms; -import com.auth0.jwt.creators.EncodeType; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isA; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.auth0.jwt.exceptions.AlgorithmMismatchException; import com.auth0.jwt.exceptions.SignatureGenerationException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.jwts.JWT; -import org.apache.commons.codec.binary.Base64; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import org.apache.commons.codec.binary.Base64; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; public class HMACAlgorithmTest { @@ -53,7 +54,7 @@ public class HMACAlgorithmTest { @Test public void shouldGetStringBytes() throws Exception { String text = "abcdef123456!@#$%^"; - byte[] expectedBytes = text.getBytes("UTF-8"); + byte[] expectedBytes = text.getBytes(StandardCharsets.UTF_8.name()); assertTrue(Arrays.equals(expectedBytes, HMACAlgorithm.getSecretBytes(text))); } @@ -61,11 +62,8 @@ public void shouldGetStringBytes() throws Exception { public void shouldPassHMAC256Verification() throws Exception { String token = "eyJhbGciOiJIUzI1NiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.mZ0m_N1J4PgeqWmi903JuUoDRZDBPB7HwkS4nVyWH1M"; Algorithm algorithmString = Algorithm.HMAC256("secret"); - Algorithm algorithmBytes = Algorithm.HMAC256("secret".getBytes(StandardCharsets.UTF_8)); JWT jwt = JWT.require(algorithmString).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithmString.verify(decoded, EncodeType.Base64); - algorithmBytes.verify(decoded, EncodeType.Base64); } @Test @@ -76,7 +74,6 @@ public void shouldFailHMAC256VerificationWithInvalidSecretString() throws Except Algorithm algorithm = Algorithm.HMAC256("not_real_secret"); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -87,18 +84,14 @@ public void shouldFailHMAC256VerificationWithInvalidSecretBytes() throws Excepti Algorithm algorithm = Algorithm.HMAC256("not_real_secret".getBytes(StandardCharsets.UTF_8)); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test public void shouldPassHMAC384Verification() throws Exception { String token = "eyJhbGciOiJIUzM4NCIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.uztpK_wUMYJhrRv8SV-1LU4aPnwl-EM1q-wJnqgyb5DHoDteP6lN_gE1xnZJH5vw"; Algorithm algorithmString = Algorithm.HMAC384("secret"); - Algorithm algorithmBytes = Algorithm.HMAC384("secret".getBytes(StandardCharsets.UTF_8)); JWT jwt = JWT.require(algorithmString).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithmString.verify(decoded, EncodeType.Base64); - algorithmBytes.verify(decoded, EncodeType.Base64); } @Test @@ -109,7 +102,6 @@ public void shouldFailHMAC384VerificationWithInvalidSecretString() throws Except Algorithm algorithm = Algorithm.HMAC384("not_real_secret"); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -120,18 +112,14 @@ public void shouldFailHMAC384VerificationWithInvalidSecretBytes() throws Excepti Algorithm algorithm = Algorithm.HMAC384("not_real_secret".getBytes(StandardCharsets.UTF_8)); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test public void shouldPassHMAC512Verification() throws Exception { String token = "eyJhbGciOiJIUzUxMiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.VUo2Z9SWDV-XcOc_Hr6Lff3vl7L9e5Vb8ThXpmGDFjHxe3Dr1ZBmUChYF-xVA7cAdX1P_D4ZCUcsv3IefpVaJw"; Algorithm algorithmString = Algorithm.HMAC512("secret"); - Algorithm algorithmBytes = Algorithm.HMAC512("secret".getBytes(StandardCharsets.UTF_8)); JWT jwt = JWT.require(algorithmString).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithmString.verify(decoded, EncodeType.Base64); - algorithmBytes.verify(decoded, EncodeType.Base64); } @Test @@ -142,7 +130,6 @@ public void shouldFailHMAC512VerificationWithInvalidSecretString() throws Except Algorithm algorithm = Algorithm.HMAC512("not_real_secret"); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -153,7 +140,6 @@ public void shouldFailHMAC512VerificationWithInvalidSecretBytes() throws Excepti Algorithm algorithm = Algorithm.HMAC512("not_real_secret".getBytes(StandardCharsets.UTF_8)); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @@ -170,7 +156,6 @@ public void shouldThrowOnVerifyWhenTheSecretIsInvalid() throws Exception { String token = "eyJhbGciOiJIUzI1NiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.mZ0m_N1J4PgeqWmi903JuUoDRZDBPB7HwkS4nVyWH1M"; JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } // Sign @@ -195,7 +180,6 @@ public void shouldDoHMAC256SigningWithBytes() throws Exception { assertThat(jwtSignature, is(expectedSignature)); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -213,7 +197,6 @@ public void shouldDoHMAC384SigningWithBytes() throws Exception { assertThat(jwtSignature, is(expectedSignature)); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -231,7 +214,6 @@ public void shouldDoHMAC512SigningWithBytes() throws Exception { assertThat(jwtSignature, is(expectedSignature)); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -249,7 +231,6 @@ public void shouldDoHMAC256SigningWithString() throws Exception { assertThat(jwtSignature, is(expectedSignature)); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -267,7 +248,6 @@ public void shouldDoHMAC384SigningWithString() throws Exception { assertThat(jwtSignature, is(expectedSignature)); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -285,7 +265,6 @@ public void shouldDoHMAC512SigningWithString() throws Exception { assertThat(jwtSignature, is(expectedSignature)); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test diff --git a/lib/src/test/java/com/auth0/jwt/algorithms/RSAAlgorithmTest.java b/lib/src/test/java/com/auth0/jwt/algorithms/RSAAlgorithmTest.java index 869074a..bc77a77 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/RSAAlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/RSAAlgorithmTest.java @@ -19,33 +19,38 @@ package com.auth0.jwt.algorithms; -import com.auth0.jwt.creators.EncodeType; +import static com.auth0.jwt.PemUtils.readPrivateKeyFromFile; +import static com.auth0.jwt.PemUtils.readPublicKeyFromFile; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isA; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.auth0.jwt.exceptions.AlgorithmMismatchException; import com.auth0.jwt.exceptions.SignatureGenerationException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.RSAKeyProvider; import com.auth0.jwt.jwts.JWT; -import org.apache.commons.codec.binary.Base64; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - import java.nio.charset.StandardCharsets; -import java.security.*; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SignatureException; import java.security.interfaces.RSAKey; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; - -import static com.auth0.jwt.PemUtils.readPrivateKeyFromFile; -import static com.auth0.jwt.PemUtils.readPublicKeyFromFile; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; -import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import org.apache.commons.codec.binary.Base64; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; @SuppressWarnings("deprecation") public class RSAAlgorithmTest { @@ -65,7 +70,6 @@ public void shouldPassRSA256Verification() throws Exception { Algorithm algorithm = Algorithm.RSA256((RSAKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -74,7 +78,6 @@ public void shouldPassRSA256VerificationWithBothKeys() throws Exception { Algorithm algorithm = Algorithm.RSA256((RSAPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA"), (RSAPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -86,7 +89,6 @@ public void shouldPassRSA256VerificationWithProvidedPublicKey() throws Exception Algorithm algorithm = Algorithm.RSA256(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -101,7 +103,6 @@ public void shouldFailRSA256VerificationWhenProvidedPublicKeyIsNull() throws Exc Algorithm algorithm = Algorithm.RSA256(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -112,7 +113,6 @@ public void shouldFailRSA256VerificationWithInvalidPublicKey() throws Exception Algorithm algorithm = Algorithm.RSA256((RSAKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE, "RSA")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -125,7 +125,6 @@ public void shouldFailRSA256VerificationWhenUsingPrivateKey() throws Exception { Algorithm algorithm = Algorithm.RSA256((RSAKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -134,7 +133,6 @@ public void shouldPassRSA384Verification() throws Exception { Algorithm algorithm = Algorithm.RSA384((RSAKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -143,7 +141,6 @@ public void shouldPassRSA384VerificationWithBothKeys() throws Exception { Algorithm algorithm = Algorithm.RSA384((RSAPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA"), (RSAPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -155,7 +152,6 @@ public void shouldPassRSA384VerificationWithProvidedPublicKey() throws Exception Algorithm algorithm = Algorithm.RSA384(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -170,7 +166,6 @@ public void shouldFailRSA384VerificationWhenProvidedPublicKeyIsNull() throws Exc Algorithm algorithm = Algorithm.RSA384(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -181,7 +176,6 @@ public void shouldFailRSA384VerificationWithInvalidPublicKey() throws Exception Algorithm algorithm = Algorithm.RSA384((RSAKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE, "RSA")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -194,7 +188,6 @@ public void shouldFailRSA384VerificationWhenUsingPrivateKey() throws Exception { Algorithm algorithm = Algorithm.RSA384((RSAKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -203,7 +196,6 @@ public void shouldPassRSA512Verification() throws Exception { Algorithm algorithm = Algorithm.RSA512((RSAKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -212,7 +204,6 @@ public void shouldPassRSA512VerificationWithBothKeys() throws Exception { Algorithm algorithm = Algorithm.RSA512((RSAPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA"), (RSAPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -224,7 +215,6 @@ public void shouldPassRSA512VerificationWithProvidedPublicKey() throws Exception Algorithm algorithm = Algorithm.RSA512(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -239,7 +229,6 @@ public void shouldFailRSA512VerificationWhenProvidedPublicKeyIsNull() throws Exc Algorithm algorithm = Algorithm.RSA512(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -250,7 +239,6 @@ public void shouldFailRSA512VerificationWithInvalidPublicKey() throws Exception Algorithm algorithm = Algorithm.RSA512((RSAKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE, "RSA")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -263,7 +251,6 @@ public void shouldFailRSA512VerificationWhenUsingPrivateKey() throws Exception { Algorithm algorithm = Algorithm.RSA512((RSAKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -282,7 +269,6 @@ public void shouldThrowWhenMacAlgorithmDoesNotExists() throws Exception { String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.dxXF3MdsyW-AuvwJpaQtrZ33fAde9xWxpLIg9cO2tMLH2GSRNuLAe61KsJusZhqZB9Iy7DvflcmRz-9OZndm6cj_ThGeJH2LLc90K83UEvvRPo8l85RrQb8PcanxCgIs2RcZOLygERizB3pr5icGkzR7R2y6zgNCjKJ5_NJ6EiZsGN6_nc2PRK_DbyY-Wn0QDxIxKoA5YgQJ9qafe7IN980pXvQv2Z62c3XR8dYuaXBqhthBj-AbaFHEpZapN-V-TmuLNzR2MCB6Xr7BYMuCaqWf_XU8og4XNe8f_8w9Wv5vvgqMM1KhqVpG5VdMJv4o_L4NoCROHhtUQSLRh2M9cA"; JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -301,7 +287,6 @@ public void shouldThrowWhenThePublicKeyIsInvalid() throws Exception { String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.dxXF3MdsyW-AuvwJpaQtrZ33fAde9xWxpLIg9cO2tMLH2GSRNuLAe61KsJusZhqZB9Iy7DvflcmRz-9OZndm6cj_ThGeJH2LLc90K83UEvvRPo8l85RrQb8PcanxCgIs2RcZOLygERizB3pr5icGkzR7R2y6zgNCjKJ5_NJ6EiZsGN6_nc2PRK_DbyY-Wn0QDxIxKoA5YgQJ9qafe7IN980pXvQv2Z62c3XR8dYuaXBqhthBj-AbaFHEpZapN-V-TmuLNzR2MCB6Xr7BYMuCaqWf_XU8og4XNe8f_8w9Wv5vvgqMM1KhqVpG5VdMJv4o_L4NoCROHhtUQSLRh2M9cA"; JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -320,7 +305,6 @@ public void shouldThrowWhenTheSignatureIsNotPrepared() throws Exception { String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.dxXF3MdsyW-AuvwJpaQtrZ33fAde9xWxpLIg9cO2tMLH2GSRNuLAe61KsJusZhqZB9Iy7DvflcmRz-9OZndm6cj_ThGeJH2LLc90K83UEvvRPo8l85RrQb8PcanxCgIs2RcZOLygERizB3pr5icGkzR7R2y6zgNCjKJ5_NJ6EiZsGN6_nc2PRK_DbyY-Wn0QDxIxKoA5YgQJ9qafe7IN980pXvQv2Z62c3XR8dYuaXBqhthBj-AbaFHEpZapN-V-TmuLNzR2MCB6Xr7BYMuCaqWf_XU8og4XNe8f_8w9Wv5vvgqMM1KhqVpG5VdMJv4o_L4NoCROHhtUQSLRh2M9cA"; JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @@ -346,7 +330,6 @@ public void shouldDoRSA256Signing() throws Exception { assertThat(jwtSignature, is(expectedSignature)); JWT jwt = JWT.require(algorithmVerify).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithmVerify.verify(decoded, EncodeType.Base64); } @Test @@ -364,7 +347,6 @@ public void shouldDoRSA256SigningWithBothKeys() throws Exception { assertThat(jwtSignature, is(expectedSignature)); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -384,7 +366,6 @@ public void shouldDoRSA256SigningWithProvidedPrivateKey() throws Exception { assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -427,7 +408,6 @@ public void shouldDoRSA384Signing() throws Exception { assertThat(jwtSignature, is(expectedSignature)); JWT jwt = JWT.require(algorithmVerify).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithmVerify.verify(decoded, EncodeType.Base64); } @Test @@ -445,7 +425,6 @@ public void shouldDoRSA384SigningWithBothKeys() throws Exception { assertThat(jwtSignature, is(expectedSignature)); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -465,7 +444,6 @@ public void shouldDoRSA384SigningWithProvidedPrivateKey() throws Exception { assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -508,7 +486,6 @@ public void shouldDoRSA512Signing() throws Exception { assertThat(jwtSignature, is(expectedSignature)); JWT jwt = JWT.require(algorithmVerify).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithmVerify.verify(decoded, EncodeType.Base64); } @Test @@ -526,7 +503,6 @@ public void shouldDoRSA512SigningWithBothKeys() throws Exception { assertThat(jwtSignature, is(expectedSignature)); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test @@ -546,7 +522,6 @@ public void shouldDoRSA512SigningWithProvidedPrivateKey() throws Exception { assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); - algorithm.verify(decoded, EncodeType.Base64); } @Test diff --git a/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java b/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java index b9e7087..0b02a37 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java @@ -21,24 +21,25 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static java.util.Arrays.asList; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; -import com.auth0.jwt.jwts.JWT; import com.auth0.jwt.jwts.AccessJWT; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertTrue; +import com.auth0.jwt.jwts.JWT; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.text.SimpleDateFormat; -import java.util.*; - public class AccessJwtCreatorTest { @Rule @@ -343,9 +344,9 @@ public void testAccessJwtCreatorExpTimeHasPassed() throws Exception { } private static void verifyClaims(Map claims, Date exp) { - assertTrue(claims.get(PublicClaims.ISSUER).asList(String.class).get(0).equals("issuer")); - assertTrue(claims.get(PublicClaims.SUBJECT).asList(String.class).get(0).equals("subject")); - assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals("audience")); - assertTrue(claims.get(PublicClaims.EXPIRES_AT).asDate().toString().equals(exp.toString())); + assertTrue(claims.get(Claims.ISSUER).asString().equals("issuer")); + assertTrue(claims.get(Claims.SUBJECT).asString().equals("subject")); + assertTrue(claims.get(Claims.AUDIENCE).asString().equals("audience")); + assertTrue(claims.get(Claims.EXPIRES_AT).asDate().toString().equals(exp.toString())); } } \ No newline at end of file diff --git a/lib/src/test/java/com/auth0/jwt/creators/ExtendedJwtCreatorTest.java b/lib/src/test/java/com/auth0/jwt/creators/ExtendedJwtCreatorTest.java index 445f0b0..316f9fe 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ExtendedJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ExtendedJwtCreatorTest.java @@ -19,29 +19,28 @@ package com.auth0.jwt.creators; -import static com.auth0.jwt.creators.GoogleJwtCreatorTest.*; import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static com.auth0.jwt.creators.GoogleJwtCreatorTest.verifyClaims; +import static com.auth0.jwt.impl.Claims.EMAIL; +import static com.auth0.jwt.impl.Claims.NAME; +import static com.auth0.jwt.impl.Claims.PICTURE; +import static java.util.Arrays.asList; + import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.impl.PublicClaims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.GoogleVerification; -import com.auth0.jwt.interfaces.Verification; -import com.auth0.jwt.jwts.AccessJWT; import com.auth0.jwt.jwts.ExtendedJWT; import com.auth0.jwt.jwts.JWT; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertTrue; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; public class ExtendedJwtCreatorTest { diff --git a/lib/src/test/java/com/auth0/jwt/creators/FbJwtCreatorTest.java b/lib/src/test/java/com/auth0/jwt/creators/FbJwtCreatorTest.java index b6cb74e..2beb2e5 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/FbJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/FbJwtCreatorTest.java @@ -21,24 +21,24 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.creators.FbJwtCreator; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; import com.auth0.jwt.jwts.FbJWT; import com.auth0.jwt.jwts.JWT; -import static org.junit.Assert.assertTrue; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.text.SimpleDateFormat; -import java.util.*; - public class FbJwtCreatorTest { @Rule @@ -131,7 +131,7 @@ public void testFbJwtCreatorInvalidAppId() throws Exception { @Test public void testFbJwtCreatorUserIdNotProvided() throws Exception { thrown.expect(Exception.class); - thrown.expectMessage("Standard claim: UserId has not been set"); + thrown.expectMessage("Standard claim: userId has not been set"); Algorithm algorithm = Algorithm.HMAC256("secret"); String token = FbJwtCreator.build() .withExp(exp) @@ -351,6 +351,6 @@ public void testFbJwtCreatorExpTimeHasPassed() throws Exception { private static void verifyClaims(Map claims) { assertTrue(claims.get(USER_ID).asString().equals(USER_ID)); assertTrue(claims.get(APP_ID).asString().equals(APP_ID)); - assertTrue(claims.get(PublicClaims.EXPIRES_AT).asDate().toString().equals(exp.toString())); + assertTrue(claims.get(Claims.EXPIRES_AT).asDate().toString().equals(exp.toString())); } } \ No newline at end of file diff --git a/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java b/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java index ceba3d9..983a204 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java @@ -21,26 +21,25 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static java.util.Arrays.asList; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.creators.GoogleJwtCreator; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.GoogleVerification; import com.auth0.jwt.jwts.GoogleJWT; import com.auth0.jwt.jwts.JWT; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertTrue; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; - -import java.text.SimpleDateFormat; -import java.util.*; - public class GoogleJwtCreatorTest { @Rule @@ -118,7 +117,7 @@ public void testGoogleJwtCreatorBase32Encoding() throws Exception { @Test public void testGoogleJwtCreatorWhenCertainRequiredClaimIsntProvided() throws Exception { thrown.expect(Exception.class); - thrown.expectMessage("Standard claim: Picture has not been set"); + thrown.expectMessage("Standard claim: picture has not been set"); Algorithm algorithm = Algorithm.HMAC256("secret"); String token = GoogleJwtCreator.build() @@ -538,7 +537,7 @@ public void testGoogleJwtCreatorTokenCantBeUsedBefore() throws Exception { @Test public void testCreateVerifierForExtended() throws Exception{ thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("you shouldn't be calling this method"); + thrown.expectMessage("this method has not been implemented"); GoogleVerification verification = GoogleJWT.require(Algorithm.HMAC256("secret")); verification.createVerifierForExtended(null, null, null, null, null, 1L, 1L, 1L); } @@ -546,10 +545,10 @@ public void testCreateVerifierForExtended() throws Exception{ protected static void verifyClaims(Map claims, Date exp) { assertTrue(claims.get(PICTURE).asString().equals(PICTURE)); assertTrue(claims.get(EMAIL).asString().equals(EMAIL)); - assertTrue(claims.get(PublicClaims.ISSUER).asList(String.class).get(0).equals("issuer")); - assertTrue(claims.get(PublicClaims.SUBJECT).asList(String.class).get(0).equals("subject")); - assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals("audience")); - assertTrue(claims.get(PublicClaims.EXPIRES_AT).asDate().toString().equals(exp.toString())); + assertTrue(claims.get(Claims.ISSUER).asString().equals("issuer")); + assertTrue(claims.get(Claims.SUBJECT).asString().equals("subject")); + assertTrue(claims.get(Claims.AUDIENCE).asString().equals("audience")); + assertTrue(claims.get(Claims.EXPIRES_AT).asDate().toString().equals(exp.toString())); assertTrue(claims.get(NAME).asString().equals(NAME)); } } \ No newline at end of file diff --git a/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java b/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java index bb7a332..c847b54 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java @@ -19,24 +19,26 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.TimeUtil; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static java.util.Arrays.asList; +import static org.junit.Assert.assertTrue; + +import com.auth0.jwt.TimeUtil; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.exceptions.RequiredClaimException; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; import com.auth0.jwt.jwts.ImplicitJWT; import com.auth0.jwt.jwts.JWT; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertTrue; +import java.util.Date; +import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.util.*; - public class ImplicitJwtCreatorTest { @Rule @@ -130,8 +132,8 @@ public void testImplicitJwtCreatorInvalidAudience() throws Exception { @Test public void testImplicitJwtCreatorIssuerNotProvided() throws Exception { - thrown.expect(Exception.class); - thrown.expectMessage("Standard claim: Issuer has not been set"); + thrown.expect(RequiredClaimException.class); + thrown.expectMessage("Standard claim: iss has not been set"); Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ImplicitJwtCreator.build() .withSubject("subject") @@ -318,8 +320,8 @@ public void testImplicitJwtCreatorNonStandardClaimDateValue() throws Exception { } private static void verifyClaims(Map claims) { - assertTrue(claims.get(PublicClaims.ISSUER).asList(String.class).get(0).equals("issuer")); - assertTrue(claims.get(PublicClaims.SUBJECT).asList(String.class).get(0).equals("subject")); - assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals("audience")); + assertTrue(claims.get(Claims.ISSUER).asString().equals("issuer")); + assertTrue(claims.get(Claims.SUBJECT).asString().equals("subject")); + assertTrue(claims.get(Claims.AUDIENCE).asString().equals("audience")); } } \ No newline at end of file diff --git a/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java b/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java index 7404e67..032aab4 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java @@ -21,11 +21,14 @@ import com.auth0.jwt.JsonMatcher; import com.auth0.jwt.PemUtils; -import com.auth0.jwt.TokenUtils; +import com.auth0.jwt.utils.TokenUtils; import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.creators.JWTCreator; +import com.auth0.jwt.exceptions.SignatureVerificationException; +import com.auth0.jwt.impl.Claims; +import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.ECDSAKeyProvider; import com.auth0.jwt.interfaces.RSAKeyProvider; +import com.auth0.jwt.jwts.JWT; import org.apache.commons.codec.binary.Base64; import org.junit.Rule; import org.junit.Test; @@ -44,12 +47,21 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; + public class JWTCreatorTest { - private static final String PRIVATE_KEY_FILE_RSA = "src/test/resources/rsa-private.pem"; + private static final String PRIVATE_KEY_FILE_RSA = "src/test/resources/rsa-private-base16-64.pem"; + private static final String PUBLIC_KEY_FILE_RSA = "src/test/resources/rsa-public-base16-64.pem"; + private static final String PRIVATE_KEY_FILE = "src/test/resources/rsa-private.pem"; + private static final String PUBLIC_KEY_FILE = "src/test/resources/rsa-public.pem"; + private static final String PUBLIC_KEY_FILE_INVALID = "src/test/resources/rsa-public_invalid.pem"; + private static final String PRIVATE_KEY_FILE_PKCS8 = "./src/test/resources/example_key_pcks8.pem"; + private static final String PEM_FILE = "./src/main/java/com/auth0/jwt/algorithms/jwks.pem"; + private static final String JWKS_FILE = "./jwksRSA.json"; + private static final String JWKS_FILE_ANOTHER_EXAMPLE = "./src/test/resources/example_jwk.json"; + private static final String INVALID_JWKS_FILE = "./jwksRSA.doc"; private static final String PRIVATE_KEY_FILE_EC_256 = "src/test/resources/ec256-key-private.pem"; - @Rule public ExpectedException exception = ExpectedException.none(); @@ -92,7 +104,7 @@ public void shouldAddKeyId() throws Exception { public void shouldAddKeyIdIfAvailableFromRSAAlgorithms() throws Exception { RSAPrivateKey privateKey = (RSAPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_RSA, "RSA"); RSAKeyProvider provider = mock(RSAKeyProvider.class); - when(provider.getPrivateKeyId()).thenReturn("my-key-id"); + when(provider.getPrivateKeyId()).thenReturn("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI"); when(provider.getPrivateKey()).thenReturn(privateKey); String signed = JWTCreator.init() @@ -101,14 +113,209 @@ public void shouldAddKeyIdIfAvailableFromRSAAlgorithms() throws Exception { assertThat(signed, is(notNullValue())); String[] parts = signed.split("\\."); String headerJson = new String(Base64.decodeBase64(parts[0]), StandardCharsets.UTF_8); - assertThat(headerJson, JsonMatcher.hasEntry("kid", "my-key-id")); + assertThat(headerJson, JsonMatcher.hasEntry("kid", "8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI")); + } + + @Test + public void shouldAddKeyIdIfAvailableFromRSAAlgorithmsForBase16() throws Exception { + RSAPrivateKey privateKey = (RSAPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_RSA, "RSA"); + RSAKeyProvider provider = mock(RSAKeyProvider.class); + when(provider.getPrivateKeyId()).thenReturn("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI"); + when(provider.getPrivateKey()).thenReturn(privateKey); + Algorithm algorithm = Algorithm.RSA256(provider); + + String signed = JWTCreator.init() + .withKeyId("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI") + .withIssuer("auth0") + .sign(algorithm, EncodeType.Base16); + + JWT jwt = JWT.require(Algorithm.RSA256(provider)).withIssuer("auth0").build(); + DecodedJWT decoded = jwt.decode16BytesWithX509(signed, JWKS_FILE, PEM_FILE); + } + + @Test + public void shouldAddKeyIdIfAvailableFromRSAAlgorithmsForBase16NotAProperJwksFile() throws Exception { + exception.expect(IllegalArgumentException.class); + exception.expectMessage("Not a proper jwks file"); + RSAPrivateKey privateKey = (RSAPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_RSA, "RSA"); + RSAKeyProvider provider = mock(RSAKeyProvider.class); + when(provider.getPrivateKeyId()).thenReturn("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI"); + when(provider.getPrivateKey()).thenReturn(privateKey); + Algorithm algorithm = Algorithm.RSA256(provider); + + String signed = JWTCreator.init() + .withKeyId("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI") + .withIssuer("auth0") + .sign(algorithm, EncodeType.Base16); + + JWT jwt = JWT.require(Algorithm.RSA256(provider)).withIssuer("auth0").build(); + DecodedJWT decoded = jwt.decode16BytesWithX509(signed, INVALID_JWKS_FILE, PEM_FILE); + } + + @Test + public void shouldAddKeyIdIfAvailableFromRSAAlgorithmsForBase16UsingRolandKeys() throws Exception { + RSAPrivateKey privateKey = (RSAPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_PKCS8, "RSA"); + RSAKeyProvider provider = mock(RSAKeyProvider.class); + when(provider.getPrivateKeyId()).thenReturn("dnVrY0tQcUZCUWh2T25EaVk3Q0ZLRW9VdnRxU0tiUHNiVkVGS3k1V1Jidw"); + when(provider.getPrivateKey()).thenReturn(privateKey); + Algorithm algorithm = Algorithm.RSA256(provider); + + String signed = JWTCreator.init() + .withKeyId("dnVrY0tQcUZCUWh2T25EaVk3Q0ZLRW9VdnRxU0tiUHNiVkVGS3k1V1Jidw") + .withIssuer("auth0") + .sign(algorithm, EncodeType.Base16); + + JWT jwt = JWT.require(Algorithm.RSA256(provider)).withIssuer("auth0").build(); + DecodedJWT decoded = jwt.decode16BytesWithX509(signed, JWKS_FILE_ANOTHER_EXAMPLE, PUBLIC_KEY_FILE_RSA); + } + + @Test + public void shouldAddKeyIdIfAvailableFromRSAAlgorithmsForBase16UsingAuth0Keys() throws Exception { + RSAPrivateKey privateKey = (RSAPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA"); + RSAKeyProvider provider = mock(RSAKeyProvider.class); + when(provider.getPrivateKeyId()).thenReturn("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI"); + when(provider.getPrivateKey()).thenReturn(privateKey); + Algorithm algorithm = Algorithm.RSA256(provider); + + String signed = JWTCreator.init() + .withKeyId("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI") + .withIssuer("auth0") + .sign(algorithm, EncodeType.Base16); + + JWT jwt = JWT.require(Algorithm.RSA256(provider)).withIssuer("auth0").build(); + DecodedJWT decoded = jwt.decode16BytesWithX509(signed, JWKS_FILE, PUBLIC_KEY_FILE); + } + + @Test + public void shouldAddKeyIdIfAvailableFromRSAAlgorithmsForBase16UsingAuth0KeysInvalidSignatureVerification() throws Exception { + exception.expect(SignatureVerificationException.class); + exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA256withRSA"); + RSAPrivateKey privateKey = (RSAPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA"); + RSAKeyProvider provider = mock(RSAKeyProvider.class); + when(provider.getPrivateKeyId()).thenReturn("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI"); + when(provider.getPrivateKey()).thenReturn(privateKey); + Algorithm algorithm = Algorithm.RSA256(provider); + + String signed = JWTCreator.init() + .withKeyId("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI") + .withIssuer("auth0") + .sign(algorithm, EncodeType.Base16); + + JWT jwt = JWT.require(Algorithm.RSA256(provider)).withIssuer("auth0").build(); + DecodedJWT decoded = jwt.decode16BytesWithX509(signed, JWKS_FILE, PUBLIC_KEY_FILE_INVALID); + } + + @Test + public void shouldAddKeyIdIfAvailableFromRSAAlgorithmsForBase32() throws Exception { + RSAPrivateKey privateKey = (RSAPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_RSA, "RSA"); + RSAKeyProvider provider = mock(RSAKeyProvider.class); + when(provider.getPrivateKeyId()).thenReturn("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI"); + when(provider.getPrivateKey()).thenReturn(privateKey); + Algorithm algorithm = Algorithm.RSA256(provider); + + String signed = JWTCreator.init() + .withKeyId("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI") + .withIssuer("auth0") + .sign(algorithm, EncodeType.Base32); + + JWT jwt = JWT.require(Algorithm.RSA256(provider)).withIssuer("auth0").build(); + DecodedJWT decoded = jwt.decode32BytesWithX509(signed, JWKS_FILE, PEM_FILE); + } + + @Test + public void shouldAddKeyIdIfAvailableFromRSAAlgorithmsForBase32UsingRolandKeys() throws Exception { + RSAPrivateKey privateKey = (RSAPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_PKCS8, "RSA"); + RSAKeyProvider provider = mock(RSAKeyProvider.class); + when(provider.getPrivateKeyId()).thenReturn("dnVrY0tQcUZCUWh2T25EaVk3Q0ZLRW9VdnRxU0tiUHNiVkVGS3k1V1Jidw"); + when(provider.getPrivateKey()).thenReturn(privateKey); + Algorithm algorithm = Algorithm.RSA256(provider); + + String signed = JWTCreator.init() + .withKeyId("dnVrY0tQcUZCUWh2T25EaVk3Q0ZLRW9VdnRxU0tiUHNiVkVGS3k1V1Jidw") + .withIssuer("auth0") + .sign(algorithm, EncodeType.Base32); + + JWT jwt = JWT.require(Algorithm.RSA256(provider)).withIssuer("auth0").build(); + DecodedJWT decoded = jwt.decode32BytesWithX509(signed, JWKS_FILE_ANOTHER_EXAMPLE, PUBLIC_KEY_FILE_RSA); + } + + @Test + public void shouldAddKeyIdIfAvailableFromRSAAlgorithmsForBase32UsingAuth0Keys() throws Exception { + RSAPrivateKey privateKey = (RSAPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA"); + RSAKeyProvider provider = mock(RSAKeyProvider.class); + when(provider.getPrivateKeyId()).thenReturn("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI"); + when(provider.getPrivateKey()).thenReturn(privateKey); + Algorithm algorithm = Algorithm.RSA256(provider); + + String signed = JWTCreator.init() + .withKeyId("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI") + .withIssuer("auth0") + .sign(algorithm, EncodeType.Base32); + + JWT jwt = JWT.require(Algorithm.RSA256(provider)).withIssuer("auth0").build(); + DecodedJWT decoded = jwt.decode32BytesWithX509(signed, JWKS_FILE, PUBLIC_KEY_FILE); + } + @Test + public void shouldAddKeyIdIfAvailableFromRSAAlgorithmsForBase64() throws Exception { + RSAPrivateKey privateKey = (RSAPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_RSA, "RSA"); + RSAKeyProvider provider = mock(RSAKeyProvider.class); + when(provider.getPrivateKeyId()).thenReturn("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI"); + when(provider.getPrivateKey()).thenReturn(privateKey); + Algorithm algorithm = Algorithm.RSA256(provider); + + String signed = + JWTCreator.init() + .withKeyId("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI") + .withIssuer("https://agaton-sax.com/") + .withNonStandardClaim("foo","bar") + .withNonStandardClaim("kit", "kat") + .sign(algorithm, EncodeType.Base64); + + JWT jwt = JWT.require(Algorithm.RSA256(provider)).withIssuer("https://agaton-sax.com/") + .withNonStandardClaim("foo","bar") + .withNonStandardClaim("kit", "kat").build(); + DecodedJWT decoded = jwt.decodeWithX509(signed, JWKS_FILE, PEM_FILE); + } + + @Test + public void shouldAddKeyIdIfAvailableFromRSAAlgorithmsForBase64UsingRolandKeys() throws Exception { + RSAPrivateKey privateKey = (RSAPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_PKCS8, "RSA"); + RSAKeyProvider provider = mock(RSAKeyProvider.class); + when(provider.getPrivateKeyId()).thenReturn("dnVrY0tQcUZCUWh2T25EaVk3Q0ZLRW9VdnRxU0tiUHNiVkVGS3k1V1Jidw"); + when(provider.getPrivateKey()).thenReturn(privateKey); + Algorithm algorithm = Algorithm.RSA256(provider); + + String signed = JWTCreator.init() + .withKeyId("dnVrY0tQcUZCUWh2T25EaVk3Q0ZLRW9VdnRxU0tiUHNiVkVGS3k1V1Jidw") + .withIssuer("auth0") + .sign(algorithm, EncodeType.Base64); + + JWT jwt = JWT.require(Algorithm.RSA256(provider)).withIssuer("auth0").build(); + DecodedJWT decoded = jwt.decodeWithX509(signed, JWKS_FILE_ANOTHER_EXAMPLE, PUBLIC_KEY_FILE_RSA); + } + + @Test + public void shouldAddKeyIdIfAvailableFromRSAAlgorithmsForBase64UsingAuth0Keys() throws Exception { + RSAPrivateKey privateKey = (RSAPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA"); + RSAKeyProvider provider = mock(RSAKeyProvider.class); + when(provider.getPrivateKeyId()).thenReturn("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI"); + when(provider.getPrivateKey()).thenReturn(privateKey); + Algorithm algorithm = Algorithm.RSA256(provider); + + String signed = JWTCreator.init() + .withKeyId("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI") + .withIssuer("auth0") + .sign(algorithm, EncodeType.Base64); + + JWT jwt = JWT.require(Algorithm.RSA256(provider)).withIssuer("auth0").build(); + DecodedJWT decoded = jwt.decodeWithX509(signed, JWKS_FILE, PUBLIC_KEY_FILE); } @Test public void shouldNotOverwriteKeyIdIfAddedFromRSAAlgorithms() throws Exception { RSAPrivateKey privateKey = (RSAPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_RSA, "RSA"); RSAKeyProvider provider = mock(RSAKeyProvider.class); - when(provider.getPrivateKeyId()).thenReturn("my-key-id"); + when(provider.getPrivateKeyId()).thenReturn("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI"); when(provider.getPrivateKey()).thenReturn(privateKey); String signed = JWTCreator.init() @@ -118,14 +325,14 @@ public void shouldNotOverwriteKeyIdIfAddedFromRSAAlgorithms() throws Exception { assertThat(signed, is(notNullValue())); String[] parts = signed.split("\\."); String headerJson = new String(Base64.decodeBase64(parts[0]), StandardCharsets.UTF_8); - assertThat(headerJson, JsonMatcher.hasEntry("kid", "my-key-id")); + assertThat(headerJson, JsonMatcher.hasEntry("kid", "8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI")); } @Test public void shouldAddKeyIdIfAvailableFromECDSAAlgorithms() throws Exception { ECPrivateKey privateKey = (ECPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_EC_256, "EC"); ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class); - when(provider.getPrivateKeyId()).thenReturn("my-key-id"); + when(provider.getPrivateKeyId()).thenReturn("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI"); when(provider.getPrivateKey()).thenReturn(privateKey); String signed = JWTCreator.init() @@ -134,14 +341,14 @@ public void shouldAddKeyIdIfAvailableFromECDSAAlgorithms() throws Exception { assertThat(signed, is(notNullValue())); String[] parts = signed.split("\\."); String headerJson = new String(Base64.decodeBase64(parts[0]), StandardCharsets.UTF_8); - assertThat(headerJson, JsonMatcher.hasEntry("kid", "my-key-id")); + assertThat(headerJson, JsonMatcher.hasEntry("kid", "8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI")); } @Test public void shouldNotOverwriteKeyIdIfAddedFromECDSAAlgorithms() throws Exception { ECPrivateKey privateKey = (ECPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_EC_256, "EC"); ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class); - when(provider.getPrivateKeyId()).thenReturn("my-key-id"); + when(provider.getPrivateKeyId()).thenReturn("8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI"); when(provider.getPrivateKey()).thenReturn(privateKey); String signed = JWTCreator.init() @@ -151,7 +358,7 @@ public void shouldNotOverwriteKeyIdIfAddedFromECDSAAlgorithms() throws Exception assertThat(signed, is(notNullValue())); String[] parts = signed.split("\\."); String headerJson = new String(Base64.decodeBase64(parts[0]), StandardCharsets.UTF_8); - assertThat(headerJson, JsonMatcher.hasEntry("kid", "my-key-id")); + assertThat(headerJson, JsonMatcher.hasEntry("kid", "8RGoVdVjD8fItyR3FFo0hVNaZYtPGwoP6xKi9e_V7bI")); } @Test @@ -161,7 +368,7 @@ public void shouldAddIssuer() throws Exception { .sign(Algorithm.HMAC256("secret")); assertThat(signed, is(notNullValue())); - assertThat(TokenUtils.splitToken(signed)[1], is("eyJpc3MiOlsiYXV0aDAiXX0")); + assertThat(TokenUtils.splitToken(signed)[1], is("eyJpc3MiOiJhdXRoMCJ9")); } @Test @@ -171,7 +378,7 @@ public void shouldAddSubject() throws Exception { .sign(Algorithm.HMAC256("secret")); assertThat(signed, is(notNullValue())); - assertThat(TokenUtils.splitToken(signed)[1], is("eyJzdWIiOlsiMTIzNDU2Nzg5MCJdfQ")); + assertThat(TokenUtils.splitToken(signed)[1], is("eyJzdWIiOiIxMjM0NTY3ODkwIn0")); } @Test @@ -284,7 +491,7 @@ public void shouldThrowOnNullCustomClaimName() throws Exception { @Test public void shouldAcceptCustomClaimOfTypeString() throws Exception { String jwt = JWTCreator.init() - .withNonStandardClaim("name", "value") + .withNonStandardClaim(Claims.NAME, "value") .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); @@ -295,7 +502,7 @@ public void shouldAcceptCustomClaimOfTypeString() throws Exception { @Test public void shouldAcceptCustomClaimOfTypeInteger() throws Exception { String jwt = JWTCreator.init() - .withNonStandardClaim("name", 123) + .withNonStandardClaim(Claims.NAME, 123) .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); @@ -306,7 +513,7 @@ public void shouldAcceptCustomClaimOfTypeInteger() throws Exception { @Test public void shouldAcceptCustomClaimOfTypeLong() throws Exception { String jwt = JWTCreator.init() - .withNonStandardClaim("name", Long.MAX_VALUE) + .withNonStandardClaim(Claims.NAME, Long.MAX_VALUE) .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); @@ -317,7 +524,7 @@ public void shouldAcceptCustomClaimOfTypeLong() throws Exception { @Test public void shouldAcceptCustomClaimOfTypeDouble() throws Exception { String jwt = JWTCreator.init() - .withNonStandardClaim("name", 23.45) + .withNonStandardClaim(Claims.NAME, 23.45) .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); @@ -328,7 +535,7 @@ public void shouldAcceptCustomClaimOfTypeDouble() throws Exception { @Test public void shouldAcceptCustomClaimOfTypeBoolean() throws Exception { String jwt = JWTCreator.init() - .withNonStandardClaim("name", true) + .withNonStandardClaim(Claims.NAME, true) .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); @@ -340,7 +547,7 @@ public void shouldAcceptCustomClaimOfTypeBoolean() throws Exception { public void shouldAcceptCustomClaimOfTypeDate() throws Exception { Date date = new Date(1478891521000L); String jwt = JWTCreator.init() - .withNonStandardClaim("name", date) + .withNonStandardClaim(Claims.NAME, date) .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); @@ -351,7 +558,7 @@ public void shouldAcceptCustomClaimOfTypeDate() throws Exception { @Test public void shouldAcceptCustomArrayClaimOfTypeString() throws Exception { String jwt = JWTCreator.init() - .withArrayClaim("name", new String[]{"text", "123", "true"}) + .withArrayClaim(Claims.NAME, new String[]{"text", "123", "true"}) .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); @@ -362,7 +569,7 @@ public void shouldAcceptCustomArrayClaimOfTypeString() throws Exception { @Test public void shouldAcceptCustomArrayClaimOfTypeInteger() throws Exception { String jwt = JWTCreator.init() - .withArrayClaim("name", new Integer[]{1, 2, 3}) + .withArrayClaim(Claims.NAME, new Integer[]{1, 2, 3}) .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); @@ -373,7 +580,7 @@ public void shouldAcceptCustomArrayClaimOfTypeInteger() throws Exception { @Test public void shouldAcceptCustomArrayClaimOfTypeLong() throws Exception { String jwt = JWTCreator.init() - .withArrayClaim("name", new Long[]{1L, 2L, 3L}) + .withArrayClaim(Claims.NAME, new Long[]{1L, 2L, 3L}) .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); diff --git a/lib/src/test/java/com/auth0/jwt/creators/RiscJwtCreatorTest.java b/lib/src/test/java/com/auth0/jwt/creators/RiscJwtCreatorTest.java index 31a03ef..bbc3f1b 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/RiscJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/RiscJwtCreatorTest.java @@ -21,24 +21,25 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static java.util.Arrays.asList; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; import com.auth0.jwt.jwts.JWT; import com.auth0.jwt.jwts.RiscJWT; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertTrue; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.text.SimpleDateFormat; -import java.util.*; - public class RiscJwtCreatorTest { @Rule @@ -108,7 +109,7 @@ public void testRiscJwtCreatorBase32Encoding() throws Exception { @Test public void testRiscJwtCreatorJtiNotProvidedButRequired() throws Exception { thrown.expect(Exception.class); - thrown.expectMessage("Jti has not been set"); + thrown.expectMessage("jti has not been set"); Algorithm algorithm = Algorithm.HMAC256("secret"); String token = RiscJwtCreator.build() @@ -129,7 +130,7 @@ public void testRiscJwtCreatorJtiNotProvidedButRequired() throws Exception { @Test public void testRiscJwtCreatorExpNotProvidedButNotRequired() throws Exception { thrown.expect(Exception.class); - thrown.expectMessage("Jti has not been set"); + thrown.expectMessage("jti has not been set"); Algorithm algorithm = Algorithm.HMAC256("secret"); String token = RiscJwtCreator.build() @@ -405,10 +406,10 @@ public void testRiscJwtCreatorExpTimeHasPassed() throws Exception { } private static void verifyClaims(Map claims, Date exp) { - assertTrue(claims.get(PublicClaims.ISSUER).asList(String.class).get(0).equals("issuer")); - assertTrue(claims.get(PublicClaims.SUBJECT).asList(String.class).get(0).equals("subject")); - assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals("audience")); - assertTrue(claims.get(PublicClaims.EXPIRES_AT).asDate().toString().equals(exp.toString())); - assertTrue(claims.get(PublicClaims.JWT_ID).asString().equals(jti)); + assertTrue(claims.get(Claims.ISSUER).asString().equals("issuer")); + assertTrue(claims.get(Claims.SUBJECT).asString().equals("subject")); + assertTrue(claims.get(Claims.AUDIENCE).asString().equals("audience")); + assertTrue(claims.get(Claims.EXPIRES_AT).asDate().toString().equals(exp.toString())); + assertTrue(claims.get(Claims.JWT_ID).asString().equals(jti)); } } \ No newline at end of file diff --git a/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java b/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java index 5ebb397..cbec6f2 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java @@ -21,25 +21,25 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static java.util.Arrays.asList; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.creators.ScopedJwtCreator; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; import com.auth0.jwt.jwts.JWT; import com.auth0.jwt.jwts.ScopedJWT; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertTrue; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.text.SimpleDateFormat; -import java.util.*; - public class ScopedJwtCreatorTest { @Rule @@ -52,7 +52,7 @@ public class ScopedJwtCreatorTest { public void testScopedJwtCreatorAllStandardClaimsMustBeRequired() throws Exception { Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("issuer") .withSubject("subject") .withAudience("audience") @@ -60,7 +60,7 @@ public void testScopedJwtCreatorAllStandardClaimsMustBeRequired() throws Excepti .withIat(iat) .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -70,7 +70,7 @@ public void testScopedJwtCreatorAllStandardClaimsMustBeRequired() throws Excepti public void testScopedJwtCreatorBase16Encoding() throws Exception { Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("issuer") .withSubject("subject") .withAudience("audience") @@ -78,7 +78,7 @@ public void testScopedJwtCreatorBase16Encoding() throws Exception { .withIat(iat) .signBase16Encoding(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode16Bytes(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -88,7 +88,7 @@ public void testScopedJwtCreatorBase16Encoding() throws Exception { public void testScopedJwtCreatorBase32Encoding() throws Exception { Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("issuer") .withSubject("subject") .withAudience("audience") @@ -96,7 +96,7 @@ public void testScopedJwtCreatorBase32Encoding() throws Exception { .withIat(iat) .signBase32Encoding(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode32Bytes(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -116,7 +116,7 @@ public void testScopedJwtCreatorInvalidScope() throws Exception { .withIat(iat) .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -126,7 +126,7 @@ public void testScopedJwtCreatorInvalidIssuer() throws Exception { thrown.expectMessage("The Claim 'iss' value doesn't match the required one."); Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("invalid") .withSubject("subject") .withAudience("audience") @@ -134,7 +134,7 @@ public void testScopedJwtCreatorInvalidIssuer() throws Exception { .withIat(iat) .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -144,7 +144,7 @@ public void testScopedJwtCreatorInvalidAudience() throws Exception { thrown.expectMessage("The Claim 'aud' value doesn't contain the required audience."); Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("issuer") .withSubject("subject") .withAudience("invalid") @@ -152,14 +152,14 @@ public void testScopedJwtCreatorInvalidAudience() throws Exception { .withIat(iat) .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @Test public void testScopedJwtCreatorScopeNotProvided() throws Exception { thrown.expect(Exception.class); - thrown.expectMessage("Standard claim: Scope has not been set"); + thrown.expectMessage("Standard claim: scope has not been set"); Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ScopedJwtCreator.build() .withIssuer("issuer") @@ -169,7 +169,7 @@ public void testScopedJwtCreatorScopeNotProvided() throws Exception { .withIat(iat) .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -182,7 +182,7 @@ public void testScopedJwtCreatorNoneAlgorithmNotAllowed() throws Exception { Algorithm algorithm = Algorithm.none(); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("issuer") .withSubject("subject") .withAudience("audience") @@ -192,7 +192,7 @@ public void testScopedJwtCreatorNoneAlgorithmNotAllowed() throws Exception { .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -203,7 +203,7 @@ public void testScopedJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() th Algorithm algorithm = Algorithm.none(); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("issuer") .withSubject("subject") .withAudience("audience") @@ -212,7 +212,7 @@ public void testScopedJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() th .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -220,7 +220,7 @@ public void testScopedJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() th public void testScopedJwtCreatorNoneAlgorithmAllowed() throws Exception { Algorithm algorithm = Algorithm.none(); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("issuer") .withSubject("subject") .withAudience("audience") @@ -229,7 +229,7 @@ public void testScopedJwtCreatorNoneAlgorithmAllowed() throws Exception { .withIat(iat) .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -239,7 +239,7 @@ public void testScopedJwtCreatorNoneAlgorithmAllowed() throws Exception { public void testScopedJwtCreatorArrayClaim() throws Exception { Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("issuer") .withSubject("subject") .withAudience("audience") @@ -248,7 +248,7 @@ public void testScopedJwtCreatorArrayClaim() throws Exception { .withIat(iat) .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -258,7 +258,7 @@ public void testScopedJwtCreatorArrayClaim() throws Exception { public void testScopedJwtCreatorNonStandardClaimStringValue() throws Exception { Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("issuer") .withSubject("subject") .withAudience("audience") @@ -267,7 +267,7 @@ public void testScopedJwtCreatorNonStandardClaimStringValue() throws Exception { .withIat(iat) .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -277,7 +277,7 @@ public void testScopedJwtCreatorNonStandardClaimStringValue() throws Exception { public void testScopedJwtCreatorNonStandardClaimIntegerValue() throws Exception { Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("issuer") .withSubject("subject") .withAudience("audience") @@ -286,7 +286,7 @@ public void testScopedJwtCreatorNonStandardClaimIntegerValue() throws Exception .withIat(iat) .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -296,7 +296,7 @@ public void testScopedJwtCreatorNonStandardClaimIntegerValue() throws Exception public void testScopedJwtCreatorNonStandardClaimDoubleValue() throws Exception { Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("issuer") .withSubject("subject") .withAudience("audience") @@ -305,7 +305,7 @@ public void testScopedJwtCreatorNonStandardClaimDoubleValue() throws Exception { .withIat(iat) .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -315,7 +315,7 @@ public void testScopedJwtCreatorNonStandardClaimDoubleValue() throws Exception { public void testScopedJwtCreatorNonStandardClaimLongValue() throws Exception { Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("issuer") .withSubject("subject") .withAudience("audience") @@ -324,7 +324,7 @@ public void testScopedJwtCreatorNonStandardClaimLongValue() throws Exception { .withIat(iat) .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -334,7 +334,7 @@ public void testScopedJwtCreatorNonStandardClaimLongValue() throws Exception { public void testScopedJwtCreatorNonStandardClaimBooleanValue() throws Exception { Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("issuer") .withSubject("subject") .withAudience("audience") @@ -343,7 +343,7 @@ public void testScopedJwtCreatorNonStandardClaimBooleanValue() throws Exception .withIat(iat) .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -353,7 +353,7 @@ public void testScopedJwtCreatorNonStandardClaimBooleanValue() throws Exception public void testScopedJwtCreatorNonStandardClaimDateValue() throws Exception { Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("issuer") .withSubject("subject") .withAudience("audience") @@ -362,7 +362,7 @@ public void testScopedJwtCreatorNonStandardClaimDateValue() throws Exception { .withIat(iat) .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -381,7 +381,7 @@ public void testScopedJwtCreatorExpTimeHasPassed() throws Exception { Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("issuer") .withSubject("subject") .withAudience("audience") @@ -390,16 +390,16 @@ public void testScopedJwtCreatorExpTimeHasPassed() throws Exception { .withIat(iat) .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Claims.SCOPE, asList("issuer"), asList("audience"), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, expDate); } private static void verifyClaims(Map claims, Date exp) { - assertTrue(claims.get(PublicClaims.ISSUER).asList(String.class).get(0).equals("issuer")); - assertTrue(claims.get(PublicClaims.SUBJECT).asList(String.class).get(0).equals("subject")); - assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals("audience")); - assertTrue(claims.get(PublicClaims.EXPIRES_AT).asDate().toString().equals(exp.toString())); + assertTrue(claims.get(Claims.ISSUER).asString().equals("issuer")); + assertTrue(claims.get(Claims.SUBJECT).asString().equals("subject")); + assertTrue(claims.get(Claims.AUDIENCE).asString().equals("audience")); + assertTrue(claims.get(Claims.EXPIRES_AT).asDate().toString().equals(exp.toString())); } } \ No newline at end of file diff --git a/lib/src/test/java/com/auth0/jwt/impl/BasicHeaderTest.java b/lib/src/test/java/com/auth0/jwt/impl/BasicHeaderTest.java index bd2c59c..5221c1b 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/BasicHeaderTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/BasicHeaderTest.java @@ -19,20 +19,22 @@ package com.auth0.jwt.impl; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.TextNode; +import java.util.HashMap; +import java.util.Map; import org.hamcrest.collection.IsMapContaining; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.util.HashMap; -import java.util.Map; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; - public class BasicHeaderTest { @Rule diff --git a/lib/src/test/java/com/auth0/jwt/impl/ClaimsHolderTest.java b/lib/src/test/java/com/auth0/jwt/impl/ClaimsHolderTest.java index fbdae57..7429937 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/ClaimsHolderTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/ClaimsHolderTest.java @@ -19,14 +19,15 @@ package com.auth0.jwt.impl; -import org.hamcrest.collection.IsMapContaining; -import org.junit.Test; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; import java.util.HashMap; import java.util.Map; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; +import org.hamcrest.collection.IsMapContaining; +import org.junit.Test; public class ClaimsHolderTest { diff --git a/lib/src/test/java/com/auth0/jwt/impl/HeaderDeserializerTest.java b/lib/src/test/java/com/auth0/jwt/impl/HeaderDeserializerTest.java index 63c72a7..8f99d87 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/HeaderDeserializerTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/HeaderDeserializerTest.java @@ -19,6 +19,15 @@ package com.auth0.jwt.impl; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.interfaces.Header; import com.fasterxml.jackson.core.JsonFactory; @@ -31,22 +40,14 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.TextNode; +import java.io.StringReader; +import java.util.HashMap; +import java.util.Map; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.io.StringReader; -import java.util.HashMap; -import java.util.Map; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class HeaderDeserializerTest { @Rule @@ -77,7 +78,7 @@ public void shouldThrowOnNullTree() throws Exception { @Test - public void shouldNotRemoveKnownPublicClaimsFromTree() throws Exception { + public void shouldNotRemoveKnownClaimsFromTree() throws Exception { String headerJSON = "{\n" + " \"alg\": \"HS256\",\n" + " \"typ\": \"jws\",\n" + diff --git a/lib/src/test/java/com/auth0/jwt/impl/JWTParserTest.java b/lib/src/test/java/com/auth0/jwt/impl/JWTParserTest.java index a19f3ee..a408cae 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/JWTParserTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/JWTParserTest.java @@ -19,6 +19,16 @@ package com.auth0.jwt.impl; +import static com.auth0.jwt.impl.JWTParser.getDefaultObjectMapper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.interfaces.Header; import com.auth0.jwt.interfaces.Payload; @@ -30,13 +40,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import static com.auth0.jwt.impl.JWTParser.getDefaultObjectMapper; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - public class JWTParserTest { @Rule diff --git a/lib/src/test/java/com/auth0/jwt/impl/JsonNodeClaimTest.java b/lib/src/test/java/com/auth0/jwt/impl/JsonNodeClaimTest.java index 2e755d6..a93dc36 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/JsonNodeClaimTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/JsonNodeClaimTest.java @@ -19,6 +19,21 @@ package com.auth0.jwt.impl; +import static com.auth0.jwt.impl.JWTParser.getDefaultObjectMapper; +import static com.auth0.jwt.impl.JsonNodeClaim.claimFromNode; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.hamcrest.core.IsNull.nullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + import com.auth0.jwt.UserPojo; import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.interfaces.Claim; @@ -30,6 +45,13 @@ import com.fasterxml.jackson.databind.node.MissingNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; import org.hamcrest.collection.IsMapContaining; import org.junit.Before; import org.junit.Rule; @@ -37,17 +59,6 @@ import org.junit.rules.ExpectedException; import org.mockito.ArgumentMatchers; -import java.io.IOException; -import java.util.*; - -import static com.auth0.jwt.impl.JWTParser.getDefaultObjectMapper; -import static com.auth0.jwt.impl.JsonNodeClaim.claimFromNode; -import static org.hamcrest.Matchers.*; -import static org.hamcrest.core.IsNull.notNullValue; -import static org.hamcrest.core.IsNull.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.*; - public class JsonNodeClaimTest { private ObjectMapper mapper; @@ -328,7 +339,7 @@ public void shouldGetAsMapValue() throws Exception { assertThat(claim, is(notNullValue())); Map map = claim.as(Map.class); - assertThat(((Map) map.get("key")), hasEntry("name", (Object) "john")); + assertThat(((Map) map.get("key")), hasEntry(Claims.NAME, (Object) "john")); assertThat(((Map) map.get("key")), hasEntry("id", (Object) 123)); } diff --git a/lib/src/test/java/com/auth0/jwt/impl/PayloadDeserializerTest.java b/lib/src/test/java/com/auth0/jwt/impl/PayloadDeserializerTest.java index 2a2d3d2..2f7f1d4 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/PayloadDeserializerTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/PayloadDeserializerTest.java @@ -19,6 +19,16 @@ package com.auth0.jwt.impl; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.interfaces.Payload; import com.fasterxml.jackson.core.JsonFactory; @@ -28,26 +38,26 @@ import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.*; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.IntNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.LongNode; +import com.fasterxml.jackson.databind.node.NullNode; +import com.fasterxml.jackson.databind.node.TextNode; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.hamcrest.collection.IsCollectionWithSize; import org.hamcrest.collection.IsEmptyCollection; import org.hamcrest.core.IsCollectionContaining; -import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.io.StringReader; -import java.util.*; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class PayloadDeserializerTest { @Rule @@ -91,7 +101,7 @@ public void shouldThrowWhenParsingArrayWithObjectValue() throws Exception { } @Test - public void shouldNotRemoveKnownPublicClaimsFromTree() throws Exception { + public void shouldNotRemoveKnownClaimsFromTree() throws Exception { String payloadJSON = "{\n" + " \"iss\": \"auth0\",\n" + " \"sub\": \"emails\",\n" + @@ -125,7 +135,7 @@ public void shouldNotRemoveKnownPublicClaimsFromTree() throws Exception { assertThat(payload.getClaim("iat").asDouble(), is(10101010D)); assertThat(payload.getClaim("exp").asDouble(), is(11111111D)); assertThat(payload.getClaim("nbf").asDouble(), is(10101011D)); - assertThat(payload.getClaim("jti").asString(), is("idid")); + assertThat(payload.getClaim(Claims.JWT_ID).asString(), is("idid")); } @Test diff --git a/lib/src/test/java/com/auth0/jwt/impl/PayloadImplTest.java b/lib/src/test/java/com/auth0/jwt/impl/PayloadImplTest.java index b81fc3f..24ca3e2 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/PayloadImplTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/PayloadImplTest.java @@ -19,26 +19,28 @@ package com.auth0.jwt.impl; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.interfaces.Claim; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; import org.hamcrest.collection.IsCollectionWithSize; import org.hamcrest.core.IsCollectionContaining; -import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; - public class PayloadImplTest { @Rule @@ -195,6 +197,6 @@ public void shouldNotAllowToModifyClaimsMap() throws Exception { Map claims = payload.getClaims(); assertThat(claims, is(notNullValue())); exception.expect(UnsupportedOperationException.class); - claims.put("name", null); + claims.put(Claims.NAME, null); } } \ No newline at end of file diff --git a/lib/src/test/java/com/auth0/jwt/impl/PayloadSerializerTest.java b/lib/src/test/java/com/auth0/jwt/impl/PayloadSerializerTest.java index c7e9873..95bfd63 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/PayloadSerializerTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/PayloadSerializerTest.java @@ -19,22 +19,23 @@ package com.auth0.jwt.impl; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + import com.auth0.jwt.UserPojo; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; -import org.junit.Before; -import org.junit.Test; - import java.io.StringWriter; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Map; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; +import org.junit.Before; +import org.junit.Test; public class PayloadSerializerTest { @@ -157,7 +158,7 @@ public void shouldSerializeDatesUsingLong() throws Exception { @Test public void shouldSerializeStrings() throws Exception { - ClaimsHolder holder = holderFor("name", "Auth0 Inc"); + ClaimsHolder holder = holderFor(Claims.NAME, "Auth0 Inc"); serializer.serialize(holder, jsonGenerator, serializerProvider); jsonGenerator.flush(); diff --git a/lib/src/test/resources/example_jwk.json b/lib/src/test/resources/example_jwk.json new file mode 100644 index 0000000..e112876 --- /dev/null +++ b/lib/src/test/resources/example_jwk.json @@ -0,0 +1 @@ +{"keys":[{"kty": "RSA", "use": "sig", "kid": "dnVrY0tQcUZCUWh2T25EaVk3Q0ZLRW9VdnRxU0tiUHNiVkVGS3k1V1Jidw", "n": "sZI5mt1nKLpbtab8wDx65B8-tgDOAiJ0oGi8VwvPpZcanlA1hBEoGol49j1CCj7mhidrFss5kDB9xMPSY51NXf3Fj6kB6VpNEG5JWPhYXcIrCXE9-9tSdvSAdpqCSD3pjgRdCrkP3OV23gF-LdYIaplLXWyOV8XNkyodW52bw5KQbXHMFqn4dDFq3IY7WSRQs5OJMKWcGMl7sdNH6aoevdBE-sRR5rHVGS2W1TH6Zjz9BA408-S3tvHWTeAceFAmwlOCNj63hBpx-u88GyLc1Q5Ta0IRdbnZFtK7DjYjtaiR36CZlyUKeNvfqH2BTl34WhTJmqEIXiiIlTECZ8424w", "e": "AQAB", "x5c": ["MIIDLjCCAhagAwIBAgIURpHFbC1b+Z8ILtRD+W54wunTh5AwDQYJKoZIhvcNAQELBQAwRDELMAkGA1UEBhMCU0UxDTALBgNVBAcMBFVtZWExEjAQBgNVBAoMCUNhdGFsb2dpeDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTE3MTIyMDIyNTExOFoXDTE3MTIzMDIyNTExOFowRDELMAkGA1UEBhMCU0UxDTALBgNVBAcMBFVtZWExEjAQBgNVBAoMCUNhdGFsb2dpeDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsZI5mt1nKLpbtab8wDx65B8+tgDOAiJ0oGi8VwvPpZcanlA1hBEoGol49j1CCj7mhidrFss5kDB9xMPSY51NXf3Fj6kB6VpNEG5JWPhYXcIrCXE9+9tSdvSAdpqCSD3pjgRdCrkP3OV23gF+LdYIaplLXWyOV8XNkyodW52bw5KQbXHMFqn4dDFq3IY7WSRQs5OJMKWcGMl7sdNH6aoevdBE+sRR5rHVGS2W1TH6Zjz9BA408+S3tvHWTeAceFAmwlOCNj63hBpx+u88GyLc1Q5Ta0IRdbnZFtK7DjYjtaiR36CZlyUKeNvfqH2BTl34WhTJmqEIXiiIlTECZ8424wIDAQABoxgwFjAUBgNVHREEDTALgglsb2NhbGhvc3QwDQYJKoZIhvcNAQELBQADggEBAA/3G++KM8jV9M/Qsn+wiVjGcF0mmjKOzpNFPP6qolGhQ72Y/abm18Wd9WMhm0U96kYvvj+lD+iW4YZsdqh6M1fP4i00tW5ZwecbNKfOgi0xRqqR3ID6w9tn/E/eN21xkNnFrmgr6ORV4h41nxRZoroJRtj7Dqg83eH6uyxxHEWApiuwbHOll1xXoQHFXv6h1/ZA5clFlmnvgzTUguBY80tIXD2j+gvMHvp5TqFqzPzqShbmOgAVAht3C4bnVLysW2ts7qde186WurSiWK185MfWijW0glD1sN2hDwkArbGCewbSNtkW0bk998z9rcyM9pZiZ8+iFa2ar97Sh1zyBpU="]}]} \ No newline at end of file diff --git a/lib/src/test/resources/example_key_pcks8.pem b/lib/src/test/resources/example_key_pcks8.pem new file mode 100644 index 0000000..bee253d --- /dev/null +++ b/lib/src/test/resources/example_key_pcks8.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCkqzojnRyJ1sbq +ubnOi8xkt7PKHmapaZmrdcbwdtT2YTFv02PenqwkJ/5ONHvoLHE/yQfJrM9DNAmI +cQFuEOOYP+aUrhm/LecniLijNgBWkDSo0t/HtZQldlMnymkqpECzFGJ1f6xIup/8 +R4t4KCDC8PCXS0We0GhYHg6NmwjljAF130RR9pJyEvPxejWSIjad8HumJWAkFBW7 +Me4hMAuVwAA8nRbe2SFuwPG1H4cLnKUaAhUKVEyXoJFtO7+a0uE3Z8eTW0yvmlWG +Nk9V4cNVdgRkPmZTJQpF8YgDlStSWm3QrBVmT1qKrADNPThfC4QLTOzvBU068crz +b4jLLqLPAgMBAAECggEANJgL5bwUlWHn/qh7VCEKk1CpN/El0Q5NapofhEYwFtFM +PO9DgqMjUBkF/Gx+9tTbBwhqWFu9hzVjphSR5Fm4l7QxLWO+DXXX0qS0dEyXJw7A +Avv3RY4VVzHHtXnMxTXZBFmKaQTyPfh9iNJBFYubiyfxcCE2h1cBPMO82jWeTdI6 +oaUvFh7XjTtcrhe4wWKqXsS3ikhgCWAdnBNU/EK1+fuXDXQmqA6HcyBg6dJIB1Rd +glNmkhM4cTqMDQZXApg/q+kvF/6gJcYP8oMYM7m3UrZlaaKWj/aV/Dy8t4ohLfYR +H7fApCSY0BWqhOxg9d63NB1BnekN6lS4XtO/igf8IQKBgQDS0S3t2zBTjDdkEa0O +W4TwPwWOJT45hpfHoRlNSkKaQ0bdn5HhO02HnjWgRqbWkEPP8Y38j3HNwA6dikki +x+1JeZVHWI5d/V/Q+Z8EEAMF6WiZExR9oFx4Oo8D4dmO4hWGH/Ea995NoddWzkD0 +nvOqR1mZ8DXOhw4kIXY6egqExQKBgQDH9gypvB6sVOuJGv1znQL7s2oLHNAhQu6k +7uNXUTtk79SnBylkWu7dvqQ30b2YcTc20ahhZvPIUJyA+lnujugb35EbSuxWZwLT +Tcn9v6h/unNeG7GcjBLOxNt8AfLh2vk8i5bSXfC4g3yG1u7i6NkGGf7lqyxMhJma +J8dUT/kKgwKBgBze1qpfPRQD/MXwgcGYmPEJwGoCAa6BFyIYls114P8dPYQ2SRUO +OQTcjr1/T3PM1+yPSQGQZ2Zk6dt7R57CwGUyiFX38689drS4qqU0yCU0HMXxzfmS +T3eLlXBTqqadoZL3pt4pmcEJ6+KQZmbZqcbk9IlXUxcQechK6NUDR5N9AoGALnfx +jWhYQHgjnGMXT0zHqrKRDDAP9grV5qJVVq9b/CL36jDx3456QDHTe91UEB8PU7/5 +P1lrgbuqAxcq2xN+wSt9TzhkH9gkgfJr5HorsDMmKFKLPfQXUtHQp8rUJMR8cyOF +UzHdhSOZRsSgEz9FX/OelsTmsImIIJjp66ACIf0CgYEA0WokWdQ8zdgmOPC8QbPN +mXUoekOOjqzuxUfctdMlrgk+6ic3zMibFAq8ocXA589Fv1lst0fmD2Y08UWaRrCV +e6INZifGgt6/b9eQrYWmng0LLdSTaVtBsPLdkWkx7ln1JJf4zpCGaAcR153vc63L +7Xg4A0PnJmdUzBm4RW+W0Go= +-----END PRIVATE KEY----- diff --git a/lib/src/test/resources/rsa-private-base16-64.pem b/lib/src/test/resources/rsa-private-base16-64.pem new file mode 100644 index 0000000..4bc0265 --- /dev/null +++ b/lib/src/test/resources/rsa-private-base16-64.pem @@ -0,0 +1,52 @@ +-----BEGIN PRIVATE KEY----- +MIIJRAIBADANBgkqhkiG9w0BAQEFAASCCS4wggkqAgEAAoICAQCgBUeuUxifOz+z +39EMmsupWdNGvwWmNOCIEK1wnoQaZAvCxDl//6Xn/RSlmFaGtmuZ28Ndb+tpj+nd +LNhfh8c4Zc9tCMbpmKMmN0UdfUIQNuAdeiQmEfIJGYy9FQT8yrGadTZOPKEdT5/E +ZhTKbPBEX4JiqfYcF0M+Br2vLVPG/R0x427Pe9ep38XepZB1j6q3wMd1/s+u9ytJ +fZ7fLdUI5tV3epgAM+drBxelQX9Q1JxxsGgCj+UM7TRLcdW31/IiR04dshZMj1ME +MBevuL/iLr3LVSv0sH/E8D6iqbIo5YFhrQaFtx0m1T91vz6145Rdo7K6MxYaply1 +Tx4YfXYcbXzMUaQhq4V8oVESTqp7iGluDc+NwmLxNe7Q4D7HVNuJwJsAhcfG+4RQ +hCjzV5E9OGAMfQhq4UW5b5ofZ4ow7Vd8aB7rnlfiiyflF8pdE29jb7DdVkwfJugN +35G9AiojhUD4ece8FL0xIAzmYBS40OfBPjvKacg7Y2sRwO9SkSGMs7qG/GfAIRK3 +ZRAQW+lsiL7pR4ZXA1pyI22er+1/qURiUiCY/rWBYMDLkwIAU5CL6ISurgUVPRPK +1TxxWf9DRrSeuiCzdyBGu8ijfIfLK3rbG+u1xbo3/JTdPkkGYW8rwI77OoLDPdwL +L6PpTj7Le6XPTt+YPBa5M7Qs78lDEQIDAQABAoICAQCA+iB/gpyK4z+CJLkjdrUG +x87B6/+Kqn37Ta3t4uZJOzA7iNtrrsuzQ8pbeoDrTadGuNoruqS9TfDKg3XW8eKC +M5VPpc5lw9BkYhIEJcyUsxZKzALM6JPz/7LvSDzf4CPsgeMGhlm5/U6iB0Fksw+p +nG3ERoeGtr1NBjPnORqYfbUFW/IZrBD069dZkIryJp0MRIbANWSB+tjaADWIXzGh +XiTai2Zua2dwXaQSX8tVhDigbfY3cnHEzH/k+1iuOJECTgTJbJwKk07vRjAhQ0Dt +9oylkf2+2G/zdUyW4T4nNmzlJIfoSOJnRWRD7KSICGmyW9oXuEttqX95584zIRSL +qKd8UhSTtNakypNAmJYOPb3M79yd0wYu34E71NqeXsxdjM2JennKJyQ3Qj+RFxwL +Ff6OuO2YrLBb8KrgPSC91buhq4S7X0HrLvCZy8QYm2xV4JD9Ng2FqHBsH9SnmzXY +lINGYdaWW8aHXScvr9r+SqwrtwgHGql/jjv+e+3czTSqOjdIr3yj1N1Y+cNq4Gwr +/li+djAV8SybOvohLj2/HSkjQ3kzny4iqrI4mD38WIJvsH0Ubj4lN8vAvPvrIOsP +oCuaD8PC8j1XP3AM6g0wifinzqnfe13pMmDgGOJyxbn7EHKNCOJCHXQqCthFA6Ld +5LPgBlfGApWbjr+NmcAQrQKCAQEA0yLgdOop8cv7zpCBcQjfUe3iayRaVu5qaEcT +zGmFVFRMqhni24r4NQGnxNObcPvAzKPlKKrUuH6SGZS55q9mT8cXt4R9i4QA24WR +R8WEgqE2DOggH9b6SIiMU4LXxaJc9jxqjdCld7LbJI5qTk1Fmmq6jSPZLsBLdskp +JcFg6kAobfIra4EFI195wvrBG/GkUezkPB8MzyzgI4bbLzmdSHAmUiqbfEwNYw37 +USwSvSUpvIJg5/4u3mvlIQ2sOHizFVbVdGg+bCU0c4oM4Z5czyqB9F4gJY3U3GYr +dQlFMVMLVT20yyvMrUPrZSgA9uL8D3BhyITJ1oV5RodVn5oicwKCAQEAwgXhZ+U4 +/BgRRLMvKKZmNe4On/Y4KoTB8LfdnZgIUYlkwTF24IGEPRDAvpBLAsyCw7o7ImNi +ft0pr7a8RxOHNHkXCmAiK3Dka4xmGdvagG4E2K/3LNa936qqbM9RkDDt+2/M4CZe +XLwA1UmWVir2+4Zw1gipOYQZqaDw0jaU3OVW4fReOlB8iInH4pYpbzSMeuYPdbEF +nxxPdzydzkxebmrD+ffxYccSPFGr34nnrqq7/DrO3WXx2eFAY/Ud9f/bDH55UKod +A2tEd6ysBo3cYJoZ+IVDNkEFNNjUN0dJngqWsCNKWAW6bXTodHvNOK1D+af1aoSj +b89DYpK8AJ9vawKCAQBD9QfV2cDiaMuFsxFWtoparnygC7VgIaDyK159/sDBYdjD +L03LaDF3ri63tXxko0NtGpuZuVJ6h5Ky1SH41B/UMbq6gNR/4V79SUJ3nWWHPihN +gzFDzkgErJ6uCoE0xYuyXcPWHYAExPawD3678Tcj+pJM92riF1ayxxCNbG6rNzdM +HBRJp99lgUeJsHgTbHV9QQg9KalPzZvfE3rc+mhbdm1/KOOe4EO2zDtF5y+o3ZtP +Z4+VXETtpkC7oND75C2QAsD1lM/ysw7s2VRIElbA/2eQpfMm4z3OKrx2ESPKOnZ9 +Wz0j39cjNadAid21mV2UApIWnlbwy0k7oDe5BT1tAoIBAQC9wcKSOj1hUKiS6CxX +NWcBl7H2AHkuHGkRZMH6P5bjJ9zClf4N1J3gm2Hm/nheZGX/x0POfiT2rpb2o2HA +ofi5+TPvkdXZZq///3BcGgm5UeCrjG3SDLPm7KOBh8Hdo/0czFszXlMrnzOxZicC +X0Lu/K2epxnahrgSjrT44yj0Ydh3ZOhDYDRr1VUI5pPfjyVVjWvRTzCQTL/rff1Y +ppg0pXbGIxiQ6IGNPNM77UQKMDFqnplzLyE6VnMDT9fdoD48GfXMTpPRpDdyVA5q +2pOOZyi/RpZVmYHeDbJ/3djCGNkHq3wqWm/aXVx7kBlGNS8mHH6Jju/Jiov8/EWi +1kvBAoIBAQDMkmh2cRXl1CkwfmO+iRxFqHX28VC9tGGG9K+vPeHha1l8GnV2MiT1 +stpZUb9SG84mjITYQvmw9kCoiSNfHZbNrvRiz9oK2QJeJsroPtTgRt4kZU2V2Pqg +CoVxGmTcT0koAN79veqWQQ0WHd/23j4uBsOA8uLD+e7JqnH7K8VDxVNxshEOt9Vg +Xk/e5M5B5sHAg3DNPPEEyutox2xf7PWDDBYhf4t5PlsX55pmvAUsBYIosct8EcAe +VBk9GfDRtWdbjQW8gK6Zbc4wyuK5aQz8C75tRypQxbshedCkFx8puDXtYQJioGY0 +mtAjiFyqQBQd7rlm6XIE4+K1yW/q6X6P +-----END PRIVATE KEY----- \ No newline at end of file diff --git a/lib/src/test/resources/rsa-public-base16-64.pem b/lib/src/test/resources/rsa-public-base16-64.pem new file mode 100644 index 0000000..12be84e --- /dev/null +++ b/lib/src/test/resources/rsa-public-base16-64.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApKs6I50cidbG6rm5zovM +ZLezyh5mqWmZq3XG8HbU9mExb9Nj3p6sJCf+TjR76CxxP8kHyazPQzQJiHEBbhDj +mD/mlK4Zvy3nJ4i4ozYAVpA0qNLfx7WUJXZTJ8ppKqRAsxRidX+sSLqf/EeLeCgg +wvDwl0tFntBoWB4OjZsI5YwBdd9EUfaSchLz8Xo1kiI2nfB7piVgJBQVuzHuITAL +lcAAPJ0W3tkhbsDxtR+HC5ylGgIVClRMl6CRbTu/mtLhN2fHk1tMr5pVhjZPVeHD +VXYEZD5mUyUKRfGIA5UrUlpt0KwVZk9aiqwAzT04XwuEC0zs7wVNOvHK82+Iyy6i +zwIDAQAB +-----END PUBLIC KEY-----