From 92f43dc6c6dc1afe8a778eb313e3a8222aa758e5 Mon Sep 17 00:00:00 2001 From: Justin Dahmubed Date: Wed, 20 Dec 2017 14:34:38 -0800 Subject: [PATCH 1/5] X509 --- lib/build.gradle | 8 +- lib/jwksRSA.json | 1 + .../com/auth0/jwt/algorithms/Algorithm.java | 4 +- .../auth0/jwt/algorithms/ECDSAAlgorithm.java | 34 +++++++- .../auth0/jwt/algorithms/HMACAlgorithm.java | 9 +- .../auth0/jwt/algorithms/NoneAlgorithm.java | 7 +- .../auth0/jwt/algorithms/RSAAlgorithm.java | 85 +++++++++++++++---- .../java/com/auth0/jwt/algorithms/jwks.pem | 3 + .../com/auth0/jwt/creators/JWTCreator.java | 5 +- .../java/com/auth0/jwt/jwts/GoogleJWT.java | 2 +- lib/src/main/java/com/auth0/jwt/jwts/JWT.java | 78 +++++++++++++++-- lib/src/test/java/com/auth0/jwt/JWTTest.java | 16 ++-- .../jwt/creators/GoogleJwtCreatorTest.java | 2 +- .../auth0/jwt/creators/JWTCreatorTest.java | 83 +++++++++++++++--- .../test/resources/rsa-private-base16-64.pem | 52 ++++++++++++ 15 files changed, 332 insertions(+), 57 deletions(-) create mode 100644 lib/jwksRSA.json create mode 100644 lib/src/main/java/com/auth0/jwt/algorithms/jwks.pem create mode 100644 lib/src/test/resources/rsa-private-base16-64.pem 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/algorithms/Algorithm.java b/lib/src/main/java/com/auth0/jwt/algorithms/Algorithm.java index a63c454..8090627 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/Algorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/Algorithm.java @@ -385,6 +385,8 @@ public String toString() { */ public abstract void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception; + public abstract void verifyWithX509(DecodedJWT jwt, EncodeType encodeType, String jwksFile, String pemFile) throws Exception; + /** * Sign the given content using this Algorithm instance. * @@ -406,4 +408,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/ECDSAAlgorithm.java b/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java index 91a7fef..52e6b4e 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java @@ -19,23 +19,43 @@ 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.exceptions.SignatureGenerationException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.ECDSAKeyProvider; +import com.auth0.jwt.interfaces.Payload; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.JWSObject; +import com.nimbusds.jose.crypto.RSASSASigner; +import com.nimbusds.jose.crypto.RSASSAVerifier; +import com.nimbusds.jose.jwk.JWK; +import net.minidev.json.JSONArray; +import net.minidev.json.JSONObject; +import net.minidev.json.parser.JSONParser; 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.File; +import java.io.FileReader; +import java.net.URL; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.SignatureException; +import java.security.*; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.ECPublicKey; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.util.List; class ECDSAAlgorithm extends Algorithm { @@ -94,6 +114,11 @@ public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { } } + @Override + public void verifyWithX509(DecodedJWT jwt, EncodeType encodeType, String jwksFile, String pemFile) throws Exception { + throw new UnsupportedOperationException("X509 is not supported for ECDSA"); + } + @Override public byte[] sign(byte[] contentBytes) throws SignatureGenerationException { try { @@ -241,6 +266,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 +284,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..b4fa457 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/HMACAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/HMACAlgorithm.java @@ -30,7 +30,7 @@ import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.binary.StringUtils; -import java.io.UnsupportedEncodingException; +import java.io.*; import java.net.URLDecoder; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; @@ -99,6 +99,11 @@ public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { } } + @Override + public void verifyWithX509(DecodedJWT jwt, EncodeType encodeType, String jwksFile, String pemFile) throws Exception { + throw new UnsupportedOperationException("X509 is not supported for HMAC"); + } + @Override public byte[] sign(byte[] contentBytes) throws SignatureGenerationException { try { @@ -108,4 +113,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..0acc663 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/NoneAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/NoneAlgorithm.java @@ -59,8 +59,13 @@ public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { } } + @Override + public void verifyWithX509(DecodedJWT jwt, EncodeType encodeType, 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..1bf3ffb 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/RSAAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/RSAAlgorithm.java @@ -19,6 +19,9 @@ 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.exceptions.SignatureGenerationException; import com.auth0.jwt.exceptions.SignatureVerificationException; @@ -27,14 +30,18 @@ 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; +import java.io.*; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.SignatureException; +import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; +import java.security.spec.X509EncodedKeySpec; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; class RSAAlgorithm extends Algorithm { @@ -55,8 +62,65 @@ class RSAAlgorithm extends Algorithm { this(new CryptoHelper(), id, algorithm, keyProvider); } + @Override + public void verifyWithX509(DecodedJWT jwt, EncodeType encodeType, String jwksFile, String pemFile) throws Exception { + List byteArrayList = decode(jwt, encodeType); + 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"), "utf-8"))) { + 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 { + List byteArrayList = decode(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 decode(DecodedJWT jwt, EncodeType encodeType) throws Exception{ byte[] contentBytes = String.format("%s.%s", jwt.getHeader(), jwt.getPayload()).getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = null; String signature = jwt.getSignature(); @@ -76,18 +140,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 new ArrayList<>(Arrays.asList(contentBytes, signatureBytes)); } @Override @@ -130,4 +183,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/JWTCreator.java b/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java index 54e4f13..baa945a 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java @@ -39,9 +39,11 @@ import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Map; +import java.util.logging.Logger; /** * The JWTCreator class holds the sign method to generate a complete JWT (with Signature) from a given Header and Payload content. @@ -448,7 +450,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/jwts/GoogleJWT.java b/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java index 1aaf574..755fad0 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java @@ -86,7 +86,7 @@ public GoogleVerification withName(String name) { @Override public Verification createVerifierForExtended(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/JWT.java b/lib/src/main/java/com/auth0/jwt/jwts/JWT.java index 4557a67..13b6849 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/JWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/JWT.java @@ -66,6 +66,26 @@ 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. + * @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, EncodeType.Base64, jwksFile, pemFile); + VerificationAndAssertion.verifyClaims(clock, jwt, claims); + return jwt; + } + /** * Convert the given token to a DecodedJWT *

@@ -86,6 +106,26 @@ 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. + * @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, EncodeType.Base16, jwksFile, pemFile); + VerificationAndAssertion.verifyClaims(clock, jwt, claims); + return jwt; + } + /** * Convert the given token to a DecodedJWT *

@@ -106,6 +146,26 @@ 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. + * @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, EncodeType.Base32, jwksFile, pemFile); + VerificationAndAssertion.verifyClaims(clock, jwt, claims); + return jwt; + } + /** * Returns a {Verification} to be used to validate token signature. * @@ -159,43 +219,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"); } /** @@ -471,4 +531,4 @@ protected void requireClaim(String name, Object value) { claims.put(name, value); } } -} +} \ No newline at end of file diff --git a/lib/src/test/java/com/auth0/jwt/JWTTest.java b/lib/src/test/java/com/auth0/jwt/JWTTest.java index b368d43..c19447c 100644 --- a/lib/src/test/java/com/auth0/jwt/JWTTest.java +++ b/lib/src/test/java/com/auth0/jwt/JWTTest.java @@ -48,56 +48,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/creators/GoogleJwtCreatorTest.java b/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java index ceba3d9..5434fdd 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java @@ -538,7 +538,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); } 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..59b5ee6 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java @@ -23,9 +23,10 @@ import com.auth0.jwt.PemUtils; import com.auth0.jwt.TokenUtils; import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.creators.JWTCreator; +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 +45,12 @@ 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 PRIVATE_KEY_FILE_EC_256 = "src/test/resources/ec256-key-private.pem"; - @Rule public ExpectedException exception = ExpectedException.none(); @@ -92,7 +93,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 +102,74 @@ 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,"./jwksRSA.json", "./src/main/java/com/auth0/jwt/algorithms/jwks.pem"); + algorithm.verifyWithX509(decoded, EncodeType.Base16,"./jwksRSA.json", "./src/main/java/com/auth0/jwt/algorithms/jwks.pem"); + } + + @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, "./jwksRSA.json", "./src/main/java/com/auth0/jwt/algorithms/jwks.pem"); + algorithm.verifyWithX509(decoded, EncodeType.Base32,"./jwksRSA.json", "./src/main/java/com/auth0/jwt/algorithms/jwks.pem"); + } + + @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, "./jwksRSA.json", "./src/main/java/com/auth0/jwt/algorithms/jwks.pem"); + algorithm.verifyWithX509(decoded, EncodeType.Base64, "./jwksRSA.json", "./src/main/java/com/auth0/jwt/algorithms/jwks.pem"); + } + + @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 +179,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 +195,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 +212,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 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 From 84459bc8eb8fa5b8dc4da540cb8dfe04146fc21c Mon Sep 17 00:00:00 2001 From: Justin Dahmubed Date: Thu, 21 Dec 2017 10:27:26 -0800 Subject: [PATCH 2/5] X509 --- .../com/auth0/jwt/algorithms/Algorithm.java | 2 +- .../auth0/jwt/algorithms/ECDSAAlgorithm.java | 2 +- .../auth0/jwt/algorithms/HMACAlgorithm.java | 2 +- .../auth0/jwt/algorithms/NoneAlgorithm.java | 2 +- .../auth0/jwt/algorithms/RSAAlgorithm.java | 9 +- .../com/auth0/jwt/creators/JWTCreator.java | 9 +- lib/src/main/java/com/auth0/jwt/jwts/JWT.java | 6 +- .../auth0/jwt/creators/JWTCreatorTest.java | 157 +++++++++++++++++- lib/src/test/resources/example_jwk.json | 1 + lib/src/test/resources/example_key_pcks8.pem | 28 ++++ .../test/resources/rsa-public-base16-64.pem | 9 + 11 files changed, 205 insertions(+), 22 deletions(-) create mode 100644 lib/src/test/resources/example_jwk.json create mode 100644 lib/src/test/resources/example_key_pcks8.pem create mode 100644 lib/src/test/resources/rsa-public-base16-64.pem 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 8090627..617b944 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/Algorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/Algorithm.java @@ -385,7 +385,7 @@ public String toString() { */ public abstract void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception; - public abstract void verifyWithX509(DecodedJWT jwt, EncodeType encodeType, String jwksFile, String pemFile) throws Exception; + public abstract void verifyWithX509(DecodedJWT jwt, String jwksFile, String pemFile) throws Exception; /** * Sign the given content using this Algorithm instance. 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 52e6b4e..0ae7a9b 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java @@ -115,7 +115,7 @@ public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { } @Override - public void verifyWithX509(DecodedJWT jwt, EncodeType encodeType, String jwksFile, String pemFile) throws Exception { + public void verifyWithX509(DecodedJWT jwt, String jwksFile, String pemFile) throws Exception { throw new UnsupportedOperationException("X509 is not supported for ECDSA"); } 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 b4fa457..c46958c 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/HMACAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/HMACAlgorithm.java @@ -100,7 +100,7 @@ public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { } @Override - public void verifyWithX509(DecodedJWT jwt, EncodeType encodeType, String jwksFile, String pemFile) throws Exception { + public void verifyWithX509(DecodedJWT jwt, String jwksFile, String pemFile) throws Exception { throw new UnsupportedOperationException("X509 is not supported for HMAC"); } 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 0acc663..c580fac 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/NoneAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/NoneAlgorithm.java @@ -60,7 +60,7 @@ public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { } @Override - public void verifyWithX509(DecodedJWT jwt, EncodeType encodeType, String jwksFile, String pemFile) throws Exception { + public void verifyWithX509(DecodedJWT jwt, String jwksFile, String pemFile) throws Exception { throw new UnsupportedOperationException("X509 is not supported for None algorithm"); } 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 1bf3ffb..8bf1627 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/RSAAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/RSAAlgorithm.java @@ -23,6 +23,7 @@ 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; @@ -63,8 +64,8 @@ class RSAAlgorithm extends Algorithm { } @Override - public void verifyWithX509(DecodedJWT jwt, EncodeType encodeType, String jwksFile, String pemFile) throws Exception { - List byteArrayList = decode(jwt, encodeType); + 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 { @@ -103,7 +104,7 @@ public void verifyWithX509(DecodedJWT jwt, EncodeType encodeType, String jwksFil @Override public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { - List byteArrayList = decode(jwt, encodeType); + List byteArrayList = fetchContentAndSignatureByteArrays(jwt, encodeType); byte[] contentBytes = byteArrayList.get(0); byte[] signatureBytes = byteArrayList.get(1); try { @@ -120,7 +121,7 @@ public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { } } - private List decode(DecodedJWT jwt, EncodeType encodeType) throws Exception{ + private List fetchContentAndSignatureByteArrays(DecodedJWT jwt, EncodeType encodeType) throws Exception{ byte[] contentBytes = String.format("%s.%s", jwt.getHeader(), jwt.getPayload()).getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = null; String signature = jwt.getSignature(); 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 baa945a..33cc7d4 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java @@ -29,21 +29,16 @@ 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.net.URLEncoder; import java.nio.charset.StandardCharsets; -import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Map; -import java.util.logging.Logger; /** * The JWTCreator class holds the sign method to generate a complete JWT (with Signature) from a given Header and Payload content. @@ -87,6 +82,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<>(); @@ -379,12 +375,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; } 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 13b6849..498e400 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/JWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/JWT.java @@ -81,7 +81,7 @@ public DecodedJWT decode(String token) throws Exception { 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, EncodeType.Base64, jwksFile, pemFile); + algorithm.verifyWithX509(jwt, jwksFile, pemFile); VerificationAndAssertion.verifyClaims(clock, jwt, claims); return jwt; } @@ -121,7 +121,7 @@ public DecodedJWT decode16Bytes(String token) throws Exception { 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, EncodeType.Base16, jwksFile, pemFile); + algorithm.verifyWithX509(jwt, jwksFile, pemFile); VerificationAndAssertion.verifyClaims(clock, jwt, claims); return jwt; } @@ -161,7 +161,7 @@ public DecodedJWT decode32Bytes(String token) throws Exception { 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, EncodeType.Base32, jwksFile, pemFile); + algorithm.verifyWithX509(jwt, jwksFile, pemFile); VerificationAndAssertion.verifyClaims(clock, jwt, claims); return jwt; } 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 59b5ee6..43491d2 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java @@ -23,6 +23,7 @@ import com.auth0.jwt.PemUtils; import com.auth0.jwt.TokenUtils; import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.ECDSAKeyProvider; import com.auth0.jwt.interfaces.RSAKeyProvider; @@ -49,6 +50,15 @@ public class JWTCreatorTest { 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 @@ -119,8 +129,79 @@ public void shouldAddKeyIdIfAvailableFromRSAAlgorithmsForBase16() throws Excepti .sign(algorithm, EncodeType.Base16); JWT jwt = JWT.require(Algorithm.RSA256(provider)).withIssuer("auth0").build(); - DecodedJWT decoded = jwt.decode16BytesWithX509(signed,"./jwksRSA.json", "./src/main/java/com/auth0/jwt/algorithms/jwks.pem"); - algorithm.verifyWithX509(decoded, EncodeType.Base16,"./jwksRSA.json", "./src/main/java/com/auth0/jwt/algorithms/jwks.pem"); + 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 @@ -137,10 +218,42 @@ public void shouldAddKeyIdIfAvailableFromRSAAlgorithmsForBase32() throws Excepti .sign(algorithm, EncodeType.Base32); JWT jwt = JWT.require(Algorithm.RSA256(provider)).withIssuer("auth0").build(); - DecodedJWT decoded = jwt.decode32BytesWithX509(signed, "./jwksRSA.json", "./src/main/java/com/auth0/jwt/algorithms/jwks.pem"); - algorithm.verifyWithX509(decoded, EncodeType.Base32,"./jwksRSA.json", "./src/main/java/com/auth0/jwt/algorithms/jwks.pem"); + 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"); @@ -160,10 +273,42 @@ public void shouldAddKeyIdIfAvailableFromRSAAlgorithmsForBase64() throws Excepti JWT jwt = JWT.require(Algorithm.RSA256(provider)).withIssuer("https://agaton-sax.com/") .withNonStandardClaim("foo","bar") .withNonStandardClaim("kit", "kat").build(); - DecodedJWT decoded = jwt.decodeWithX509(signed, "./jwksRSA.json", "./src/main/java/com/auth0/jwt/algorithms/jwks.pem"); - algorithm.verifyWithX509(decoded, EncodeType.Base64, "./jwksRSA.json", "./src/main/java/com/auth0/jwt/algorithms/jwks.pem"); + 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 { 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-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----- From fc6782b6da8b7c36e21aecf4c389b44159c70c5c Mon Sep 17 00:00:00 2001 From: Justin Dahmubed Date: Wed, 27 Dec 2017 09:49:20 -0800 Subject: [PATCH 3/5] X509 --- .../main/java/com/auth0/jwt/JWTDecoder.java | 49 +++++++++++++++++-- .../auth0/jwt/creators/AccessJwtCreator.java | 22 ++++----- .../jwt/creators/ExtendedJwtCreator.java | 4 +- .../com/auth0/jwt/creators/FbJwtCreator.java | 18 +++---- .../auth0/jwt/creators/GoogleJwtCreator.java | 30 ++++++------ .../jwt/creators/GoogleOrFbJwtCreator.java | 4 ++ .../jwt/creators/ImplicitJwtCreator.java | 22 ++++----- .../com/auth0/jwt/creators/JWTCreator.java | 6 +-- .../auth0/jwt/creators/RiscJwtCreator.java | 24 +++++---- .../auth0/jwt/creators/ScopedJwtCreator.java | 26 +++++----- .../jwt/interfaces/ExtendedVerification.java | 23 --------- .../java/com/auth0/jwt/jwts/AccessJWT.java | 2 +- .../java/com/auth0/jwt/jwts/ExtendedJWT.java | 2 +- .../main/java/com/auth0/jwt/jwts/FbJWT.java | 2 +- .../java/com/auth0/jwt/jwts/ImplicitJWT.java | 2 +- .../main/java/com/auth0/jwt/jwts/RiscJWT.java | 2 +- .../java/com/auth0/jwt/jwts/ScopedJWT.java | 2 +- .../VerificationAndAssertion.java | 8 +-- .../com/auth0/jwt/MainTestSignatures.java | 24 +++++---- .../jwt/algorithms/ECDSAAlgorithmTest.java | 49 ------------------- .../jwt/algorithms/HMACAlgorithmTest.java | 19 ------- .../jwt/algorithms/RSAAlgorithmTest.java | 30 ------------ .../jwt/creators/AccessJwtCreatorTest.java | 4 +- .../jwt/creators/GoogleJwtCreatorTest.java | 5 +- .../jwt/creators/ImplicitJwtCreatorTest.java | 4 +- .../auth0/jwt/creators/JWTCreatorTest.java | 4 +- .../jwt/creators/RiscJwtCreatorTest.java | 4 +- .../jwt/creators/ScopedJwtCreatorTest.java | 5 +- 28 files changed, 153 insertions(+), 243 deletions(-) create mode 100644 lib/src/main/java/com/auth0/jwt/creators/GoogleOrFbJwtCreator.java delete mode 100644 lib/src/main/java/com/auth0/jwt/interfaces/ExtendedVerification.java diff --git a/lib/src/main/java/com/auth0/jwt/JWTDecoder.java b/lib/src/main/java/com/auth0/jwt/JWTDecoder.java index 7a967fb..e655064 100644 --- a/lib/src/main/java/com/auth0/jwt/JWTDecoder.java +++ b/lib/src/main/java/com/auth0/jwt/JWTDecoder.java @@ -19,14 +19,15 @@ package com.auth0.jwt; -import com.auth0.jwt.creators.EncodeType; -import com.auth0.jwt.creators.JWTCreator; +import com.auth0.jwt.creators.*; import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.impl.JWTParser; +import com.auth0.jwt.impl.PublicClaims; 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 com.auth0.jwt.jwts.ExtendedJWT; import org.apache.commons.codec.binary.Base32; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; @@ -34,9 +35,7 @@ import java.net.URLDecoder; import java.net.URLEncoder; -import java.util.Date; -import java.util.List; -import java.util.Map; +import java.util.*; /** * The JWTDecoder class holds the decode method to parse a given JWT token into it's JWT representation. @@ -48,6 +47,19 @@ public final class JWTDecoder implements DecodedJWT { private final Header header; private final Payload payload; + private static final String NAME = "name"; + private static final String EMAIL = "email"; + private static final String PICTURE = "picture"; + private static final String ISSUER = "iss"; + private static final String AUDIENCE = "aud"; + private static final String SUBJECT = "sub"; + private static final String ISSUED_AT = "iat"; + private static final String EXP = "exp"; + private static final String APP_ID = "appId"; + private static final String USER_ID = "userId"; + private static final String FACEBOOK = "facebook"; + private static final String GOOGLE = "google"; + public JWTDecoder(String jwt, EncodeType encodeType) throws Exception { parts = TokenUtils.splitToken(jwt); final JWTParser converter = new JWTParser(); @@ -161,4 +173,31 @@ public String getSignature() { public String getToken() { return String.format("%s.%s.%s", parts[0], parts[1], parts[2]); } + + public static GoogleOrFbJwtCreator decodeJWT(DecodedJWT jwt) { + Map claims = jwt.getClaims(); + String issuer = claims.get(ISSUER).asString(); + GoogleOrFbJwtCreator googleOrFbJwtCreator = null; + if(issuer.contains(FACEBOOK)) { + googleOrFbJwtCreator = FbJwtCreator.build() + .withExp(claims.get(EXP).asDate()) + .withIat(claims.get(ISSUED_AT).asDate()) + .withAppId(claims.get(APP_ID).asString()) + .withUserId(claims.get(USER_ID).asString()); + } else if(issuer.contains(GOOGLE)) { + googleOrFbJwtCreator = GoogleJwtCreator.build() + .withPicture(claims.get(PICTURE).asString()) + .withEmail(claims.get(EMAIL).asString()) + .withIssuer(claims.get(ISSUER).asString()) + .withSubject(claims.get(SUBJECT).asString()) + .withAudience(claims.get(AUDIENCE).asString()) + .withExp(claims.get(EXP).asDate()) + .withIat(claims.get(ISSUED_AT).asDate()) + .withName(claims.get(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/creators/AccessJwtCreator.java b/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java index 4b126c4..88d4c4c 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java @@ -35,12 +35,12 @@ public class AccessJwtCreator { protected JWTCreator.Builder jwt; - protected HashMap addedClaims; + protected HashMap requiredClaims; protected Set publicClaims; public AccessJwtCreator() { jwt = JWT.create(); - addedClaims = new HashMap() {{ + requiredClaims = new HashMap() {{ put("Issuer", false); put("Subject", false); put("Iat", false); @@ -58,27 +58,25 @@ public 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); + requiredClaims.put("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); + requiredClaims.put("Subject", true); return this; } @@ -102,7 +100,7 @@ public AccessJwtCreator withAudience(String... audience) { */ public AccessJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - addedClaims.put("Iat", true); + requiredClaims.put("Iat", true); return this; } @@ -206,7 +204,7 @@ 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); + requiredClaims.put(name, true); return this; } @@ -281,8 +279,8 @@ public String signBase32Encoding(Algorithm algorithm) throws Exception { * @throws Exception if all the standard claims weren't provided */ private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) + for(String claim : requiredClaims.keySet()) + if(!requiredClaims.get(claim)) throw new Exception("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..5be743c 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ExtendedJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ExtendedJwtCreator.java @@ -103,8 +103,8 @@ public String signBase32Encoding(Algorithm algorithm) throws Exception { * @throws Exception if all the standard claims weren't provided */ private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) + for(String claim : requiredClaims.keySet()) + if(!requiredClaims.get(claim)) throw new Exception("Standard claim: " + claim + " has not been set"); } 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..fc63325 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/FbJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/FbJwtCreator.java @@ -32,15 +32,15 @@ /** * 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 { +public class FbJwtCreator extends GoogleOrFbJwtCreator { protected JWTCreator.Builder jwt; - protected HashMap addedClaims; + protected HashMap requiredClaims; protected Set publicClaims; public FbJwtCreator() { jwt = JWT.create(); - addedClaims = new HashMap() {{ + requiredClaims = new HashMap() {{ put("UserId", false); put("AppId", false); put("Iat", false); @@ -59,7 +59,7 @@ public FbJwtCreator() { */ public FbJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - addedClaims.put("Iat", true); + requiredClaims.put("Iat", true); return this; } @@ -82,7 +82,7 @@ public FbJwtCreator withExp(Date exp) { */ public FbJwtCreator withUserId(String userId) { jwt.withNonStandardClaim("userId", userId); - addedClaims.put("UserId", true); + requiredClaims.put("UserId", true); return this; } @@ -94,7 +94,7 @@ public FbJwtCreator withUserId(String userId) { */ public FbJwtCreator withAppId(String appId) { jwt.withNonStandardClaim("appId", appId); - addedClaims.put("AppId", true); + requiredClaims.put("AppId", true); return this; } @@ -187,7 +187,7 @@ 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); + requiredClaims.put(name, true); return this; } @@ -262,8 +262,8 @@ public String signBase32Encoding(Algorithm algorithm) throws Exception { * @throws Exception if all the standard claims weren't provided */ private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) + for(String claim : requiredClaims.keySet()) + if(!requiredClaims.get(claim)) throw new Exception("Standard claim: " + claim + " has not been set"); } 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..e5b0f01 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/GoogleJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/GoogleJwtCreator.java @@ -32,15 +32,15 @@ /** * 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 { +public class GoogleJwtCreator extends GoogleOrFbJwtCreator { protected JWTCreator.Builder jwt; - protected HashMap addedClaims; + protected HashMap requiredClaims; protected Set publicClaims; public GoogleJwtCreator() { jwt = JWT.create(); - addedClaims = new HashMap() {{ + requiredClaims = new HashMap() {{ put("Name", false); put("Email", false); put("Picture", false); @@ -68,7 +68,7 @@ public GoogleJwtCreator() { */ public GoogleJwtCreator withName(String name) { jwt.withNonStandardClaim("name", name); - addedClaims.put("Name", true); + requiredClaims.put("Name", true); return this; } @@ -80,7 +80,7 @@ public GoogleJwtCreator withName(String name) { */ public GoogleJwtCreator withEmail(String email) { jwt.withNonStandardClaim("email", email); - addedClaims.put("Email", true); + requiredClaims.put("Email", true); return this; } @@ -92,33 +92,31 @@ public GoogleJwtCreator withEmail(String email) { */ public GoogleJwtCreator withPicture(String picture) { jwt.withNonStandardClaim("picture", picture); - addedClaims.put("Picture", true); + requiredClaims.put("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); + requiredClaims.put("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); + requiredClaims.put("Subject", true); return this; } @@ -142,7 +140,7 @@ public GoogleJwtCreator withAudience(String... audience) { */ public GoogleJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - addedClaims.put("Iat", true); + requiredClaims.put("Iat", true); return this; } @@ -246,7 +244,7 @@ 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); + requiredClaims.put(name, true); return this; } @@ -321,8 +319,8 @@ public String signBase32Encoding(Algorithm algorithm) throws Exception { * @throws Exception if all the standard claims weren't provided */ private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) + for(String claim : requiredClaims.keySet()) + if(!requiredClaims.get(claim)) throw new Exception("Standard claim: " + claim + " has not been set"); } 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..cab2db8 --- /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 { +} 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..41821d6 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ImplicitJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ImplicitJwtCreator.java @@ -35,12 +35,12 @@ public class ImplicitJwtCreator { protected JWTCreator.Builder jwt; - protected HashMap addedClaims; + protected HashMap requiredClaims; protected Set publicClaims; public ImplicitJwtCreator() { jwt = JWT.create(); - addedClaims = new HashMap() {{ + requiredClaims = new HashMap() {{ put("Issuer", false); put("Subject", false); put("Iat", false); @@ -55,27 +55,25 @@ public 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); + requiredClaims.put("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); + requiredClaims.put("Subject", true); return this; } @@ -99,7 +97,7 @@ public ImplicitJwtCreator withAudience(String... audience) { */ public ImplicitJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - addedClaims.put("Iat", true); + requiredClaims.put("Iat", true); return this; } @@ -192,7 +190,7 @@ 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); + requiredClaims.put(name, true); return this; } @@ -267,8 +265,8 @@ public String signBase32Encoding(Algorithm algorithm) throws Exception { * @throws Exception if all the standard claims weren't provided */ private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) + for(String claim : requiredClaims.keySet()) + if(!requiredClaims.get(claim)) throw new Exception("Standard claim: " + claim + " has not been set"); } 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 33cc7d4..e6db884 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java @@ -115,24 +115,22 @@ public Builder withKeyId(String keyId) { /** * 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) { + public Builder withIssuer(String issuer) { addClaim(PublicClaims.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) { + public Builder withSubject(String subject) { addClaim(PublicClaims.SUBJECT, subject); return this; } 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..2fbe44c 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/RiscJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/RiscJwtCreator.java @@ -36,12 +36,12 @@ public class RiscJwtCreator { protected JWTCreator.Builder jwt; - protected HashMap addedClaims; + protected HashMap requiredClaims; protected Set publicClaims; public RiscJwtCreator() { jwt = JWT.create(); - addedClaims = new HashMap() {{ + requiredClaims = new HashMap() {{ put("Jti", false); put("Issuer", false); put("Subject", false); @@ -66,33 +66,31 @@ public RiscJwtCreator() { */ public RiscJwtCreator withJWTId(String jwtId) { jwt.withJWTId(jwtId); - addedClaims.put("Jti", true); + requiredClaims.put("Jti", 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); + requiredClaims.put("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); + requiredClaims.put("Subject", true); return this; } @@ -116,7 +114,7 @@ public RiscJwtCreator withAudience(String... audience) { */ public RiscJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - addedClaims.put("Iat", true); + requiredClaims.put("Iat", true); return this; } @@ -231,7 +229,7 @@ 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); + requiredClaims.put(name, true); return this; } @@ -306,8 +304,8 @@ public String signBase32Encoding(Algorithm algorithm) throws Exception { * @throws Exception if all the standard claims weren't provided */ private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) + for(String claim : requiredClaims.keySet()) + if(!requiredClaims.get(claim)) throw new Exception("Standard claim: " + claim + " has not been set"); } 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..3fc392e 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ScopedJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ScopedJwtCreator.java @@ -32,15 +32,15 @@ /** * 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{ +public class ScopedJwtCreator { protected JWTCreator.Builder jwt; - protected HashMap addedClaims; + protected HashMap requiredClaims; protected Set publicClaims; public ScopedJwtCreator() { jwt = JWT.create(); - addedClaims = new HashMap() {{ + requiredClaims = new HashMap() {{ put("Scope", false); put("Issuer", false); put("Subject", false); @@ -66,33 +66,31 @@ public ScopedJwtCreator() { */ public ScopedJwtCreator withScope(String scope) { jwt.withNonStandardClaim("scope", scope); - addedClaims.put("Scope", true); + requiredClaims.put("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); + requiredClaims.put("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); + requiredClaims.put("Subject", true); return this; } @@ -116,7 +114,7 @@ public ScopedJwtCreator withAudience(String... audience) { */ public ScopedJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - addedClaims.put("Iat", true); + requiredClaims.put("Iat", true); return this; } @@ -220,7 +218,7 @@ 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); + requiredClaims.put(name, true); return this; } @@ -295,8 +293,8 @@ public String signBase32Encoding(Algorithm algorithm) throws Exception { * @throws Exception if all the standard claims weren't provided */ private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) + for(String claim : requiredClaims.keySet()) + if(!requiredClaims.get(claim)) throw new Exception("Standard claim: " + claim + " has not been set"); } 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..99ad64a 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/FbJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/FbJWT.java @@ -24,7 +24,7 @@ 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); 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/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..69c4bd6 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/ScopedJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/ScopedJWT.java @@ -26,7 +26,7 @@ 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); 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..0f85ab4 100644 --- a/lib/src/main/java/com/auth0/jwt/verification/VerificationAndAssertion.java +++ b/lib/src/main/java/com/auth0/jwt/verification/VerificationAndAssertion.java @@ -137,14 +137,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 (expected == null || !expected.containsAll(actual)) { 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 (expected == null || !expected.contains(actual.get(0))) { throw new InvalidClaimException("The Claim 'iss' value doesn't match the required one."); } } diff --git a/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java b/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java index bc298eb..ffb13e2 100644 --- a/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java +++ b/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java @@ -90,26 +90,24 @@ 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")); + String issuer = claims.get(PublicClaims.ISSUER).asString(); + assertTrue(issuer.equals("issuer")); + String subject = claims.get(PublicClaims.SUBJECT).asString(); + assertTrue(subject.equals("subject")); List audience = claims.get(PublicClaims.AUDIENCE).asList(String.class); assertTrue(audience.get(0).equals("audience")); assertTrue(audience.get(1).equals("audience2")); @@ -127,12 +125,12 @@ public void testConfigurableToIncorrectNumberMultipleKeysForAudience() throws Ex 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"), @@ -150,12 +148,12 @@ public void testConfigurableToIncorrectValueMultipleKeysForAudience() throws Exc 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/algorithms/ECDSAAlgorithmTest.java b/lib/src/test/java/com/auth0/jwt/algorithms/ECDSAAlgorithmTest.java index ef3f917..97f54f7 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/ECDSAAlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/ECDSAAlgorithmTest.java @@ -85,7 +85,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 +99,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 +107,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 +120,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 +131,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 +145,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 +155,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 +167,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 +183,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 +197,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 +212,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 +221,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 +235,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 +243,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 +256,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 +267,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 +281,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 +291,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 +303,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 +317,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 +331,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 +346,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 +355,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 +369,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 +377,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 +390,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 +401,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 +415,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 +425,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 +437,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 +451,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 +465,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 +480,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 +500,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 +518,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 +536,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 +554,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 +575,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 +589,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 +608,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 +647,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 +661,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 +680,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 +719,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 +733,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 +753,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 +919,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 +934,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 +949,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/HMACAlgorithmTest.java b/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java index 043c8f7..7aee69a 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java @@ -64,8 +64,6 @@ public void shouldPassHMAC256Verification() throws Exception { 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,7 +84,6 @@ 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 @@ -97,8 +93,6 @@ public void shouldPassHMAC384Verification() throws Exception { 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 +103,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,7 +113,6 @@ 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 @@ -130,8 +122,6 @@ public void shouldPassHMAC512Verification() throws Exception { 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 +132,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 +142,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 +158,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 +182,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 +199,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 +216,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 +233,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 +250,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 +267,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..e8d9843 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/RSAAlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/RSAAlgorithmTest.java @@ -65,7 +65,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 +73,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 +84,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 +98,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 +108,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 +120,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 +128,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 +136,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 +147,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 +161,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 +171,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 +183,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 +191,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 +199,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 +210,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 +224,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 +234,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 +246,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 +264,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 +282,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 +300,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 +325,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 +342,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 +361,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 +403,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 +420,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 +439,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 +481,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 +498,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 +517,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..9c5405f 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java @@ -343,8 +343,8 @@ 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.ISSUER).asString().equals("issuer")); + assertTrue(claims.get(PublicClaims.SUBJECT).asString().equals("subject")); assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals("audience")); assertTrue(claims.get(PublicClaims.EXPIRES_AT).asDate().toString().equals(exp.toString())); } 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 5434fdd..dbd7622 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java @@ -19,6 +19,7 @@ package com.auth0.jwt.creators; +import com.auth0.jwt.JWTDecoder; import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; import com.auth0.jwt.algorithms.Algorithm; @@ -546,8 +547,8 @@ 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.ISSUER).asString().equals("issuer")); + assertTrue(claims.get(PublicClaims.SUBJECT).asString().equals("subject")); assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals("audience")); assertTrue(claims.get(PublicClaims.EXPIRES_AT).asDate().toString().equals(exp.toString())); assertTrue(claims.get(NAME).asString().equals(NAME)); 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..03bb217 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java @@ -318,8 +318,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.ISSUER).asString().equals("issuer")); + assertTrue(claims.get(PublicClaims.SUBJECT).asString().equals("subject")); assertTrue(claims.get(PublicClaims.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 43491d2..c4c5f0d 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java @@ -367,7 +367,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 @@ -377,7 +377,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 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..4f2074e 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/RiscJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/RiscJwtCreatorTest.java @@ -405,8 +405,8 @@ 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.ISSUER).asString().equals("issuer")); + assertTrue(claims.get(PublicClaims.SUBJECT).asString().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)); 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..e3faa28 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java @@ -19,6 +19,7 @@ package com.auth0.jwt.creators; +import com.auth0.jwt.JWTDecoder; import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; import com.auth0.jwt.algorithms.Algorithm; @@ -397,8 +398,8 @@ public void testScopedJwtCreatorExpTimeHasPassed() 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.ISSUER).asString().equals("issuer")); + assertTrue(claims.get(PublicClaims.SUBJECT).asString().equals("subject")); assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals("audience")); assertTrue(claims.get(PublicClaims.EXPIRES_AT).asDate().toString().equals(exp.toString())); } From 050e87d9fb300bd769357d54d98aad36730352cd Mon Sep 17 00:00:00 2001 From: Justin Dahmubed Date: Thu, 11 Jan 2018 11:36:09 -0800 Subject: [PATCH 4/5] Refactoring --- .../main/java/com/auth0/jwt/JWTDecoder.java | 42 ++++----- .../auth0/jwt/creators/AccessJwtCreator.java | 60 ++++++------- .../jwt/creators/ExtendedJwtCreator.java | 16 ++-- .../com/auth0/jwt/creators/FbJwtCreator.java | 59 ++++++------ .../auth0/jwt/creators/GoogleJwtCreator.java | 90 ++++++++++--------- .../jwt/creators/ImplicitJwtCreator.java | 57 ++++++------ .../com/auth0/jwt/creators/JWTCreator.java | 26 +++--- .../auth0/jwt/creators/RiscJwtCreator.java | 68 +++++++------- .../auth0/jwt/creators/ScopedJwtCreator.java | 70 ++++++++------- .../impl/{PublicClaims.java => Claims.java} | 10 ++- .../auth0/jwt/impl/HeaderDeserializer.java | 8 +- .../auth0/jwt/impl/PayloadDeserializer.java | 14 +-- .../com/auth0/jwt/impl/PayloadSerializer.java | 8 +- .../com/auth0/jwt/interfaces/Payload.java | 2 +- .../main/java/com/auth0/jwt/jwts/FbJWT.java | 9 +- .../java/com/auth0/jwt/jwts/GoogleJWT.java | 13 +-- lib/src/main/java/com/auth0/jwt/jwts/JWT.java | 43 ++++----- .../java/com/auth0/jwt/jwts/ScopedJWT.java | 5 +- .../com/auth0/jwt/{ => utils}/TokenUtils.java | 2 +- .../VerificationAndAssertion.java | 14 +-- .../java/com/auth0/jwt/JWTDecoderTest.java | 27 +++--- .../com/auth0/jwt/MainTestSignatures.java | 10 +-- .../java/com/auth0/jwt/TokenUtilsTest.java | 1 + .../jwt/creators/AccessJwtCreatorTest.java | 10 +-- .../jwt/creators/ExtendedJwtCreatorTest.java | 2 +- .../auth0/jwt/creators/FbJwtCreatorTest.java | 10 +-- .../jwt/creators/GoogleJwtCreatorTest.java | 18 ++-- .../jwt/creators/ImplicitJwtCreatorTest.java | 10 +-- .../auth0/jwt/creators/JWTCreatorTest.java | 21 ++--- .../jwt/creators/RiscJwtCreatorTest.java | 18 ++-- .../jwt/creators/ScopedJwtCreatorTest.java | 80 ++++++++--------- .../jwt/impl/HeaderDeserializerTest.java | 2 +- .../com/auth0/jwt/impl/JsonNodeClaimTest.java | 2 +- .../jwt/impl/PayloadDeserializerTest.java | 4 +- .../com/auth0/jwt/impl/PayloadImplTest.java | 2 +- .../auth0/jwt/impl/PayloadSerializerTest.java | 2 +- 36 files changed, 422 insertions(+), 413 deletions(-) rename lib/src/main/java/com/auth0/jwt/impl/{PublicClaims.java => Claims.java} (87%) rename lib/src/main/java/com/auth0/jwt/{ => utils}/TokenUtils.java (98%) diff --git a/lib/src/main/java/com/auth0/jwt/JWTDecoder.java b/lib/src/main/java/com/auth0/jwt/JWTDecoder.java index e655064..144ca19 100644 --- a/lib/src/main/java/com/auth0/jwt/JWTDecoder.java +++ b/lib/src/main/java/com/auth0/jwt/JWTDecoder.java @@ -20,21 +20,19 @@ package com.auth0.jwt; import com.auth0.jwt.creators.*; -import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.impl.JWTParser; -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.Header; import com.auth0.jwt.interfaces.Payload; -import com.auth0.jwt.jwts.ExtendedJWT; +import com.auth0.jwt.utils.TokenUtils; 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.net.URLEncoder; import java.util.*; /** @@ -47,16 +45,6 @@ public final class JWTDecoder implements DecodedJWT { private final Header header; private final Payload payload; - private static final String NAME = "name"; - private static final String EMAIL = "email"; - private static final String PICTURE = "picture"; - private static final String ISSUER = "iss"; - private static final String AUDIENCE = "aud"; - private static final String SUBJECT = "sub"; - private static final String ISSUED_AT = "iat"; - private static final String EXP = "exp"; - private static final String APP_ID = "appId"; - private static final String USER_ID = "userId"; private static final String FACEBOOK = "facebook"; private static final String GOOGLE = "google"; @@ -176,24 +164,24 @@ public String getToken() { public static GoogleOrFbJwtCreator decodeJWT(DecodedJWT jwt) { Map claims = jwt.getClaims(); - String issuer = claims.get(ISSUER).asString(); + String issuer = claims.get(Claims.ISSUER).asString(); GoogleOrFbJwtCreator googleOrFbJwtCreator = null; if(issuer.contains(FACEBOOK)) { googleOrFbJwtCreator = FbJwtCreator.build() - .withExp(claims.get(EXP).asDate()) - .withIat(claims.get(ISSUED_AT).asDate()) - .withAppId(claims.get(APP_ID).asString()) - .withUserId(claims.get(USER_ID).asString()); + .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.contains(GOOGLE)) { googleOrFbJwtCreator = GoogleJwtCreator.build() - .withPicture(claims.get(PICTURE).asString()) - .withEmail(claims.get(EMAIL).asString()) - .withIssuer(claims.get(ISSUER).asString()) - .withSubject(claims.get(SUBJECT).asString()) - .withAudience(claims.get(AUDIENCE).asString()) - .withExp(claims.get(EXP).asDate()) - .withIat(claims.get(ISSUED_AT).asDate()) - .withName(claims.get(NAME).asString()); + .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"); } 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 88d4c4c..b62f279 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java @@ -21,7 +21,7 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.jwts.JWT; import java.util.Date; @@ -36,47 +36,37 @@ public class AccessJwtCreator { protected JWTCreator.Builder jwt; protected HashMap requiredClaims; - protected Set publicClaims; - public AccessJwtCreator() { + private AccessJwtCreator() { jwt = JWT.create(); requiredClaims = 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); + put(Claims.ISSUER, false); + put(Claims.SUBJECT, false); + put(Claims.ISSUED_AT, false); }}; } /** - * Add a specific Issuer ("issuer") claim to the Payload. + * Add a specific Issuer (Claims.ISSUER) claim to the Payload. * * @param issuer the Issuer value. * @return this same Builder instance. */ public AccessJwtCreator withIssuer(String issuer) { jwt.withIssuer(issuer); - requiredClaims.put("Issuer", true); + requiredClaims.put(Claims.ISSUER, true); return this; } /** - * Add a specific Subject ("subject") claim to the Payload. + * Add a specific Subject (Claims.SUBJECT) claim to the Payload. * * @param subject the Subject value. * @return this same Builder instance. */ public AccessJwtCreator withSubject(String subject) { jwt.withSubject(subject); - requiredClaims.put("Subject", true); + requiredClaims.put(Claims.SUBJECT, true); return this; } @@ -93,14 +83,14 @@ public AccessJwtCreator withAudience(String... audience) { } /** - * Add a specific Issued At ("iat") claim to the Payload. + * Add a specific Issued At (Claims.ISSUED_AT) claim to the Payload. * * @param iat the Issued At value. * @return this same Builder instance. */ public AccessJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - requiredClaims.put("Iat", true); + requiredClaims.put(Claims.ISSUED_AT, true); return this; } @@ -124,7 +114,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(name.equalsIgnoreCase("subject") || name.equalsIgnoreCase(Claims.SUBJECT)) { + withSubject(value); + } else if(name.equalsIgnoreCase("issuer") || name.equalsIgnoreCase(Claims.ISSUER)) { + withIssuer(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -189,7 +185,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; } @@ -203,7 +203,7 @@ 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)) + if(requiredClaims.containsKey(name)) requiredClaims.put(name, true); return this; } @@ -230,11 +230,11 @@ public AccessJwtCreator setIsNoneAlgorithmAllowed(boolean isNoneAlgorithmAllowed * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm); verifyClaims(); + String JWS = jwt.sign(algorithm); return JWS; } @@ -248,11 +248,11 @@ public String sign(Algorithm algorithm) throws Exception { * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm, EncodeType.Base16); verifyClaims(); + String JWS = jwt.sign(algorithm, EncodeType.Base16); return JWS; } @@ -266,11 +266,11 @@ public String signBase16Encoding(Algorithm algorithm) throws Exception { * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm, EncodeType.Base32); verifyClaims(); + String JWS = jwt.sign(algorithm, EncodeType.Base32); return JWS; } 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 5be743c..51ca9b7 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ExtendedJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ExtendedJwtCreator.java @@ -29,7 +29,7 @@ */ public class ExtendedJwtCreator extends GoogleJwtCreator{ - public ExtendedJwtCreator() { + private ExtendedJwtCreator() { super(); } @@ -39,7 +39,7 @@ 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; } @@ -54,11 +54,11 @@ public GoogleJwtCreator withNbf(Date nbf) { * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm); verifyClaims(); + String JWS = jwt.sign(algorithm); return JWS; } @@ -72,11 +72,11 @@ public String sign(Algorithm algorithm) throws Exception { * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm, EncodeType.Base16); verifyClaims(); + String JWS = jwt.sign(algorithm, EncodeType.Base16); return JWS; } @@ -90,11 +90,11 @@ public String signBase16Encoding(Algorithm algorithm) throws Exception { * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm, EncodeType.Base32); verifyClaims(); + String JWS = jwt.sign(algorithm, EncodeType.Base32); return JWS; } 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 fc63325..14b2f2d 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/FbJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/FbJwtCreator.java @@ -21,7 +21,7 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.jwts.JWT; import java.util.Date; @@ -36,30 +36,25 @@ public class FbJwtCreator extends GoogleOrFbJwtCreator { protected JWTCreator.Builder jwt; protected HashMap requiredClaims; - protected Set publicClaims; - public FbJwtCreator() { + private FbJwtCreator() { jwt = JWT.create(); requiredClaims = new HashMap() {{ - put("UserId", false); - put("AppId", false); - put("Iat", false); - }}; - publicClaims = new HashSet() {{ - add(PublicClaims.ISSUED_AT); - add(PublicClaims.EXPIRES_AT); + put(Claims.USER_ID, false); + put(Claims.APP_ID, false); + put(Claims.ISSUED_AT, false); }}; } /** - * Add a specific Issued At ("iat") claim to the Payload. + * Add a specific Issued At (Claims.ISSUED_AT) claim to the Payload. * * @param iat the Issued At value. * @return this same Builder instance. */ public FbJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - requiredClaims.put("Iat", true); + requiredClaims.put(Claims.ISSUED_AT, true); return this; } @@ -75,26 +70,26 @@ public FbJwtCreator withExp(Date exp) { } /** - * Require a specific userId ("userId") claim. + * Require a specific userId (Claims.USER_ID) claim. * * @param userId the required userId value * @return this same Verification instance. */ public FbJwtCreator withUserId(String userId) { - jwt.withNonStandardClaim("userId", userId); - requiredClaims.put("UserId", true); + jwt.withNonStandardClaim(Claims.USER_ID, userId); + requiredClaims.put(Claims.USER_ID, true); return this; } /** - * Require a specific appId ("appId") claim. + * Require a specific appId (Claims.APP_ID) claim. * * @param appId the required appId value * @return this same Verification instance. */ public FbJwtCreator withAppId(String appId) { - jwt.withNonStandardClaim("appId", appId); - requiredClaims.put("AppId", true); + jwt.withNonStandardClaim(Claims.APP_ID, appId); + requiredClaims.put(Claims.APP_ID, true); return this; } @@ -107,7 +102,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(name.equalsIgnoreCase(Claims.USER_ID) || name.equalsIgnoreCase("user_id")) { + withUserId(value); + } else if(name.equalsIgnoreCase(Claims.APP_ID) || name.equalsIgnoreCase("app_id")) { + withAppId(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -172,7 +173,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(name.equalsIgnoreCase(Claims.ISSUED_AT) || name.equalsIgnoreCase("issuedAt") || name.equalsIgnoreCase("issued_at")) { + withIat(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -186,7 +191,7 @@ 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)) + if(requiredClaims.containsKey(name)) requiredClaims.put(name, true); return this; } @@ -213,11 +218,11 @@ public FbJwtCreator setIsNoneAlgorithmAllowed(boolean isNoneAlgorithmAllowed) { * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm); verifyClaims(); + String JWS = jwt.sign(algorithm); return JWS; } @@ -231,11 +236,11 @@ public String sign(Algorithm algorithm) throws Exception { * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm, EncodeType.Base16); verifyClaims(); + String JWS = jwt.sign(algorithm, EncodeType.Base16); return JWS; } @@ -249,11 +254,11 @@ public String signBase16Encoding(Algorithm algorithm) throws Exception { * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm, EncodeType.Base32); verifyClaims(); + String JWS = jwt.sign(algorithm, EncodeType.Base32); return JWS; } 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 e5b0f01..7116943 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/GoogleJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/GoogleJwtCreator.java @@ -21,7 +21,7 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.jwts.JWT; import java.util.Date; @@ -36,87 +36,77 @@ public class GoogleJwtCreator extends GoogleOrFbJwtCreator { protected JWTCreator.Builder jwt; protected HashMap requiredClaims; - protected Set publicClaims; - public GoogleJwtCreator() { + protected GoogleJwtCreator() { jwt = JWT.create(); requiredClaims = 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); + 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); }}; } /** - * Add a specific Name ("name") claim to the Payload. + * Add a specific Name (Claims.NAME) claim to the Payload. * * @param name the Name value. * @return this same Builder instance. */ public GoogleJwtCreator withName(String name) { - jwt.withNonStandardClaim("name", name); - requiredClaims.put("Name", true); + jwt.withNonStandardClaim(Claims.NAME, name); + requiredClaims.put(Claims.NAME, true); return this; } /** - * Add a specific Email ("email") claim to the Payload. + * Add a specific Email (Claims.EMAIL) claim to the Payload. * * @param email the Email value. * @return this same Builder instance. */ public GoogleJwtCreator withEmail(String email) { - jwt.withNonStandardClaim("email", email); - requiredClaims.put("Email", true); + jwt.withNonStandardClaim(Claims.EMAIL, email); + requiredClaims.put(Claims.EMAIL, true); return this; } /** - * Add a specific Picture ("picture") claim to the Payload. + * Add a specific Picture (Claims.PICTURE) claim to the Payload. * * @param picture the Picture value. * @return this same Builder instance. */ public GoogleJwtCreator withPicture(String picture) { - jwt.withNonStandardClaim("picture", picture); - requiredClaims.put("Picture", true); + jwt.withNonStandardClaim(Claims.PICTURE, picture); + requiredClaims.put(Claims.PICTURE, true); return this; } /** - * Add a specific Issuer ("issuer") claim to the Payload. + * Add a specific Issuer (Claims.ISSUER) claim to the Payload. * * @param issuer the Issuer value. * @return this same Builder instance. */ public GoogleJwtCreator withIssuer(String issuer) { jwt.withIssuer(issuer); - requiredClaims.put("Issuer", true); + requiredClaims.put(Claims.ISSUER, true); return this; } /** - * Add a specific Subject ("subject") claim to the Payload. + * Add a specific Subject (Claims.SUBJECT) claim to the Payload. * * @param subject the Subject value. * @return this same Builder instance. */ public GoogleJwtCreator withSubject(String subject) { jwt.withSubject(subject); - requiredClaims.put("Subject", true); + requiredClaims.put(Claims.SUBJECT, true); return this; } @@ -133,14 +123,14 @@ public GoogleJwtCreator withAudience(String... audience) { } /** - * Add a specific Issued At ("iat") claim to the Payload. + * Add a specific Issued At (Claims.ISSUED_AT) claim to the Payload. * * @param iat the Issued At value. * @return this same Builder instance. */ public GoogleJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - requiredClaims.put("Iat", true); + requiredClaims.put(Claims.ISSUED_AT, true); return this; } @@ -164,7 +154,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(value.equalsIgnoreCase(Claims.NAME)) { + withName(value); + } else if(value.equalsIgnoreCase(Claims.EMAIL)) { + withEmail(value); + } else if(value.equalsIgnoreCase(Claims.PICTURE)) { + withPicture(value); + } else if(value.equalsIgnoreCase(Claims.ISSUER) || value.equalsIgnoreCase("issuer")) { + withIssuer(value); + } else if(name.equalsIgnoreCase("subject") || name.equalsIgnoreCase(Claims.SUBJECT)) { + withSubject(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -229,7 +231,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(name.equalsIgnoreCase(Claims.ISSUED_AT) || name.equalsIgnoreCase("issuedAt") || name.equalsIgnoreCase("issued_at")) { + withIat(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -243,7 +249,7 @@ 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)) + if(requiredClaims.containsKey(name)) requiredClaims.put(name, true); return this; } @@ -270,11 +276,11 @@ public GoogleJwtCreator setIsNoneAlgorithmAllowed(boolean isNoneAlgorithmAllowed * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm); verifyClaims(); + String JWS = jwt.sign(algorithm); return JWS; } @@ -288,11 +294,11 @@ public String sign(Algorithm algorithm) throws Exception { * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm, EncodeType.Base16); verifyClaims(); + String JWS = jwt.sign(algorithm, EncodeType.Base16); return JWS; } @@ -306,11 +312,11 @@ public String signBase16Encoding(Algorithm algorithm) throws Exception { * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm, EncodeType.Base32); verifyClaims(); + String JWS = jwt.sign(algorithm, EncodeType.Base32); return JWS; } 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 41821d6..b71b83c 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ImplicitJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ImplicitJwtCreator.java @@ -21,7 +21,7 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.jwts.JWT; import java.util.Date; @@ -36,44 +36,37 @@ public class ImplicitJwtCreator { protected JWTCreator.Builder jwt; protected HashMap requiredClaims; - protected Set publicClaims; - public ImplicitJwtCreator() { + private ImplicitJwtCreator() { jwt = JWT.create(); requiredClaims = 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); + put(Claims.ISSUER, false); + put(Claims.SUBJECT, false); + put(Claims.ISSUED_AT, false); }}; } /** - * Add a specific Issuer ("issuer") claim to the Payload. + * Add a specific Issuer (Claims.ISSUER) claim to the Payload. * * @param issuer the Issuer value. * @return this same Builder instance. */ public ImplicitJwtCreator withIssuer(String issuer) { jwt.withIssuer(issuer); - requiredClaims.put("Issuer", true); + requiredClaims.put(Claims.ISSUER, true); return this; } /** - * Add a specific Subject ("subject") claim to the Payload. + * Add a specific Subject (Claims.SUBJECT) claim to the Payload. * * @param subject the Subject value. * @return this same Builder instance. */ public ImplicitJwtCreator withSubject(String subject) { jwt.withSubject(subject); - requiredClaims.put("Subject", true); + requiredClaims.put(Claims.SUBJECT, true); return this; } @@ -90,14 +83,14 @@ public ImplicitJwtCreator withAudience(String... audience) { } /** - * Add a specific Issued At ("iat") claim to the Payload. + * Add a specific Issued At (Claims.ISSUED_AT) claim to the Payload. * * @param iat the Issued At value. * @return this same Builder instance. */ public ImplicitJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - requiredClaims.put("Iat", true); + requiredClaims.put(Claims.ISSUED_AT, true); return this; } @@ -110,7 +103,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(name.equalsIgnoreCase("subject") || name.equalsIgnoreCase(Claims.SUBJECT)) { + withSubject(value); + } else if(name.equalsIgnoreCase("issuer") || name.equalsIgnoreCase(Claims.ISSUER)) { + withIssuer(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -175,7 +174,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(name.equalsIgnoreCase(Claims.ISSUED_AT) || name.equalsIgnoreCase("issuedAt") || name.equalsIgnoreCase("issued_at")) { + withIat(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -189,7 +192,7 @@ 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)) + if(requiredClaims.containsKey(name)) requiredClaims.put(name, true); return this; } @@ -216,11 +219,11 @@ public ImplicitJwtCreator setIsNoneAlgorithmAllowed(boolean isNoneAlgorithmAllow * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm); verifyClaims(); + String JWS = jwt.sign(algorithm); return JWS; } @@ -234,11 +237,11 @@ public String sign(Algorithm algorithm) throws Exception { * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm, EncodeType.Base16); verifyClaims(); + String JWS = jwt.sign(algorithm, EncodeType.Base16); return JWS; } @@ -252,11 +255,11 @@ public String signBase16Encoding(Algorithm algorithm) throws Exception { * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm, EncodeType.Base32); verifyClaims(); + String JWS = jwt.sign(algorithm, EncodeType.Base32); return JWS; } 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 e6db884..1d6c2f0 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java @@ -24,7 +24,7 @@ import com.auth0.jwt.exceptions.SignatureGenerationException; import com.auth0.jwt.impl.ClaimsHolder; import com.auth0.jwt.impl.PayloadSerializer; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.impl.Claims; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; @@ -109,7 +109,7 @@ 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; } @@ -120,7 +120,7 @@ public Builder withKeyId(String keyId) { * @return this same Builder instance. */ public Builder withIssuer(String issuer) { - addClaim(PublicClaims.ISSUER, issuer); + addClaim(Claims.ISSUER, issuer); return this; } @@ -131,7 +131,7 @@ public Builder withIssuer(String issuer) { * @return this same Builder instance. */ public Builder withSubject(String subject) { - addClaim(PublicClaims.SUBJECT, subject); + addClaim(Claims.SUBJECT, subject); return this; } @@ -143,7 +143,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; } @@ -154,7 +154,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; } @@ -165,29 +165,29 @@ 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; } /** - * Add a specific Issued At ("iat") claim to the Payload. + * Add a specific Issued At (Claims.ISSUED_AT) claim to the Payload. * * @param issuedAt the Issued At value. * @return this same Builder instance. */ public Builder withIssuedAt(Date issuedAt) { - addClaim(PublicClaims.ISSUED_AT, issuedAt); + addClaim(Claims.ISSUED_AT, issuedAt); return this; } /** - * Add a specific JWT Id ("jti") claim to the Payload. + * Add a specific JWT Id (Claims.JWT_ID) claim to the Payload. * * @param jwtId the Token Id value. * @return this same Builder instance. */ public Builder withJWTId(String jwtId) { - addClaim(PublicClaims.JWT_ID, jwtId); + addClaim(Claims.JWT_ID, jwtId); return this; } @@ -362,8 +362,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); 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 2fbe44c..ee9eaf2 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/RiscJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/RiscJwtCreator.java @@ -21,7 +21,7 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.interfaces.Verification; import com.auth0.jwt.jwts.JWT; @@ -37,60 +37,50 @@ public class RiscJwtCreator { protected JWTCreator.Builder jwt; protected HashMap requiredClaims; - protected Set publicClaims; - public RiscJwtCreator() { + private RiscJwtCreator() { jwt = JWT.create(); requiredClaims = 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); + put(Claims.JWT_ID, false); + put(Claims.ISSUER, false); + put(Claims.SUBJECT, false); + put(Claims.ISSUED_AT, false); }}; } /** - * Require a specific JWT Id ("jti") claim. + * Require a specific JWT Id (Claims.JWT_ID) claim. * * @param jwtId the required Id value * @return this same Verification instance. */ public RiscJwtCreator withJWTId(String jwtId) { jwt.withJWTId(jwtId); - requiredClaims.put("Jti", true); + requiredClaims.put(Claims.JWT_ID, true); return this; } /** - * Add a specific Issuer ("issuer") claim to the Payload. + * Add a specific Issuer (Claims.ISSUER) claim to the Payload. * * @param issuer the Issuer value. * @return this same Builder instance. */ public RiscJwtCreator withIssuer(String issuer) { jwt.withIssuer(issuer); - requiredClaims.put("Issuer", true); + requiredClaims.put(Claims.ISSUER, true); return this; } /** - * Add a specific Subject ("subject") claim to the Payload. + * Add a specific Subject (Claims.SUBJECT) claim to the Payload. * * @param subject the Subject value. * @return this same Builder instance. */ public RiscJwtCreator withSubject(String subject) { jwt.withSubject(subject); - requiredClaims.put("Subject", true); + requiredClaims.put(Claims.SUBJECT, true); return this; } @@ -107,14 +97,14 @@ public RiscJwtCreator withAudience(String... audience) { } /** - * Add a specific Issued At ("iat") claim to the Payload. + * Add a specific Issued At (Claims.ISSUED_AT) claim to the Payload. * * @param iat the Issued At value. * @return this same Builder instance. */ public RiscJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - requiredClaims.put("Iat", true); + requiredClaims.put(Claims.ISSUED_AT, true); return this; } @@ -149,7 +139,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(name.equalsIgnoreCase("subject") || name.equalsIgnoreCase(Claims.SUBJECT)) { + withSubject(value); + } else if(name.equalsIgnoreCase("issuer") || name.equalsIgnoreCase(Claims.ISSUER)) { + withIssuer(value); + } else if(name.equalsIgnoreCase(Claims.JWT_ID) || name.equalsIgnoreCase("jwtId") || name.equalsIgnoreCase("jwt_id")) { + withJWTId(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -214,7 +212,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(name.equalsIgnoreCase(Claims.ISSUED_AT) || name.equalsIgnoreCase("issuedAt") || name.equalsIgnoreCase("issued_at")) { + withIat(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -228,7 +230,7 @@ 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)) + if(requiredClaims.containsKey(name)) requiredClaims.put(name, true); return this; } @@ -255,11 +257,11 @@ public RiscJwtCreator setIsNoneAlgorithmAllowed(boolean isNoneAlgorithmAllowed) * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm); verifyClaims(); + String JWS = jwt.sign(algorithm); return JWS; } @@ -273,11 +275,11 @@ public String sign(Algorithm algorithm) throws Exception { * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm, EncodeType.Base16); verifyClaims(); + String JWS = jwt.sign(algorithm, EncodeType.Base16); return JWS; } @@ -291,11 +293,11 @@ public String signBase16Encoding(Algorithm algorithm) throws Exception { * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm, EncodeType.Base32); verifyClaims(); + String JWS = jwt.sign(algorithm, EncodeType.Base32); return JWS; } 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 3fc392e..479b6b0 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ScopedJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ScopedJwtCreator.java @@ -21,7 +21,7 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.impl.Claims; import com.auth0.jwt.jwts.JWT; import java.util.Date; @@ -36,61 +36,51 @@ public class ScopedJwtCreator { protected JWTCreator.Builder jwt; protected HashMap requiredClaims; - protected Set publicClaims; - public ScopedJwtCreator() { + private ScopedJwtCreator() { jwt = JWT.create(); requiredClaims = 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); + put(Claims.SCOPE, false); + put(Claims.ISSUER, false); + put(Claims.SUBJECT, false); + put(Claims.ISSUED_AT, false); }}; } /** - * Add a specific Scope ("scope") claim to the Payload. + * Add a specific Scope (Claims.SCOPE) claim to the Payload. * Allows for multiple issuers * * @param scope the Scope value. * @return this same Builder instance. */ public ScopedJwtCreator withScope(String scope) { - jwt.withNonStandardClaim("scope", scope); - requiredClaims.put("Scope", true); + jwt.withNonStandardClaim(Claims.SCOPE, scope); + requiredClaims.put(Claims.SCOPE, true); return this; } /** - * Add a specific Issuer ("issuer") claim to the Payload. + * Add a specific Issuer (Claims.ISSUER) claim to the Payload. * * @param issuer the Issuer value. * @return this same Builder instance. */ public ScopedJwtCreator withIssuer(String issuer) { jwt.withIssuer(issuer); - requiredClaims.put("Issuer", true); + requiredClaims.put(Claims.ISSUER, true); return this; } /** - * Add a specific Subject ("subject") claim to the Payload. + * Add a specific Subject (Claims.SUBJECT) claim to the Payload. * * @param subject the Subject value. * @return this same Builder instance. */ public ScopedJwtCreator withSubject(String subject) { jwt.withSubject(subject); - requiredClaims.put("Subject", true); + requiredClaims.put(Claims.SUBJECT, true); return this; } @@ -107,14 +97,14 @@ public ScopedJwtCreator withAudience(String... audience) { } /** - * Add a specific Issued At ("iat") claim to the Payload. + * Add a specific Issued At (Claims.ISSUED_AT) claim to the Payload. * * @param iat the Issued At value. * @return this same Builder instance. */ public ScopedJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - requiredClaims.put("Iat", true); + requiredClaims.put(Claims.ISSUED_AT, true); return this; } @@ -138,7 +128,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(name.equalsIgnoreCase("subject") || name.equalsIgnoreCase(Claims.SUBJECT)) { + withSubject(value); + } else if(name.equalsIgnoreCase("issuer") || name.equalsIgnoreCase(Claims.ISSUER)) { + withIssuer(value); + } else if(name.equalsIgnoreCase(Claims.SCOPE)) { + withScope(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -203,7 +201,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(name.equalsIgnoreCase(Claims.ISSUED_AT) || name.equalsIgnoreCase("issuedAt") || name.equalsIgnoreCase("issued_at")) { + withIat(value); + } else { + jwt.withNonStandardClaim(name, value); + } return this; } @@ -217,7 +219,7 @@ 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)) + if(requiredClaims.containsKey(name)) requiredClaims.put(name, true); return this; } @@ -244,11 +246,11 @@ public ScopedJwtCreator setIsNoneAlgorithmAllowed(boolean isNoneAlgorithmAllowed * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm); verifyClaims(); + String JWS = jwt.sign(algorithm); return JWS; } @@ -262,11 +264,11 @@ public String sign(Algorithm algorithm) throws Exception { * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm, EncodeType.Base16); verifyClaims(); + String JWS = jwt.sign(algorithm, EncodeType.Base16); return JWS; } @@ -280,11 +282,11 @@ public String signBase16Encoding(Algorithm algorithm) throws Exception { * @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())) { + if(!jwt.getIsNoneAlgorithmAllowed() && Algorithm.none().equals(algorithm)) { throw new IllegalAccessException("None algorithm isn't allowed"); } - String JWS = jwt.sign(algorithm, EncodeType.Base32); verifyClaims(); + String JWS = jwt.sign(algorithm, EncodeType.Base32); return JWS; } 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..be61aef 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/PayloadDeserializer.java +++ b/lib/src/main/java/com/auth0/jwt/impl/PayloadDeserializer.java @@ -50,13 +50,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/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/Payload.java b/lib/src/main/java/com/auth0/jwt/interfaces/Payload.java index d9a4e00..c4afdf2 100644 --- a/lib/src/main/java/com/auth0/jwt/interfaces/Payload.java +++ b/lib/src/main/java/com/auth0/jwt/interfaces/Payload.java @@ -71,7 +71,7 @@ public interface Payload { Date getIssuedAt(); /** - * Get the value of the "jti" claim, or null if it's not available. + * Get the value of the Claims.JWT_ID claim, or null if it's not available. * * @return the JWT ID value or null. */ 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 99ad64a..34dfd69 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/FbJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/FbJWT.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.Verification; @@ -41,24 +42,24 @@ public Verification createVerifierForFb(String userId, String appId) { } /** - * Require a specific userId ("userId") claim. + * Require a specific userId (Claims.USER_ID) claim. * * @param userId the required userId value * @return this same Verification instance. */ public Verification withUserId(String userId) { - requireClaim("userId", userId); + requireClaim(Claims.USER_ID, userId); return this; } /** - * Require a specific appId ("appId") claim. + * Require a specific appId (Claims.APP_ID) claim. * * @param appId the required appId value * @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 755fad0..9798e9f 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; @@ -49,38 +50,38 @@ public Verification createVerifierForGoogle(String picture, String email, List issuer, List au */ @Override public Verification withIssuer(String... issuer) { - requireClaim(PublicClaims.ISSUER, Arrays.asList(issuer)); + requireClaim(Claims.ISSUER, Arrays.asList(issuer)); return this; } @@ -280,7 +269,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; } @@ -293,7 +282,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; } @@ -323,7 +312,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; } @@ -338,7 +327,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; } @@ -353,19 +342,19 @@ 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; } /** - * Require a specific JWT Id ("jti") claim. + * Require a specific JWT Id (Claims.JWT_ID) claim. * * @param jwtId the required Id value * @return this same Verification instance. */ @Override public Verification withJWTId(String jwtId) { - requireClaim(PublicClaims.JWT_ID, jwtId); + requireClaim(Claims.JWT_ID, jwtId); return this; } @@ -512,14 +501,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); } } 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 69c4bd6..97af68a 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/ScopedJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/ScopedJWT.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.Verification; @@ -46,13 +47,13 @@ public Verification createVerifierForScoped(String scope, List issuer, } /** - * Require a specific Scope ("scope") claim. + * Require a specific Scope (Claims.SCOPE) claim. * * @param scope the required Scope value * @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 0f85ab4..979bc47 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,23 +56,23 @@ 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: + case Claims.AUDIENCE: //noinspection unchecked VerificationAndAssertion.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: + case Claims.ISSUER: VerificationAndAssertion.assertValidIssuerClaim(jwt.getIssuer(), (List) entry.getValue()); break; - case PublicClaims.JWT_ID: + case Claims.JWT_ID: VerificationAndAssertion.assertValidStringClaim(entry.getKey(), jwt.getId(), (String) entry.getValue()); break; default: diff --git a/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java b/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java index 8ff3844..7ceecb2 100644 --- a/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java +++ b/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java @@ -21,6 +21,7 @@ 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; @@ -48,7 +49,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 +60,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 +68,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 +129,7 @@ public void shouldGetSignature() throws Exception { assertThat(decodedJWT.getSignature(), is("XmNK3GpH3Ys_7wsYBfq4C3M6goz71I7dTgUkuIa5lyQ")); } - // Public PublicClaims + // Public Claims @Test public void shouldGetIssuer() throws Exception { @@ -243,7 +244,7 @@ public void shouldGetAlgorithm() throws Exception { assertThat(decodedJWT.getAlgorithm(), is("HS256")); } - //Private PublicClaims + //Private Claims @Test @@ -273,7 +274,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 +283,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 +292,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 +302,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 +311,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 +320,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 +329,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 +347,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/MainTestSignatures.java b/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java index ffb13e2..0b6f8ef 100644 --- a/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java +++ b/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java @@ -25,7 +25,7 @@ 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; @@ -104,14 +104,14 @@ public void testConfigurableToMultipleKeys() throws Exception { Map claims = jwt.getClaims(); assertTrue(claims.get(GoogleJwtCreatorTest.PICTURE).asString().equals(GoogleJwtCreatorTest.PICTURE)); assertTrue(claims.get(GoogleJwtCreatorTest.EMAIL).asString().equals(GoogleJwtCreatorTest.EMAIL)); - String issuer = claims.get(PublicClaims.ISSUER).asString(); + String issuer = claims.get(Claims.ISSUER).asString(); assertTrue(issuer.equals("issuer")); - String subject = claims.get(PublicClaims.SUBJECT).asString(); + String subject = claims.get(Claims.SUBJECT).asString(); assertTrue(subject.equals("subject")); - List audience = claims.get(PublicClaims.AUDIENCE).asList(String.class); + 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)); } diff --git a/lib/src/test/java/com/auth0/jwt/TokenUtilsTest.java b/lib/src/test/java/com/auth0/jwt/TokenUtilsTest.java index c0f375e..9468ddf 100644 --- a/lib/src/test/java/com/auth0/jwt/TokenUtilsTest.java +++ b/lib/src/test/java/com/auth0/jwt/TokenUtilsTest.java @@ -20,6 +20,7 @@ package com.auth0.jwt; 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; 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 9c5405f..c7475d4 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java @@ -24,7 +24,7 @@ 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; @@ -343,9 +343,9 @@ public void testAccessJwtCreatorExpTimeHasPassed() throws Exception { } private static void verifyClaims(Map claims, Date exp) { - assertTrue(claims.get(PublicClaims.ISSUER).asString().equals("issuer")); - assertTrue(claims.get(PublicClaims.SUBJECT).asString().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..12212a9 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ExtendedJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ExtendedJwtCreatorTest.java @@ -25,7 +25,7 @@ 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.GoogleVerification; 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..81d7ddb 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/FbJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/FbJwtCreatorTest.java @@ -25,7 +25,7 @@ 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; @@ -45,8 +45,8 @@ public class FbJwtCreatorTest { public ExpectedException thrown = ExpectedException.none(); private static final Date exp = generateRandomExpDateInFuture(); private static final Date iat = generateRandomIatDateInPast(); - private static final String USER_ID = "userId"; - private static final String APP_ID = "appId"; + private static final String USER_ID = Claims.USER_ID; + private static final String APP_ID = Claims.APP_ID; @Test public void testFbJwtCreatorAllStandardClaimsMustBeRequired() throws Exception { @@ -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 dbd7622..31d8c92 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java @@ -26,7 +26,7 @@ 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; @@ -48,9 +48,9 @@ public class GoogleJwtCreatorTest { public ExpectedException thrown = ExpectedException.none(); private static final Date exp = generateRandomExpDateInFuture(); private static final Date iat = generateRandomIatDateInPast(); - public static final String PICTURE = "picture"; - public static final String EMAIL = "email"; - public static final String NAME = "name"; + public static final String PICTURE = Claims.PICTURE; + public static final String EMAIL = Claims.EMAIL; + public static final String NAME = Claims.NAME; @Test @@ -119,7 +119,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() @@ -547,10 +547,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).asString().equals("issuer")); - assertTrue(claims.get(PublicClaims.SUBJECT).asString().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 03bb217..40e28be 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java @@ -23,7 +23,7 @@ import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; import com.auth0.jwt.algorithms.Algorithm; 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.Verification; @@ -131,7 +131,7 @@ 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.expectMessage("Standard claim: iss has not been set"); Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ImplicitJwtCreator.build() .withSubject("subject") @@ -318,8 +318,8 @@ public void testImplicitJwtCreatorNonStandardClaimDateValue() throws Exception { } private static void verifyClaims(Map claims) { - assertTrue(claims.get(PublicClaims.ISSUER).asString().equals("issuer")); - assertTrue(claims.get(PublicClaims.SUBJECT).asString().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 c4c5f0d..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,9 +21,10 @@ 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.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; @@ -490,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())); @@ -501,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())); @@ -512,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())); @@ -523,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())); @@ -534,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())); @@ -546,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())); @@ -557,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())); @@ -568,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())); @@ -579,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 4f2074e..7e7d4b2 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/RiscJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/RiscJwtCreatorTest.java @@ -24,7 +24,7 @@ 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; @@ -46,7 +46,7 @@ public class RiscJwtCreatorTest { private static final Date exp = generateRandomExpDateInFuture(); private static final Date iat = generateRandomIatDateInPast(); private static final Date nbf = iat; - private static final String jti = "jti"; + private static final String jti = Claims.JWT_ID; @Test public void testRiscJwtCreatorAllStandardClaimsMustBeRequired() throws Exception { @@ -108,7 +108,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 +129,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 +405,10 @@ public void testRiscJwtCreatorExpTimeHasPassed() throws Exception { } private static void verifyClaims(Map claims, Date exp) { - assertTrue(claims.get(PublicClaims.ISSUER).asString().equals("issuer")); - assertTrue(claims.get(PublicClaims.SUBJECT).asString().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 e3faa28..f8319ce 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java @@ -26,7 +26,7 @@ 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; @@ -53,7 +53,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") @@ -61,7 +61,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); @@ -71,7 +71,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") @@ -79,7 +79,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); @@ -89,7 +89,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") @@ -97,7 +97,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); @@ -117,7 +117,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); } @@ -127,7 +127,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") @@ -135,7 +135,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); } @@ -145,7 +145,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") @@ -153,14 +153,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") @@ -170,7 +170,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); @@ -183,7 +183,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") @@ -193,7 +193,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); } @@ -204,7 +204,7 @@ public void testScopedJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() th Algorithm algorithm = Algorithm.none(); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Claims.SCOPE) .withIssuer("issuer") .withSubject("subject") .withAudience("audience") @@ -213,7 +213,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); } @@ -221,7 +221,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") @@ -230,7 +230,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); @@ -240,7 +240,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") @@ -249,7 +249,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); @@ -259,7 +259,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") @@ -268,7 +268,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); @@ -278,7 +278,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") @@ -287,7 +287,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); @@ -297,7 +297,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") @@ -306,7 +306,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); @@ -316,7 +316,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") @@ -325,7 +325,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); @@ -335,7 +335,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") @@ -344,7 +344,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); @@ -354,7 +354,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") @@ -363,7 +363,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); @@ -382,7 +382,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") @@ -391,16 +391,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).asString().equals("issuer")); - assertTrue(claims.get(PublicClaims.SUBJECT).asString().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/HeaderDeserializerTest.java b/lib/src/test/java/com/auth0/jwt/impl/HeaderDeserializerTest.java index 63c72a7..bbaef88 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/HeaderDeserializerTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/HeaderDeserializerTest.java @@ -77,7 +77,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/JsonNodeClaimTest.java b/lib/src/test/java/com/auth0/jwt/impl/JsonNodeClaimTest.java index 2e755d6..dc6a418 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/JsonNodeClaimTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/JsonNodeClaimTest.java @@ -328,7 +328,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..8bae87e 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/PayloadDeserializerTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/PayloadDeserializerTest.java @@ -91,7 +91,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 +125,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..83e5b30 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/PayloadImplTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/PayloadImplTest.java @@ -195,6 +195,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..d5d7cdb 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/PayloadSerializerTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/PayloadSerializerTest.java @@ -157,7 +157,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(); From 29fc485aaa72a3e545afa93be1f2c12c81ec268d Mon Sep 17 00:00:00 2001 From: Justin Dahmubed Date: Thu, 1 Mar 2018 14:25:02 -0800 Subject: [PATCH 5/5] X509 --- .../main/java/com/auth0/jwt/JWTDecoder.java | 45 +++--- .../com/auth0/jwt/algorithms/Algorithm.java | 16 ++- .../auth0/jwt/algorithms/CryptoHelper.java | 8 +- .../auth0/jwt/algorithms/ECDSAAlgorithm.java | 40 ++---- .../auth0/jwt/algorithms/HMACAlgorithm.java | 20 ++- .../auth0/jwt/algorithms/NoneAlgorithm.java | 8 +- .../auth0/jwt/algorithms/RSAAlgorithm.java | 33 +++-- .../auth0/jwt/creators/AccessJwtCreator.java | 102 ++----------- .../java/com/auth0/jwt/creators/Creator.java | 134 ++++++++++++++++++ .../jwt/creators/ExtendedJwtCreator.java | 67 --------- .../com/auth0/jwt/creators/FbJwtCreator.java | 102 ++----------- .../auth0/jwt/creators/GoogleJwtCreator.java | 123 +++------------- .../jwt/creators/GoogleOrFbJwtCreator.java | 2 +- .../jwt/creators/ImplicitJwtCreator.java | 104 ++------------ .../com/auth0/jwt/creators/JWTCreator.java | 35 +++-- .../java/com/auth0/jwt/creators/Message.java | 6 +- .../auth0/jwt/creators/RiscJwtCreator.java | 112 ++------------- .../auth0/jwt/creators/ScopedJwtCreator.java | 111 ++------------- .../exceptions/RequiredClaimException.java | 7 + .../auth0/jwt/impl/PayloadDeserializer.java | 7 +- .../java/com/auth0/jwt/impl/PayloadImpl.java | 11 +- .../com/auth0/jwt/interfaces/Payload.java | 2 +- .../main/java/com/auth0/jwt/jwts/FbJWT.java | 4 +- .../java/com/auth0/jwt/jwts/GoogleJWT.java | 6 +- lib/src/main/java/com/auth0/jwt/jwts/JWT.java | 25 +++- .../java/com/auth0/jwt/jwts/ScopedJWT.java | 2 +- .../VerificationAndAssertion.java | 13 +- .../java/com/auth0/jwt/ClockImplTest.java | 11 +- .../com/auth0/jwt/ConcurrentVerifyTest.java | 19 +-- .../java/com/auth0/jwt/JWTDecoderTest.java | 20 +-- lib/src/test/java/com/auth0/jwt/JWTTest.java | 16 +-- .../com/auth0/jwt/MainTestSignatures.java | 14 +- .../java/com/auth0/jwt/TokenUtilsTest.java | 9 +- .../auth0/jwt/algorithms/AlgorithmTest.java | 22 +-- .../jwt/algorithms/ECDSAAlgorithmTest.java | 43 +++--- .../ECDSABouncyCastleProviderTests.java | 48 ++++--- .../jwt/algorithms/HMACAlgorithmTest.java | 34 +++-- .../jwt/algorithms/RSAAlgorithmTest.java | 39 ++--- .../jwt/creators/AccessJwtCreatorTest.java | 13 +- .../jwt/creators/ExtendedJwtCreatorTest.java | 19 ++- .../auth0/jwt/creators/FbJwtCreatorTest.java | 14 +- .../jwt/creators/GoogleJwtCreatorTest.java | 20 ++- .../jwt/creators/ImplicitJwtCreatorTest.java | 14 +- .../jwt/creators/RiscJwtCreatorTest.java | 13 +- .../jwt/creators/ScopedJwtCreatorTest.java | 13 +- .../com/auth0/jwt/impl/BasicHeaderTest.java | 14 +- .../com/auth0/jwt/impl/ClaimsHolderTest.java | 11 +- .../jwt/impl/HeaderDeserializerTest.java | 23 +-- .../com/auth0/jwt/impl/JWTParserTest.java | 17 ++- .../com/auth0/jwt/impl/JsonNodeClaimTest.java | 33 +++-- .../jwt/impl/PayloadDeserializerTest.java | 34 +++-- .../com/auth0/jwt/impl/PayloadImplTest.java | 20 +-- .../auth0/jwt/impl/PayloadSerializerTest.java | 13 +- 53 files changed, 679 insertions(+), 1012 deletions(-) create mode 100644 lib/src/main/java/com/auth0/jwt/creators/Creator.java create mode 100644 lib/src/main/java/com/auth0/jwt/exceptions/RequiredClaimException.java diff --git a/lib/src/main/java/com/auth0/jwt/JWTDecoder.java b/lib/src/main/java/com/auth0/jwt/JWTDecoder.java index 144ca19..e6a25aa 100644 --- a/lib/src/main/java/com/auth0/jwt/JWTDecoder.java +++ b/lib/src/main/java/com/auth0/jwt/JWTDecoder.java @@ -19,22 +19,28 @@ package com.auth0.jwt; -import com.auth0.jwt.creators.*; -import com.auth0.jwt.impl.JWTParser; +import com.auth0.jwt.creators.EncodeType; +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 com.auth0.jwt.utils.TokenUtils; +import com.google.common.base.Strings; +import java.net.URLDecoder; +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; -import java.net.URLDecoder; -import java.util.*; - /** * The JWTDecoder class holds the decode method to parse a given JWT token into it's JWT representation. */ @@ -44,9 +50,8 @@ public final class JWTDecoder implements DecodedJWT { private final String[] parts; private final Header header; private final Payload payload; - - private static final String FACEBOOK = "facebook"; - private static final String GOOGLE = "google"; + 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])); @@ -162,17 +167,24 @@ public String getToken() { return String.format("%s.%s.%s", parts[0], parts[1], parts[2]); } - public static GoogleOrFbJwtCreator decodeJWT(DecodedJWT jwt) { + public GoogleOrFbJwtCreator decodeJWT(DecodedJWT jwt) { Map claims = jwt.getClaims(); - String issuer = claims.get(Claims.ISSUER).asString(); + Claim issuerClaim = claims.get(Claims.ISSUER); + if(issuerClaim == null) { + throw new IllegalArgumentException("null issuer claim"); + } + String issuer = issuerClaim.asString(); GoogleOrFbJwtCreator googleOrFbJwtCreator = null; - if(issuer.contains(FACEBOOK)) { + 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.contains(GOOGLE)) { + } else if(ISSUER_GOOGLE.contains(issuer)) { googleOrFbJwtCreator = GoogleJwtCreator.build() .withPicture(claims.get(Claims.PICTURE).asString()) .withEmail(claims.get(Claims.EMAIL).asString()) @@ -188,4 +200,5 @@ public static GoogleOrFbJwtCreator decodeJWT(DecodedJWT jwt) { 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 617b944..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,13 @@ 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; /** 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 0ae7a9b..95b2ef8 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java @@ -19,43 +19,21 @@ 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.exceptions.SignatureGenerationException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.ECDSAKeyProvider; -import com.auth0.jwt.interfaces.Payload; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.JWSObject; -import com.nimbusds.jose.crypto.RSASSASigner; -import com.nimbusds.jose.crypto.RSASSAVerifier; -import com.nimbusds.jose.jwk.JWK; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; -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.File; -import java.io.FileReader; -import java.net.URL; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; -import java.security.*; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.SignatureException; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.ECPublicKey; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -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; class ECDSAAlgorithm extends Algorithm { @@ -86,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: @@ -116,7 +94,7 @@ 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"); + throw new UnsupportedOperationException("X509 is not supported for ECDSA algorithm"); } @Override 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 c46958c..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.*; +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: @@ -101,7 +97,7 @@ 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"); + throw new UnsupportedOperationException("X509 is not supported for HMAC algorithm"); } @Override 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 c580fac..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: 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 8bf1627..b9ecbe1 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/RSAAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/RSAAlgorithm.java @@ -28,21 +28,28 @@ 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 org.bouncycastle.util.io.pem.PemReader; - -import java.io.*; +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.*; +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.ArrayList; 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 { @@ -76,7 +83,7 @@ public void verifyWithX509(DecodedJWT jwt, String jwksFile, String pemFile) thro Jwk jwk = provider.get(kid); String cert = jwk.getCertificateChain().get(0); try (Writer writer = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream("./jwks.cert"), "utf-8"))) { + new FileOutputStream("./jwks.cert"), StandardCharsets.UTF_8.name()))) { writer.write("-----BEGIN CERTIFICATE-----"); writer.append("\n" + cert + "\n"); writer.append("-----END CERTIFICATE-----"); @@ -122,18 +129,18 @@ public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { } private List fetchContentAndSignatureByteArrays(DecodedJWT jwt, EncodeType encodeType) throws Exception{ - byte[] contentBytes = String.format("%s.%s", jwt.getHeader(), jwt.getPayload()).getBytes(StandardCharsets.UTF_8); + 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: @@ -141,7 +148,7 @@ private List fetchContentAndSignatureByteArrays(DecodedJWT jwt, EncodeTy break; } - return new ArrayList<>(Arrays.asList(contentBytes, signatureBytes)); + return Arrays.asList(contentBytes, signatureBytes); } @Override 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 b62f279..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,54 +19,38 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.exceptions.JWTCreationException; import com.auth0.jwt.impl.Claims; -import com.auth0.jwt.jwts.JWT; - 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 requiredClaims; +public class AccessJwtCreator extends Creator{ private AccessJwtCreator() { - jwt = JWT.create(); - requiredClaims = new HashMap() {{ - put(Claims.ISSUER, false); - put(Claims.SUBJECT, false); - put(Claims.ISSUED_AT, false); - }}; } /** - * Add a specific Issuer (Claims.ISSUER) claim to the Payload. + * Add a specific Issuer ("issuer") claim to the Payload. * * @param issuer the Issuer value. * @return this same Builder instance. */ public AccessJwtCreator withIssuer(String issuer) { jwt.withIssuer(issuer); - requiredClaims.put(Claims.ISSUER, true); + requiredClaimsAccess.put(Claims.ISSUER, true); return this; } /** - * Add a specific Subject (Claims.SUBJECT) claim to the Payload. + * Add a specific Subject ("subject") claim to the Payload. * * @param subject the Subject value. * @return this same Builder instance. */ public AccessJwtCreator withSubject(String subject) { jwt.withSubject(subject); - requiredClaims.put(Claims.SUBJECT, true); + requiredClaimsAccess.put(Claims.SUBJECT, true); return this; } @@ -83,14 +67,14 @@ public AccessJwtCreator withAudience(String... audience) { } /** - * Add a specific Issued At (Claims.ISSUED_AT) claim to the Payload. + * Add a specific Issued At ("iat") claim to the Payload. * * @param iat the Issued At value. * @return this same Builder instance. */ public AccessJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - requiredClaims.put(Claims.ISSUED_AT, true); + requiredClaimsAccess.put(Claims.ISSUED_AT, true); return this; } @@ -114,9 +98,9 @@ public AccessJwtCreator withExp(Date exp) { * @throws IllegalArgumentException if the name is null. */ public AccessJwtCreator withNonStandardClaim(String name, String value) { - if(name.equalsIgnoreCase("subject") || name.equalsIgnoreCase(Claims.SUBJECT)) { + if("subject".equalsIgnoreCase(name) || Claims.SUBJECT.equalsIgnoreCase(name)) { withSubject(value); - } else if(name.equalsIgnoreCase("issuer") || name.equalsIgnoreCase(Claims.ISSUER)) { + } else if("issuer".equalsIgnoreCase(name) || Claims.ISSUER.equalsIgnoreCase(name)) { withIssuer(value); } else { jwt.withNonStandardClaim(name, value); @@ -203,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(requiredClaims.containsKey(name)) - requiredClaims.put(name, true); + if(requiredClaimsAccess.containsKey(name)) + requiredClaimsAccess.put(name, true); return this; } @@ -220,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.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; - } - - /** - * 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 : requiredClaims.keySet()) - if(!requiredClaims.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 51ca9b7..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; /** @@ -44,70 +41,6 @@ public ExtendedJwtCreator withNbf(Date 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.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; - } - - /** - * 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 : requiredClaims.keySet()) - if(!requiredClaims.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 14b2f2d..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,42 +19,26 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.exceptions.JWTCreationException; import com.auth0.jwt.impl.Claims; -import com.auth0.jwt.jwts.JWT; - 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 extends GoogleOrFbJwtCreator { - protected JWTCreator.Builder jwt; - protected HashMap requiredClaims; - private FbJwtCreator() { - jwt = JWT.create(); - requiredClaims = new HashMap() {{ - put(Claims.USER_ID, false); - put(Claims.APP_ID, false); - put(Claims.ISSUED_AT, false); - }}; } /** - * Add a specific Issued At (Claims.ISSUED_AT) claim to the Payload. + * Add a specific Issued At ("iat") claim to the Payload. * * @param iat the Issued At value. * @return this same Builder instance. */ public FbJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - requiredClaims.put(Claims.ISSUED_AT, true); + requiredClaimsFB.put(Claims.ISSUED_AT, true); return this; } @@ -70,26 +54,26 @@ public FbJwtCreator withExp(Date exp) { } /** - * Require a specific userId (Claims.USER_ID) claim. + * Require a specific userId ("userId") claim. * * @param userId the required userId value * @return this same Verification instance. */ public FbJwtCreator withUserId(String userId) { jwt.withNonStandardClaim(Claims.USER_ID, userId); - requiredClaims.put(Claims.USER_ID, true); + requiredClaimsFB.put(Claims.USER_ID, true); return this; } /** - * Require a specific appId (Claims.APP_ID) claim. + * Require a specific appId ("appId") claim. * * @param appId the required appId value * @return this same Verification instance. */ public FbJwtCreator withAppId(String appId) { jwt.withNonStandardClaim(Claims.APP_ID, appId); - requiredClaims.put(Claims.APP_ID, true); + requiredClaimsFB.put(Claims.APP_ID, true); return this; } @@ -102,9 +86,9 @@ public FbJwtCreator withAppId(String appId) { * @throws IllegalArgumentException if the name is null. */ public FbJwtCreator withNonStandardClaim(String name, String value) { - if(name.equalsIgnoreCase(Claims.USER_ID) || name.equalsIgnoreCase("user_id")) { + if(Claims.USER_ID.equalsIgnoreCase(name) || "user_id".equalsIgnoreCase(name)) { withUserId(value); - } else if(name.equalsIgnoreCase(Claims.APP_ID) || name.equalsIgnoreCase("app_id")) { + } else if(Claims.APP_ID.equalsIgnoreCase(name) || "app_id".equalsIgnoreCase(name)) { withAppId(value); } else { jwt.withNonStandardClaim(name, value); @@ -173,7 +157,7 @@ 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 { - if(name.equalsIgnoreCase(Claims.ISSUED_AT) || name.equalsIgnoreCase("issuedAt") || name.equalsIgnoreCase("issued_at")) { + if(Claims.ISSUED_AT.equalsIgnoreCase(name) || "issuedAt".equalsIgnoreCase(name) || "issued_at".equalsIgnoreCase(name)) { withIat(value); } else { jwt.withNonStandardClaim(name, value); @@ -191,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(requiredClaims.containsKey(name)) - requiredClaims.put(name, true); + if(requiredClaimsFB.containsKey(name)) + requiredClaimsFB.put(name, true); return this; } @@ -208,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.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; - } - - /** - * 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 : requiredClaims.keySet()) - if(!requiredClaims.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 7116943..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,94 +19,75 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.exceptions.JWTCreationException; import com.auth0.jwt.impl.Claims; -import com.auth0.jwt.jwts.JWT; - 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 extends GoogleOrFbJwtCreator { - protected JWTCreator.Builder jwt; - protected HashMap requiredClaims; - protected GoogleJwtCreator() { - jwt = JWT.create(); - requiredClaims = 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); - }}; } /** - * Add a specific Name (Claims.NAME) claim to the Payload. + * Add a specific Name ("name") claim to the Payload. * * @param name the Name value. * @return this same Builder instance. */ public GoogleJwtCreator withName(String name) { jwt.withNonStandardClaim(Claims.NAME, name); - requiredClaims.put(Claims.NAME, true); + requiredClaimsGoogle.put(Claims.NAME, true); return this; } /** - * Add a specific Email (Claims.EMAIL) claim to the Payload. + * Add a specific Email ("email") claim to the Payload. * * @param email the Email value. * @return this same Builder instance. */ public GoogleJwtCreator withEmail(String email) { jwt.withNonStandardClaim(Claims.EMAIL, email); - requiredClaims.put(Claims.EMAIL, true); + requiredClaimsGoogle.put(Claims.EMAIL, true); return this; } /** - * Add a specific Picture (Claims.PICTURE) claim to the Payload. + * Add a specific Picture ("picture") claim to the Payload. * * @param picture the Picture value. * @return this same Builder instance. */ public GoogleJwtCreator withPicture(String picture) { jwt.withNonStandardClaim(Claims.PICTURE, picture); - requiredClaims.put(Claims.PICTURE, true); + requiredClaimsGoogle.put(Claims.PICTURE, true); return this; } /** - * Add a specific Issuer (Claims.ISSUER) claim to the Payload. + * Add a specific Issuer ("issuer") claim to the Payload. * * @param issuer the Issuer value. * @return this same Builder instance. */ public GoogleJwtCreator withIssuer(String issuer) { jwt.withIssuer(issuer); - requiredClaims.put(Claims.ISSUER, true); + requiredClaimsGoogle.put(Claims.ISSUER, true); return this; } /** - * Add a specific Subject (Claims.SUBJECT) claim to the Payload. + * Add a specific Subject ("subject") claim to the Payload. * * @param subject the Subject value. * @return this same Builder instance. */ public GoogleJwtCreator withSubject(String subject) { jwt.withSubject(subject); - requiredClaims.put(Claims.SUBJECT, true); + requiredClaimsGoogle.put(Claims.SUBJECT, true); return this; } @@ -123,14 +104,14 @@ public GoogleJwtCreator withAudience(String... audience) { } /** - * Add a specific Issued At (Claims.ISSUED_AT) claim to the Payload. + * Add a specific Issued At ("iat") claim to the Payload. * * @param iat the Issued At value. * @return this same Builder instance. */ public GoogleJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - requiredClaims.put(Claims.ISSUED_AT, true); + requiredClaimsGoogle.put(Claims.ISSUED_AT, true); return this; } @@ -154,15 +135,15 @@ public GoogleJwtCreator withExp(Date exp) { * @throws IllegalArgumentException if the name is null. */ public GoogleJwtCreator withNonStandardClaim(String name, String value) { - if(value.equalsIgnoreCase(Claims.NAME)) { + if(Claims.NAME.equalsIgnoreCase(value)) { withName(value); - } else if(value.equalsIgnoreCase(Claims.EMAIL)) { + } else if(Claims.EMAIL.equalsIgnoreCase(value)) { withEmail(value); - } else if(value.equalsIgnoreCase(Claims.PICTURE)) { + } else if(Claims.PICTURE.equalsIgnoreCase(value)) { withPicture(value); - } else if(value.equalsIgnoreCase(Claims.ISSUER) || value.equalsIgnoreCase("issuer")) { + } else if(Claims.ISSUER.equalsIgnoreCase(value) || "issuer".equalsIgnoreCase(value)) { withIssuer(value); - } else if(name.equalsIgnoreCase("subject") || name.equalsIgnoreCase(Claims.SUBJECT)) { + } else if("subject".equalsIgnoreCase(name) || Claims.SUBJECT.equalsIgnoreCase(name)) { withSubject(value); } else { jwt.withNonStandardClaim(name, value); @@ -231,7 +212,7 @@ 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 { - if(name.equalsIgnoreCase(Claims.ISSUED_AT) || name.equalsIgnoreCase("issuedAt") || name.equalsIgnoreCase("issued_at")) { + if(Claims.ISSUED_AT.equalsIgnoreCase(name) || "issuedAt".equalsIgnoreCase(name) || "issued_at".equalsIgnoreCase(name)) { withIat(value); } else { jwt.withNonStandardClaim(name, value); @@ -249,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(requiredClaims.containsKey(name)) - requiredClaims.put(name, true); + if(requiredClaimsGoogle.containsKey(name)) + requiredClaimsGoogle.put(name, true); return this; } @@ -266,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.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; - } - - /** - * 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 : requiredClaims.keySet()) - if(!requiredClaims.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 index cab2db8..c239224 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/GoogleOrFbJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/GoogleOrFbJwtCreator.java @@ -1,4 +1,4 @@ package com.auth0.jwt.creators; -public abstract class GoogleOrFbJwtCreator { +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 b71b83c..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,54 +19,38 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.exceptions.JWTCreationException; import com.auth0.jwt.impl.Claims; -import com.auth0.jwt.jwts.JWT; - 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 requiredClaims; +public class ImplicitJwtCreator extends Creator{ private ImplicitJwtCreator() { - jwt = JWT.create(); - requiredClaims = new HashMap() {{ - put(Claims.ISSUER, false); - put(Claims.SUBJECT, false); - put(Claims.ISSUED_AT, false); - }}; } /** - * Add a specific Issuer (Claims.ISSUER) claim to the Payload. + * Add a specific Issuer ("issuer") claim to the Payload. * * @param issuer the Issuer value. * @return this same Builder instance. */ public ImplicitJwtCreator withIssuer(String issuer) { jwt.withIssuer(issuer); - requiredClaims.put(Claims.ISSUER, true); + requiredClaimsImplicit.put(Claims.ISSUER, true); return this; } /** - * Add a specific Subject (Claims.SUBJECT) claim to the Payload. + * Add a specific Subject ("subject") claim to the Payload. * * @param subject the Subject value. * @return this same Builder instance. */ public ImplicitJwtCreator withSubject(String subject) { jwt.withSubject(subject); - requiredClaims.put(Claims.SUBJECT, true); + requiredClaimsImplicit.put(Claims.SUBJECT, true); return this; } @@ -83,14 +67,14 @@ public ImplicitJwtCreator withAudience(String... audience) { } /** - * Add a specific Issued At (Claims.ISSUED_AT) claim to the Payload. + * Add a specific Issued At ("iat") claim to the Payload. * * @param iat the Issued At value. * @return this same Builder instance. */ public ImplicitJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - requiredClaims.put(Claims.ISSUED_AT, true); + requiredClaimsImplicit.put(Claims.ISSUED_AT, true); return this; } @@ -103,9 +87,9 @@ public ImplicitJwtCreator withIat(Date iat) { * @throws IllegalArgumentException if the name is null. */ public ImplicitJwtCreator withNonStandardClaim(String name, String value) { - if(name.equalsIgnoreCase("subject") || name.equalsIgnoreCase(Claims.SUBJECT)) { + if("subject".equalsIgnoreCase(name) || Claims.SUBJECT.equalsIgnoreCase(name)) { withSubject(value); - } else if(name.equalsIgnoreCase("issuer") || name.equalsIgnoreCase(Claims.ISSUER)) { + } else if("issuer".equalsIgnoreCase(name) || Claims.ISSUER.equalsIgnoreCase(name)) { withIssuer(value); } else { jwt.withNonStandardClaim(name, value); @@ -174,7 +158,7 @@ public ImplicitJwtCreator withNonStandardClaim(String name, Double value) throws * @throws IllegalArgumentException if the name is null. */ public ImplicitJwtCreator withNonStandardClaim(String name, Date value) throws IllegalArgumentException { - if(name.equalsIgnoreCase(Claims.ISSUED_AT) || name.equalsIgnoreCase("issuedAt") || name.equalsIgnoreCase("issued_at")) { + if(Claims.ISSUED_AT.equalsIgnoreCase(name) || "issuedAt".equalsIgnoreCase(name) || "issued_at".equalsIgnoreCase(name)) { withIat(value); } else { jwt.withNonStandardClaim(name, value); @@ -192,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(requiredClaims.containsKey(name)) - requiredClaims.put(name, true); + if(requiredClaimsImplicit.containsKey(name)) + requiredClaimsImplicit.put(name, true); return this; } @@ -209,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.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; - } - - /** - * 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 : requiredClaims.keySet()) - if(!requiredClaims.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 1d6c2f0..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,23 +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.Claims; 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.binary.Base32; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.binary.Hex; - -import java.io.*; +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. @@ -170,7 +169,7 @@ public Builder withNotBefore(Date notBefore) { } /** - * Add a specific Issued At (Claims.ISSUED_AT) claim to the Payload. + * Add a specific Issued At ("iat") claim to the Payload. * * @param issuedAt the Issued At value. * @return this same Builder instance. @@ -181,7 +180,7 @@ public Builder withIssuedAt(Date issuedAt) { } /** - * Add a specific JWT Id (Claims.JWT_ID) claim to the Payload. + * Add a specific JWT Id ("jti") claim to the Payload. * * @param jwtId the Token Id value. * @return this same Builder instance. @@ -404,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); } 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 ee9eaf2..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,68 +19,50 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.exceptions.JWTCreationException; import com.auth0.jwt.impl.Claims; -import com.auth0.jwt.interfaces.Verification; -import com.auth0.jwt.jwts.JWT; - 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 requiredClaims; +public class RiscJwtCreator extends Creator{ private RiscJwtCreator() { - jwt = JWT.create(); - requiredClaims = new HashMap() {{ - put(Claims.JWT_ID, false); - put(Claims.ISSUER, false); - put(Claims.SUBJECT, false); - put(Claims.ISSUED_AT, false); - }}; } /** - * Require a specific JWT Id (Claims.JWT_ID) claim. + * Require a specific JWT Id ("jti") claim. * * @param jwtId the required Id value * @return this same Verification instance. */ public RiscJwtCreator withJWTId(String jwtId) { jwt.withJWTId(jwtId); - requiredClaims.put(Claims.JWT_ID, true); + requiredClaimsRisc.put(Claims.JWT_ID, true); return this; } /** - * Add a specific Issuer (Claims.ISSUER) claim to the Payload. + * Add a specific Issuer ("issuer") claim to the Payload. * * @param issuer the Issuer value. * @return this same Builder instance. */ public RiscJwtCreator withIssuer(String issuer) { jwt.withIssuer(issuer); - requiredClaims.put(Claims.ISSUER, true); + requiredClaimsRisc.put(Claims.ISSUER, true); return this; } /** - * Add a specific Subject (Claims.SUBJECT) claim to the Payload. + * Add a specific Subject ("subject") claim to the Payload. * * @param subject the Subject value. * @return this same Builder instance. */ public RiscJwtCreator withSubject(String subject) { jwt.withSubject(subject); - requiredClaims.put(Claims.SUBJECT, true); + requiredClaimsRisc.put(Claims.SUBJECT, true); return this; } @@ -97,14 +79,14 @@ public RiscJwtCreator withAudience(String... audience) { } /** - * Add a specific Issued At (Claims.ISSUED_AT) claim to the Payload. + * Add a specific Issued At ("iat") claim to the Payload. * * @param iat the Issued At value. * @return this same Builder instance. */ public RiscJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - requiredClaims.put(Claims.ISSUED_AT, true); + requiredClaimsRisc.put(Claims.ISSUED_AT, true); return this; } @@ -139,11 +121,11 @@ public RiscJwtCreator withNbf(Date nbf) { * @throws IllegalArgumentException if the name is null. */ public RiscJwtCreator withNonStandardClaim(String name, String value) { - if(name.equalsIgnoreCase("subject") || name.equalsIgnoreCase(Claims.SUBJECT)) { + if("subject".equalsIgnoreCase(name) || Claims.SUBJECT.equalsIgnoreCase(name)) { withSubject(value); - } else if(name.equalsIgnoreCase("issuer") || name.equalsIgnoreCase(Claims.ISSUER)) { + } else if("issuer".equalsIgnoreCase(name) || Claims.ISSUER.equalsIgnoreCase(name)) { withIssuer(value); - } else if(name.equalsIgnoreCase(Claims.JWT_ID) || name.equalsIgnoreCase("jwtId") || name.equalsIgnoreCase("jwt_id")) { + } else if(Claims.JWT_ID.equalsIgnoreCase(name) || "jwtId".equalsIgnoreCase(name) || "jwt_id".equalsIgnoreCase(name)) { withJWTId(value); } else { jwt.withNonStandardClaim(name, value); @@ -212,7 +194,7 @@ 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 { - if(name.equalsIgnoreCase(Claims.ISSUED_AT) || name.equalsIgnoreCase("issuedAt") || name.equalsIgnoreCase("issued_at")) { + if(Claims.ISSUED_AT.equalsIgnoreCase(name) || "issuedAt".equalsIgnoreCase(name) || "issued_at".equalsIgnoreCase(name)) { withIat(value); } else { jwt.withNonStandardClaim(name, value); @@ -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(requiredClaims.containsKey(name)) - requiredClaims.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.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; - } - - /** - * 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 : requiredClaims.keySet()) - if(!requiredClaims.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 479b6b0..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,36 +19,19 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.exceptions.JWTCreationException; import com.auth0.jwt.impl.Claims; -import com.auth0.jwt.jwts.JWT; - 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 requiredClaims; +public class ScopedJwtCreator extends Creator{ private ScopedJwtCreator() { - jwt = JWT.create(); - requiredClaims = new HashMap() {{ - put(Claims.SCOPE, false); - put(Claims.ISSUER, false); - put(Claims.SUBJECT, false); - put(Claims.ISSUED_AT, false); - }}; } /** - * Add a specific Scope (Claims.SCOPE) claim to the Payload. + * Add a specific Scope ("scope") claim to the Payload. * Allows for multiple issuers * * @param scope the Scope value. @@ -56,31 +39,31 @@ private ScopedJwtCreator() { */ public ScopedJwtCreator withScope(String scope) { jwt.withNonStandardClaim(Claims.SCOPE, scope); - requiredClaims.put(Claims.SCOPE, true); + requiredClaimsScoped.put(Claims.SCOPE, true); return this; } /** - * Add a specific Issuer (Claims.ISSUER) claim to the Payload. + * Add a specific Issuer ("issuer") claim to the Payload. * * @param issuer the Issuer value. * @return this same Builder instance. */ public ScopedJwtCreator withIssuer(String issuer) { jwt.withIssuer(issuer); - requiredClaims.put(Claims.ISSUER, true); + requiredClaimsScoped.put(Claims.ISSUER, true); return this; } /** - * Add a specific Subject (Claims.SUBJECT) claim to the Payload. + * Add a specific Subject ("subject") claim to the Payload. * * @param subject the Subject value. * @return this same Builder instance. */ public ScopedJwtCreator withSubject(String subject) { jwt.withSubject(subject); - requiredClaims.put(Claims.SUBJECT, true); + requiredClaimsScoped.put(Claims.SUBJECT, true); return this; } @@ -97,14 +80,14 @@ public ScopedJwtCreator withAudience(String... audience) { } /** - * Add a specific Issued At (Claims.ISSUED_AT) claim to the Payload. + * Add a specific Issued At ("iat") claim to the Payload. * * @param iat the Issued At value. * @return this same Builder instance. */ public ScopedJwtCreator withIat(Date iat) { jwt.withIssuedAt(iat); - requiredClaims.put(Claims.ISSUED_AT, true); + requiredClaimsScoped.put(Claims.ISSUED_AT, true); return this; } @@ -128,11 +111,11 @@ public ScopedJwtCreator withExp(Date exp) { * @throws IllegalArgumentException if the name is null. */ public ScopedJwtCreator withNonStandardClaim(String name, String value) { - if(name.equalsIgnoreCase("subject") || name.equalsIgnoreCase(Claims.SUBJECT)) { + if("subject".equalsIgnoreCase(name) || Claims.SUBJECT.equalsIgnoreCase(name)) { withSubject(value); - } else if(name.equalsIgnoreCase("issuer") || name.equalsIgnoreCase(Claims.ISSUER)) { + } else if("issuer".equalsIgnoreCase(name) || Claims.ISSUER.equalsIgnoreCase(name)) { withIssuer(value); - } else if(name.equalsIgnoreCase(Claims.SCOPE)) { + } else if(Claims.SCOPE.equalsIgnoreCase(name)) { withScope(value); } else { jwt.withNonStandardClaim(name, value); @@ -201,7 +184,7 @@ 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 { - if(name.equalsIgnoreCase(Claims.ISSUED_AT) || name.equalsIgnoreCase("issuedAt") || name.equalsIgnoreCase("issued_at")) { + if(Claims.ISSUED_AT.equalsIgnoreCase(name) || "issuedAt".equalsIgnoreCase(name) || "issued_at".equalsIgnoreCase(name)) { withIat(value); } else { jwt.withNonStandardClaim(name, value); @@ -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(requiredClaims.containsKey(name)) - requiredClaims.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.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; - } - - /** - * 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 : requiredClaims.keySet()) - if(!requiredClaims.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/PayloadDeserializer.java b/lib/src/main/java/com/auth0/jwt/impl/PayloadDeserializer.java index be61aef..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 { 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/interfaces/Payload.java b/lib/src/main/java/com/auth0/jwt/interfaces/Payload.java index c4afdf2..d9a4e00 100644 --- a/lib/src/main/java/com/auth0/jwt/interfaces/Payload.java +++ b/lib/src/main/java/com/auth0/jwt/interfaces/Payload.java @@ -71,7 +71,7 @@ public interface Payload { Date getIssuedAt(); /** - * Get the value of the Claims.JWT_ID claim, or null if it's not available. + * Get the value of the "jti" claim, or null if it's not available. * * @return the JWT ID value or null. */ 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 34dfd69..be32623 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/FbJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/FbJWT.java @@ -42,7 +42,7 @@ public Verification createVerifierForFb(String userId, String appId) { } /** - * Require a specific userId (Claims.USER_ID) claim. + * Require a specific userId ("userId") claim. * * @param userId the required userId value * @return this same Verification instance. @@ -53,7 +53,7 @@ public Verification withUserId(String userId) { } /** - * Require a specific appId (Claims.APP_ID) claim. + * Require a specific appId ("appId") claim. * * @param appId the required appId value * @return this same Verification instance. 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 9798e9f..f94bdad 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java @@ -50,7 +50,7 @@ public Verification createVerifierForGoogle(String picture, String email, Listdoesn'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. @@ -112,6 +121,8 @@ public DecodedJWT decode16Bytes(String token) throws Exception { * 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. @@ -152,6 +163,8 @@ public DecodedJWT decode32Bytes(String token) throws Exception { * 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. @@ -347,7 +360,7 @@ public Verification acceptIssuedAt(long leeway) throws IllegalArgumentException } /** - * Require a specific JWT Id (Claims.JWT_ID) claim. + * Require a specific JWT Id ("jti") claim. * * @param jwtId the required Id value * @return this same Verification instance. 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 97af68a..71402f6 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/ScopedJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/ScopedJWT.java @@ -47,7 +47,7 @@ public Verification createVerifierForScoped(String scope, List issuer, } /** - * Require a specific Scope (Claims.SCOPE) claim. + * Require a specific Scope ("scope") claim. * * @param scope the required Scope value * @return this same Verification instance. 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 979bc47..8cfba4c 100644 --- a/lib/src/main/java/com/auth0/jwt/verification/VerificationAndAssertion.java +++ b/lib/src/main/java/com/auth0/jwt/verification/VerificationAndAssertion.java @@ -57,8 +57,7 @@ public static void verifyClaims(Clock clock, DecodedJWT jwt, Map for (Map.Entry entry : claims.entrySet()) { switch (entry.getKey()) { case Claims.AUDIENCE: - //noinspection unchecked - VerificationAndAssertion.assertValidAudienceClaim(jwt.getAudience(), (List) entry.getValue()); + assertValidAudienceClaim(jwt.getAudience(), (List) entry.getValue()); break; case Claims.EXPIRES_AT: assertValidDateClaim(clock, jwt.getExpiresAt(), (Long) entry.getValue(), true); @@ -70,13 +69,13 @@ public static void verifyClaims(Clock clock, DecodedJWT jwt, Map assertValidDateClaim(clock, jwt.getNotBefore(), (Long) entry.getValue(), false); break; case Claims.ISSUER: - VerificationAndAssertion.assertValidIssuerClaim(jwt.getIssuer(), (List) entry.getValue()); + assertValidIssuerClaim(jwt.getIssuer(), (List) entry.getValue()); break; case Claims.JWT_ID: - VerificationAndAssertion.assertValidStringClaim(entry.getKey(), jwt.getId(), (String) entry.getValue()); + 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; } } @@ -138,13 +137,13 @@ private static void assertDateIsPast(Date date, long leeway, Date today) { } private static void assertValidAudienceClaim(List actual, List expected) { - if (expected == null || !expected.containsAll(actual)) { + if (actual == null || !actual.containsAll(expected)) { throw new InvalidClaimException("The Claim 'aud' value doesn't contain the required audience."); } } private static void assertValidIssuerClaim(List actual, List expected) { - if (expected == null || !expected.contains(actual.get(0))) { + 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 7ceecb2..977d1ee 100644 --- a/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java +++ b/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java @@ -19,28 +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 diff --git a/lib/src/test/java/com/auth0/jwt/JWTTest.java b/lib/src/test/java/com/auth0/jwt/JWTTest.java index c19447c..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 diff --git a/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java b/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java index 0b6f8ef..4ea8edc 100644 --- a/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java +++ b/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java @@ -21,6 +21,9 @@ 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; @@ -31,15 +34,12 @@ 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 { @@ -121,7 +121,6 @@ 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) @@ -144,7 +143,6 @@ 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) diff --git a/lib/src/test/java/com/auth0/jwt/TokenUtilsTest.java b/lib/src/test/java/com/auth0/jwt/TokenUtilsTest.java index 9468ddf..de39f1b 100644 --- a/lib/src/test/java/com/auth0/jwt/TokenUtilsTest.java +++ b/lib/src/test/java/com/auth0/jwt/TokenUtilsTest.java @@ -19,15 +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 97f54f7..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 { 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 7aee69a..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,7 +62,6 @@ 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); } @@ -90,7 +90,6 @@ public void shouldFailHMAC256VerificationWithInvalidSecretBytes() throws Excepti 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); } @@ -119,7 +118,6 @@ public void shouldFailHMAC384VerificationWithInvalidSecretBytes() throws Excepti 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); } 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 e8d9843..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 { 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 c7475d4..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,6 +21,9 @@ 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; @@ -28,17 +31,15 @@ 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 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 12212a9..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.Claims; 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 81d7ddb..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,8 +21,9 @@ 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.Claims; @@ -31,22 +32,21 @@ 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 public ExpectedException thrown = ExpectedException.none(); private static final Date exp = generateRandomExpDateInFuture(); private static final Date iat = generateRandomIatDateInPast(); - private static final String USER_ID = Claims.USER_ID; - private static final String APP_ID = Claims.APP_ID; + private static final String USER_ID = "userId"; + private static final String APP_ID = "appId"; @Test public void testFbJwtCreatorAllStandardClaimsMustBeRequired() throws Exception { 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 31d8c92..983a204 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java @@ -19,11 +19,12 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.JWTDecoder; 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.Claims; @@ -32,25 +33,22 @@ 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 public ExpectedException thrown = ExpectedException.none(); private static final Date exp = generateRandomExpDateInFuture(); private static final Date iat = generateRandomIatDateInPast(); - public static final String PICTURE = Claims.PICTURE; - public static final String EMAIL = Claims.EMAIL; - public static final String NAME = Claims.NAME; + public static final String PICTURE = "picture"; + public static final String EMAIL = "email"; + public static final String NAME = "name"; @Test 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 40e28be..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.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,7 +132,7 @@ public void testImplicitJwtCreatorInvalidAudience() throws Exception { @Test public void testImplicitJwtCreatorIssuerNotProvided() throws Exception { - thrown.expect(Exception.class); + thrown.expect(RequiredClaimException.class); thrown.expectMessage("Standard claim: iss has not been set"); Algorithm algorithm = Algorithm.HMAC256("secret"); String token = ImplicitJwtCreator.build() 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 7e7d4b2..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,6 +21,9 @@ 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; @@ -30,15 +33,13 @@ 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 @@ -46,7 +47,7 @@ public class RiscJwtCreatorTest { private static final Date exp = generateRandomExpDateInFuture(); private static final Date iat = generateRandomIatDateInPast(); private static final Date nbf = iat; - private static final String jti = Claims.JWT_ID; + private static final String jti = "jti"; @Test public void testRiscJwtCreatorAllStandardClaimsMustBeRequired() throws Exception { 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 f8319ce..cbec6f2 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java @@ -19,11 +19,12 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.JWTDecoder; 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.Claims; @@ -32,15 +33,13 @@ 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 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 bbaef88..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 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 dc6a418..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; 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 8bae87e..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 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 83e5b30..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 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 d5d7cdb..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 {