diff --git a/lib/build.gradle b/lib/build.gradle index 2a7694c..4f32879 100644 --- a/lib/build.gradle +++ b/lib/build.gradle @@ -37,11 +37,13 @@ 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 group: 'com.google.guava', name: 'guava', version: 'r05' testCompile 'org.bouncycastle:bcprov-jdk15on:1.58' testCompile 'junit:junit:4.12' testCompile 'net.jodah:concurrentunit:0.4.3' testCompile 'org.hamcrest:java-hamcrest:2.0.0.0' testCompile 'org.mockito:mockito-core:2.11.0' + testCompile group: 'org.slf4j', name: 'slf4j-simple', version: '1.6.1' } jacocoTestReport { diff --git a/lib/src/main/java/com/auth0/jwt/ClockImpl.java b/lib/src/main/java/com/auth0/jwt/ClockImpl.java index 250c6a0..d8b7311 100644 --- a/lib/src/main/java/com/auth0/jwt/ClockImpl.java +++ b/lib/src/main/java/com/auth0/jwt/ClockImpl.java @@ -20,7 +20,6 @@ package com.auth0.jwt; import com.auth0.jwt.interfaces.Clock; - import java.util.Date; public final class ClockImpl implements Clock { diff --git a/lib/src/main/java/com/auth0/jwt/JWTDecoder.java b/lib/src/main/java/com/auth0/jwt/JWTDecoder.java index 7a967fb..92ba0cd 100644 --- a/lib/src/main/java/com/auth0/jwt/JWTDecoder.java +++ b/lib/src/main/java/com/auth0/jwt/JWTDecoder.java @@ -20,23 +20,19 @@ package com.auth0.jwt; import com.auth0.jwt.creators.EncodeType; -import com.auth0.jwt.creators.JWTCreator; -import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.impl.JWTParser; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Header; import com.auth0.jwt.interfaces.Payload; -import org.apache.commons.codec.binary.Base32; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.binary.Hex; -import org.apache.commons.codec.binary.StringUtils; - import java.net.URLDecoder; -import java.net.URLEncoder; import java.util.Date; import java.util.List; import java.util.Map; +import org.apache.commons.codec.binary.Base32; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.codec.binary.Hex; +import org.apache.commons.codec.binary.StringUtils; /** * The JWTDecoder class holds the decode method to parse a given JWT token into it's JWT representation. 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..c892946 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,13 @@ 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. @@ -396,12 +400,15 @@ public String toString() { @Override public boolean equals(Object algorithmParam) { - if(this == algorithmParam) + if (this == algorithmParam) { return true; - if(algorithmParam == null) + } + if (algorithmParam == null) { return false; - if(getClass() != algorithmParam.getClass()) + } + if (getClass() != algorithmParam.getClass()) { return false; + } Algorithm algorithm = (Algorithm) algorithmParam; return this.description.equals(algorithm.description) && this.name.equals(algorithm.name); diff --git a/lib/src/main/java/com/auth0/jwt/algorithms/CryptoHelper.java b/lib/src/main/java/com/auth0/jwt/algorithms/CryptoHelper.java index 43b6f82..271f817 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/CryptoHelper.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/CryptoHelper.java @@ -19,9 +19,15 @@ package com.auth0.jwt.algorithms; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.Signature; +import java.security.SignatureException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; -import java.security.*; class CryptoHelper { diff --git a/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java b/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java index 91a7fef..1d3ca2f 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java @@ -24,11 +24,6 @@ import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.ECDSAKeyProvider; -import org.apache.commons.codec.binary.Base32; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.binary.Hex; -import org.apache.commons.codec.binary.StringUtils; - import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; @@ -36,6 +31,9 @@ import java.security.SignatureException; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.ECPublicKey; +import org.apache.commons.codec.binary.Base32; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.codec.binary.Hex; class ECDSAAlgorithm extends Algorithm { 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..98f3655 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/HMACAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/HMACAlgorithm.java @@ -20,22 +20,18 @@ package com.auth0.jwt.algorithms; import com.auth0.jwt.creators.EncodeType; -import com.auth0.jwt.creators.JWTCreator; import com.auth0.jwt.exceptions.SignatureGenerationException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; -import org.apache.commons.codec.CharEncoding; -import org.apache.commons.codec.binary.Base32; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.binary.Hex; -import org.apache.commons.codec.binary.StringUtils; - import java.io.UnsupportedEncodingException; import java.net.URLDecoder; -import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; +import org.apache.commons.codec.CharEncoding; +import org.apache.commons.codec.binary.Base32; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.codec.binary.Hex; class HMACAlgorithm extends Algorithm { 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..20ee288 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,11 @@ import com.auth0.jwt.exceptions.SignatureGenerationException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; +import java.net.URLDecoder; 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() { 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..daf1231 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/RSAAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/RSAAlgorithm.java @@ -24,10 +24,6 @@ import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.RSAKeyProvider; -import org.apache.commons.codec.binary.Base32; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.binary.Hex; - import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; @@ -35,6 +31,9 @@ import java.security.SignatureException; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; +import org.apache.commons.codec.binary.Base32; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.codec.binary.Hex; class RSAAlgorithm extends Algorithm { 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..20bae2b 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java @@ -21,9 +21,9 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.interfaces.constants.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.JWT; - import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -41,8 +41,8 @@ public class AccessJwtCreator { public AccessJwtCreator() { jwt = JWT.create(); addedClaims = new HashMap() {{ - put("Issuer", false); - put("Subject", false); + put(Constants.ISSUER_CAPITALIZED, false); + put(Constants.SUBJECT_CAPITALIZED, false); put("Iat", false); }}; publicClaims = new HashSet() {{ @@ -65,7 +65,7 @@ public AccessJwtCreator() { */ public AccessJwtCreator withIssuer(String... issuer) { jwt.withIssuer(issuer); - addedClaims.put("Issuer", true); + addedClaims.put(Constants.ISSUER_CAPITALIZED, true); return this; } @@ -78,7 +78,7 @@ public AccessJwtCreator withIssuer(String... issuer) { */ public AccessJwtCreator withSubject(String... subject) { jwt.withSubject(subject); - addedClaims.put("Subject", true); + addedClaims.put(Constants.SUBJECT_CAPITALIZED, true); return this; } @@ -205,8 +205,9 @@ 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 (publicClaims.contains(name)) { addedClaims.put(name, true); + } return this; } @@ -232,7 +233,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm); @@ -250,7 +251,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm, EncodeType.Base16); @@ -268,7 +269,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm, EncodeType.Base32); @@ -278,12 +279,15 @@ public String signBase32Encoding(Algorithm algorithm) throws Exception { /** * Verifies that all the standard claims were provided + * * @throws Exception if all the standard claims weren't provided */ private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) + for (String claim : addedClaims.keySet()) { + if (!addedClaims.get(claim)) { throw new Exception("Standard claim: " + claim + " has not been set"); + } + } } public static AccessJwtCreator build() { 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..d9c868e 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ExtendedJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ExtendedJwtCreator.java @@ -21,13 +21,12 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; - import java.util.Date; /** * The ExtendedJwtCreator class holds the sign method to generate a complete Extended JWT (with Signature) from a given Header and Payload content. */ -public class ExtendedJwtCreator extends GoogleJwtCreator{ +public class ExtendedJwtCreator extends GoogleJwtCreator { public ExtendedJwtCreator() { super(); @@ -53,8 +52,9 @@ public GoogleJwtCreator withNbf(Date nbf) { * @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. */ + @Override public String sign(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { + if (!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm); @@ -71,8 +71,9 @@ public String sign(Algorithm algorithm) throws Exception { * @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. */ + @Override public String signBase16Encoding(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { + if (!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm, EncodeType.Base16); @@ -89,8 +90,9 @@ public String signBase16Encoding(Algorithm algorithm) throws Exception { * @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. */ + @Override public String signBase32Encoding(Algorithm algorithm) throws Exception { - if(!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { + if (!jwt.getIsNoneAlgorithmAllowed() && algorithm.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm, EncodeType.Base32); @@ -100,12 +102,15 @@ public String signBase32Encoding(Algorithm algorithm) throws Exception { /** * Verifies that all the standard claims were provided + * * @throws Exception if all the standard claims weren't provided */ private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) + for (String claim : addedClaims.keySet()) { + if (!addedClaims.get(claim)) { throw new Exception("Standard claim: " + claim + " has not been set"); + } + } } public static ExtendedJwtCreator build() { 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..eb68296 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/FbJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/FbJwtCreator.java @@ -21,9 +21,8 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.JWT; - import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -186,8 +185,9 @@ 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 (publicClaims.contains(name)) { addedClaims.put(name, true); + } return this; } @@ -213,7 +213,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm); @@ -231,7 +231,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm, EncodeType.Base16); @@ -249,7 +249,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm, EncodeType.Base32); @@ -259,12 +259,15 @@ public String signBase32Encoding(Algorithm algorithm) throws Exception { /** * Verifies that all the standard claims were provided + * * @throws Exception if all the standard claims weren't provided */ private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) + for (String claim : addedClaims.keySet()) { + if (!addedClaims.get(claim)) { throw new Exception("Standard claim: " + claim + " has not been set"); + } + } } public static FbJwtCreator build() { 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..8f3b706 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/GoogleJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/GoogleJwtCreator.java @@ -21,9 +21,9 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.interfaces.constants.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.JWT; - import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -41,11 +41,11 @@ public class GoogleJwtCreator { public GoogleJwtCreator() { jwt = JWT.create(); addedClaims = new HashMap() {{ - put("Name", false); - put("Email", false); - put("Picture", false); - put("Issuer", false); - put("Subject", false); + put(Constants.NAME_CAPITALIZED, false); + put(Constants.EMAIL_CAPITALIZED, false); + put(Constants.PICTURE_CAPITALIZED, false); + put(Constants.ISSUER_CAPITALIZED, false); + put(Constants.SUBJECT_CAPITALIZED, false); put("Iat", false); }}; publicClaims = new HashSet() {{ @@ -68,7 +68,7 @@ public GoogleJwtCreator() { */ public GoogleJwtCreator withName(String name) { jwt.withNonStandardClaim("name", name); - addedClaims.put("Name", true); + addedClaims.put(Constants.NAME_CAPITALIZED, true); return this; } @@ -79,8 +79,8 @@ public GoogleJwtCreator withName(String name) { * @return this same Builder instance. */ public GoogleJwtCreator withEmail(String email) { - jwt.withNonStandardClaim("email", email); - addedClaims.put("Email", true); + jwt.withNonStandardClaim(Constants.EMAIL, email); + addedClaims.put(Constants.EMAIL_CAPITALIZED, true); return this; } @@ -91,8 +91,8 @@ public GoogleJwtCreator withEmail(String email) { * @return this same Builder instance. */ public GoogleJwtCreator withPicture(String picture) { - jwt.withNonStandardClaim("picture", picture); - addedClaims.put("Picture", true); + jwt.withNonStandardClaim(Constants.PICTURE, picture); + addedClaims.put(Constants.PICTURE_CAPITALIZED, true); return this; } @@ -105,7 +105,7 @@ public GoogleJwtCreator withPicture(String picture) { */ public GoogleJwtCreator withIssuer(String... issuer) { jwt.withIssuer(issuer); - addedClaims.put("Issuer", true); + addedClaims.put(Constants.ISSUER_CAPITALIZED, true); return this; } @@ -118,7 +118,7 @@ public GoogleJwtCreator withIssuer(String... issuer) { */ public GoogleJwtCreator withSubject(String... subject) { jwt.withSubject(subject); - addedClaims.put("Subject", true); + addedClaims.put(Constants.SUBJECT_CAPITALIZED, true); return this; } @@ -245,8 +245,9 @@ 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 (publicClaims.contains(name)) { addedClaims.put(name, true); + } return this; } @@ -272,7 +273,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm); @@ -290,7 +291,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm, EncodeType.Base16); @@ -308,7 +309,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm, EncodeType.Base32); @@ -318,12 +319,15 @@ public String signBase32Encoding(Algorithm algorithm) throws Exception { /** * Verifies that all the standard claims were provided + * * @throws Exception if all the standard claims weren't provided */ private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) + for (String claim : addedClaims.keySet()) { + if (!addedClaims.get(claim)) { throw new Exception("Standard claim: " + claim + " has not been set"); + } + } } public static GoogleJwtCreator build() { 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..475f74d 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ImplicitJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ImplicitJwtCreator.java @@ -21,9 +21,9 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.interfaces.constants.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.JWT; - import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -41,8 +41,8 @@ public class ImplicitJwtCreator { public ImplicitJwtCreator() { jwt = JWT.create(); addedClaims = new HashMap() {{ - put("Issuer", false); - put("Subject", false); + put(Constants.ISSUER_CAPITALIZED, false); + put(Constants.SUBJECT_CAPITALIZED, false); put("Iat", false); }}; publicClaims = new HashSet() {{ @@ -62,7 +62,7 @@ public ImplicitJwtCreator() { */ public ImplicitJwtCreator withIssuer(String... issuer) { jwt.withIssuer(issuer); - addedClaims.put("Issuer", true); + addedClaims.put(Constants.ISSUER_CAPITALIZED, true); return this; } @@ -75,7 +75,7 @@ public ImplicitJwtCreator withIssuer(String... issuer) { */ public ImplicitJwtCreator withSubject(String... subject) { jwt.withSubject(subject); - addedClaims.put("Subject", true); + addedClaims.put(Constants.SUBJECT_CAPITALIZED, true); return this; } @@ -191,8 +191,9 @@ 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 (publicClaims.contains(name)) { addedClaims.put(name, true); + } return this; } @@ -218,7 +219,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm); @@ -236,7 +237,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm, EncodeType.Base16); @@ -254,7 +255,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm, EncodeType.Base32); @@ -264,12 +265,15 @@ public String signBase32Encoding(Algorithm algorithm) throws Exception { /** * Verifies that all the standard claims were provided + * * @throws Exception if all the standard claims weren't provided */ private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) + for (String claim : addedClaims.keySet()) { + if (!addedClaims.get(claim)) { throw new Exception("Standard claim: " + claim + " has not been set"); + } + } } public static ImplicitJwtCreator build() { 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..5c2cfa9 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java @@ -24,24 +24,20 @@ 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.interfaces.constants.PublicClaims; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; -import org.apache.commons.codec.Encoder; -import org.apache.commons.codec.binary.Base32; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.binary.Hex; -import org.apache.commons.codec.binary.StringUtils; - -import java.io.*; -import java.net.URLDecoder; +import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.HashMap; import java.util.Map; +import org.apache.commons.codec.binary.Base32; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.codec.binary.Hex; /** * The JWTCreator class holds the sign method to generate a complete JWT (with Signature) from a given Header and Payload content. @@ -346,14 +342,14 @@ public Builder withArrayClaim(String name, Long[] items) throws IllegalArgumentE * @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{ + public String sign(Algorithm algorithm) throws Exception { return sign(algorithm, EncodeType.Base64); } /** * Creates a new JWT and signs it with the given algorithm * - * @param algorithm used to sign the JWT + * @param algorithm used to sign the JWT * @param encodeType specifies which base encoding is required * @return a new JWT token * @throws IllegalArgumentException if the provided algorithm is null. @@ -363,7 +359,7 @@ public String sign(Algorithm algorithm, EncodeType encodeType) throws Exception if (algorithm == null) { throw new IllegalArgumentException("The Algorithm cannot be null."); } - if(encodeType == null) { + if (encodeType == null) { throw new IllegalArgumentException("Encodetype cannot be null."); } headerClaims.put(PublicClaims.ALGORITHM, algorithm.getName()); @@ -422,7 +418,7 @@ private String signBase16Encoding() throws UnsupportedEncodingException { return String.format("%s.%s", content, signatureFinal); } - private String signBase32Encoding() throws UnsupportedEncodingException{ + private String signBase32Encoding() throws UnsupportedEncodingException { Base32 base32 = new Base32(); String header = URLEncoder.encode(headerJson, "UTF-8"); String payload = URLEncoder.encode(payloadJson, "UTF-8"); 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..e989d86 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/Message.java +++ b/lib/src/main/java/com/auth0/jwt/creators/Message.java @@ -22,7 +22,6 @@ 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; @@ -40,12 +39,13 @@ public String toUrlDecoded(String urlEncoded) throws UnsupportedEncodingExceptio return URLDecoder.decode(urlEncoded, "UTF-8"); } - public String toJSON(HashMap hashMap) { + public String toJSON(HashMap hashMap) { return new Gson().toJson(hashMap); } - public HashMap fromJSON(String json) throws IOException { - return new ObjectMapper().readValue(json, new TypeReference>(){}); + public HashMap fromJSON(String json) throws IOException { + return new ObjectMapper().readValue(json, new TypeReference>() { + }); } } \ No newline at end of file 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..8cc362a 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/RiscJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/RiscJwtCreator.java @@ -21,10 +21,9 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; -import com.auth0.jwt.interfaces.Verification; +import com.auth0.jwt.interfaces.constants.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.JWT; - import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -43,8 +42,8 @@ public RiscJwtCreator() { jwt = JWT.create(); addedClaims = new HashMap() {{ put("Jti", false); - put("Issuer", false); - put("Subject", false); + put(Constants.ISSUER_CAPITALIZED, false); + put(Constants.SUBJECT_CAPITALIZED, false); put("Iat", false); }}; publicClaims = new HashSet() {{ @@ -79,7 +78,7 @@ public RiscJwtCreator withJWTId(String jwtId) { */ public RiscJwtCreator withIssuer(String... issuer) { jwt.withIssuer(issuer); - addedClaims.put("Issuer", true); + addedClaims.put(Constants.ISSUER_CAPITALIZED, true); return this; } @@ -92,7 +91,7 @@ public RiscJwtCreator withIssuer(String... issuer) { */ public RiscJwtCreator withSubject(String... subject) { jwt.withSubject(subject); - addedClaims.put("Subject", true); + addedClaims.put(Constants.SUBJECT_CAPITALIZED, true); return this; } @@ -230,8 +229,9 @@ 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 (publicClaims.contains(name)) { addedClaims.put(name, true); + } return this; } @@ -257,7 +257,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm); @@ -275,7 +275,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm, EncodeType.Base16); @@ -293,7 +293,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm, EncodeType.Base32); @@ -303,12 +303,15 @@ public String signBase32Encoding(Algorithm algorithm) throws Exception { /** * Verifies that all the standard claims were provided + * * @throws Exception if all the standard claims weren't provided */ private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) + for (String claim : addedClaims.keySet()) { + if (!addedClaims.get(claim)) { throw new Exception("Standard claim: " + claim + " has not been set"); + } + } } public static RiscJwtCreator build() { 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..e601d41 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ScopedJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ScopedJwtCreator.java @@ -21,9 +21,9 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.interfaces.constants.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.JWT; - import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -32,7 +32,7 @@ /** * 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; @@ -41,9 +41,9 @@ public class ScopedJwtCreator{ public ScopedJwtCreator() { jwt = JWT.create(); addedClaims = new HashMap() {{ - put("Scope", false); - put("Issuer", false); - put("Subject", false); + put(Constants.SCOPE_CAPITALIZED, false); + put(Constants.ISSUER_CAPITALIZED, false); + put(Constants.SUBJECT_CAPITALIZED, false); put("Iat", false); }}; publicClaims = new HashSet() {{ @@ -65,8 +65,8 @@ public ScopedJwtCreator() { * @return this same Builder instance. */ public ScopedJwtCreator withScope(String scope) { - jwt.withNonStandardClaim("scope", scope); - addedClaims.put("Scope", true); + jwt.withNonStandardClaim(Constants.SCOPE, scope); + addedClaims.put(Constants.SCOPE_CAPITALIZED, true); return this; } @@ -79,7 +79,7 @@ public ScopedJwtCreator withScope(String scope) { */ public ScopedJwtCreator withIssuer(String... issuer) { jwt.withIssuer(issuer); - addedClaims.put("Issuer", true); + addedClaims.put(Constants.ISSUER_CAPITALIZED, true); return this; } @@ -92,7 +92,7 @@ public ScopedJwtCreator withIssuer(String... issuer) { */ public ScopedJwtCreator withSubject(String... subject) { jwt.withSubject(subject); - addedClaims.put("Subject", true); + addedClaims.put(Constants.SUBJECT_CAPITALIZED, true); return this; } @@ -219,8 +219,9 @@ 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 (publicClaims.contains(name)) { addedClaims.put(name, true); + } return this; } @@ -246,7 +247,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm); @@ -264,7 +265,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm, EncodeType.Base16); @@ -282,7 +283,7 @@ 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.equals(Algorithm.none())) { throw new IllegalAccessException("None algorithm isn't allowed"); } String JWS = jwt.sign(algorithm, EncodeType.Base32); @@ -292,12 +293,15 @@ public String signBase32Encoding(Algorithm algorithm) throws Exception { /** * Verifies that all the standard claims were provided + * * @throws Exception if all the standard claims weren't provided */ private void verifyClaims() throws Exception { - for(String claim : addedClaims.keySet()) - if(!addedClaims.get(claim)) + for (String claim : addedClaims.keySet()) { + if (!addedClaims.get(claim)) { throw new Exception("Standard claim: " + claim + " has not been set"); + } + } } public static ScopedJwtCreator build() { diff --git a/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/DeserializationNotPossible.java b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/DeserializationNotPossible.java new file mode 100644 index 0000000..66bfeba --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/DeserializationNotPossible.java @@ -0,0 +1,11 @@ +package com.auth0.jwt.exceptions.oicmsg_exceptions; + +public class DeserializationNotPossible extends JWKException { + public DeserializationNotPossible(String message) { + super(message); + } + + public DeserializationNotPossible() { + super(); + } +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/HeaderError.java b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/HeaderError.java new file mode 100644 index 0000000..4fe7a97 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/HeaderError.java @@ -0,0 +1,7 @@ +package com.auth0.jwt.exceptions.oicmsg_exceptions; + +public class HeaderError extends Exception { + public HeaderError(String message) { + super(message); + } +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/ImportException.java b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/ImportException.java new file mode 100644 index 0000000..1e29884 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/ImportException.java @@ -0,0 +1,7 @@ +package com.auth0.jwt.exceptions.oicmsg_exceptions; + +public class ImportException extends Exception { + public ImportException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/JWKException.java b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/JWKException.java new file mode 100644 index 0000000..8cba426 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/JWKException.java @@ -0,0 +1,12 @@ +package com.auth0.jwt.exceptions.oicmsg_exceptions; + +public class JWKException extends Exception { + + public JWKException(String message) { + super(message); + } + + public JWKException() { + super("JWKException"); + } +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/SerializationNotPossible.java b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/SerializationNotPossible.java new file mode 100644 index 0000000..676da1f --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/SerializationNotPossible.java @@ -0,0 +1,4 @@ +package com.auth0.jwt.exceptions.oicmsg_exceptions; + +public class SerializationNotPossible extends Throwable { +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/TypeError.java b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/TypeError.java new file mode 100644 index 0000000..3cc2df0 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/TypeError.java @@ -0,0 +1,4 @@ +package com.auth0.jwt.exceptions.oicmsg_exceptions; + +public class TypeError extends Exception { +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/UnknownKeyType.java b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/UnknownKeyType.java new file mode 100644 index 0000000..1d9c714 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/UnknownKeyType.java @@ -0,0 +1,7 @@ +package com.auth0.jwt.exceptions.oicmsg_exceptions; + +public class UnknownKeyType extends Exception { + public UnknownKeyType(String message) { + super(message); + } +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/UpdateFailed.java b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/UpdateFailed.java new file mode 100644 index 0000000..9d1fa27 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/UpdateFailed.java @@ -0,0 +1,7 @@ +package com.auth0.jwt.exceptions.oicmsg_exceptions; + +public class UpdateFailed extends Exception { + public UpdateFailed(String message) { + super(message); + } +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/ValueError.java b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/ValueError.java new file mode 100644 index 0000000..0b68495 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/ValueError.java @@ -0,0 +1,4 @@ +package com.auth0.jwt.exceptions.oicmsg_exceptions; + +public class ValueError extends Exception { +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/impl/BasicHeader.java b/lib/src/main/java/com/auth0/jwt/impl/BasicHeader.java index d6c502d..e5efbc0 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/BasicHeader.java +++ b/lib/src/main/java/com/auth0/jwt/impl/BasicHeader.java @@ -19,16 +19,15 @@ package com.auth0.jwt.impl; +import static com.auth0.jwt.impl.JsonNodeClaim.extractClaim; + import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.Header; import com.fasterxml.jackson.databind.JsonNode; - import java.util.Collections; import java.util.HashMap; import java.util.Map; -import static com.auth0.jwt.impl.JsonNodeClaim.extractClaim; - /** * The BasicHeader class implements the Header interface. */ 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..21a3d29 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/HeaderDeserializer.java +++ b/lib/src/main/java/com/auth0/jwt/impl/HeaderDeserializer.java @@ -20,12 +20,12 @@ package com.auth0.jwt.impl; import com.auth0.jwt.exceptions.JWTDecodeException; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; - import java.io.IOException; import java.util.Map; diff --git a/lib/src/main/java/com/auth0/jwt/impl/JWTParser.java b/lib/src/main/java/com/auth0/jwt/impl/JWTParser.java index d471f82..c7466af 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/JWTParser.java +++ b/lib/src/main/java/com/auth0/jwt/impl/JWTParser.java @@ -27,7 +27,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.module.SimpleModule; - import java.io.IOException; public class JWTParser implements JWTPartsParser { diff --git a/lib/src/main/java/com/auth0/jwt/impl/JsonNodeClaim.java b/lib/src/main/java/com/auth0/jwt/impl/JsonNodeClaim.java index 9b41403..7cb2316 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/JsonNodeClaim.java +++ b/lib/src/main/java/com/auth0/jwt/impl/JsonNodeClaim.java @@ -26,7 +26,6 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; - import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayList; @@ -87,7 +86,9 @@ public T[] asArray(Class tClazz) throws JWTDecodeException { } T[] arr = (T[]) Array.newInstance(tClazz, data.size()); - for (int i = 0; i < data.size(); i++) { + for (int i = 0; + i < data.size(); + i++) { try { arr[i] = getObjectMapper().treeToValue(data.get(i), tClazz); } catch (JsonProcessingException e) { @@ -104,7 +105,9 @@ public List asList(Class tClazz) throws JWTDecodeException { } List list = new ArrayList<>(); - for (int i = 0; i < data.size(); i++) { + for (int i = 0; + i < data.size(); + i++) { try { list.add(getObjectMapper().treeToValue(data.get(i), tClazz)); } catch (JsonProcessingException e) { diff --git a/lib/src/main/java/com/auth0/jwt/impl/NullClaim.java b/lib/src/main/java/com/auth0/jwt/impl/NullClaim.java index 82e7c03..ad21043 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/NullClaim.java +++ b/lib/src/main/java/com/auth0/jwt/impl/NullClaim.java @@ -21,7 +21,6 @@ import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.interfaces.Claim; - import java.util.Date; import java.util.List; import java.util.Map; 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..bbb6568 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/PayloadDeserializer.java +++ b/lib/src/main/java/com/auth0/jwt/impl/PayloadDeserializer.java @@ -21,6 +21,7 @@ import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.interfaces.Payload; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; @@ -28,9 +29,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 { @@ -72,7 +76,9 @@ List getStringOrArray(Map tree, String claimName) thro ObjectMapper mapper = new ObjectMapper(); List list = new ArrayList<>(node.size()); - for (int i = 0; i < node.size(); i++) { + for (int i = 0; + i < node.size(); + i++) { try { list.add(mapper.treeToValue(node.get(i), String.class)); } catch (JsonProcessingException e) { diff --git a/lib/src/main/java/com/auth0/jwt/impl/PayloadImpl.java b/lib/src/main/java/com/auth0/jwt/impl/PayloadImpl.java index a732416..5800585 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/PayloadImpl.java +++ b/lib/src/main/java/com/auth0/jwt/impl/PayloadImpl.java @@ -19,13 +19,16 @@ package com.auth0.jwt.impl; +import static com.auth0.jwt.impl.JsonNodeClaim.extractClaim; + import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.Payload; import com.fasterxml.jackson.databind.JsonNode; - -import java.util.*; - -import static com.auth0.jwt.impl.JsonNodeClaim.extractClaim; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * The PayloadImpl class implements the Payload interface. diff --git a/lib/src/main/java/com/auth0/jwt/impl/PayloadSerializer.java b/lib/src/main/java/com/auth0/jwt/impl/PayloadSerializer.java index 09915f8..4a53aee 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/PayloadSerializer.java +++ b/lib/src/main/java/com/auth0/jwt/impl/PayloadSerializer.java @@ -19,10 +19,10 @@ package com.auth0.jwt.impl; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; - import java.io.IOException; import java.util.Date; import java.util.HashMap; diff --git a/lib/src/main/java/com/auth0/jwt/interfaces/Claim.java b/lib/src/main/java/com/auth0/jwt/interfaces/Claim.java index 6ec9d67..a48caf1 100644 --- a/lib/src/main/java/com/auth0/jwt/interfaces/Claim.java +++ b/lib/src/main/java/com/auth0/jwt/interfaces/Claim.java @@ -20,7 +20,6 @@ package com.auth0.jwt.interfaces; import com.auth0.jwt.exceptions.JWTDecodeException; - import java.util.Date; import java.util.List; import java.util.Map; 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/interfaces/GoogleVerification.java b/lib/src/main/java/com/auth0/jwt/interfaces/GoogleVerification.java index c7b66cc..40fd382 100644 --- a/lib/src/main/java/com/auth0/jwt/interfaces/GoogleVerification.java +++ b/lib/src/main/java/com/auth0/jwt/interfaces/GoogleVerification.java @@ -19,10 +19,9 @@ package com.auth0.jwt.interfaces; -import java.util.Date; import java.util.List; -public interface GoogleVerification extends Verification{ +public interface GoogleVerification extends Verification { Verification createVerifierForGoogle(String picture, String email, List issuer, List audience, String name, long expLeeway, long iatLeeway); diff --git a/lib/src/main/java/com/auth0/jwt/interfaces/Verification.java b/lib/src/main/java/com/auth0/jwt/interfaces/Verification.java index 82ffaba..97040bb 100644 --- a/lib/src/main/java/com/auth0/jwt/interfaces/Verification.java +++ b/lib/src/main/java/com/auth0/jwt/interfaces/Verification.java @@ -20,7 +20,6 @@ package com.auth0.jwt.interfaces; import com.auth0.jwt.jwts.JWT; - import java.util.Date; import java.util.List; diff --git a/lib/src/main/java/com/auth0/jwt/interfaces/constants/Constants.java b/lib/src/main/java/com/auth0/jwt/interfaces/constants/Constants.java new file mode 100644 index 0000000..ad08ade --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/interfaces/constants/Constants.java @@ -0,0 +1,18 @@ +package com.auth0.jwt.interfaces.constants; + +public interface Constants { + String ISSUER = "issuer"; + String ISSUER_CAPITALIZED = "Issuer"; + String AUDIENCE = "audience"; + String SUBJECT = "subject"; + String SUBJECT_CAPITALIZED = "Subject"; + String SECRET = "secret"; + String PICTURE = "picture"; + String PICTURE_CAPITALIZED = "Picture"; + String EMAIL = "email"; + String EMAIL_CAPITALIZED = "Email"; + String NAME = "name"; + String NAME_CAPITALIZED = "Name"; + String SCOPE = "scope"; + String SCOPE_CAPITALIZED = "Scope"; +} diff --git a/lib/src/main/java/com/auth0/jwt/impl/PublicClaims.java b/lib/src/main/java/com/auth0/jwt/interfaces/constants/PublicClaims.java similarity index 97% rename from lib/src/main/java/com/auth0/jwt/impl/PublicClaims.java rename to lib/src/main/java/com/auth0/jwt/interfaces/constants/PublicClaims.java index b7594e1..6f34f00 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/PublicClaims.java +++ b/lib/src/main/java/com/auth0/jwt/interfaces/constants/PublicClaims.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.impl; +package com.auth0.jwt.interfaces.constants; public interface PublicClaims { 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..a353c19 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/AccessJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/AccessJWT.java @@ -23,7 +23,6 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.Clock; import com.auth0.jwt.interfaces.Verification; - import java.util.List; public class AccessJWT extends JWT.BaseVerification implements Verification { @@ -34,12 +33,14 @@ public class AccessJWT extends JWT.BaseVerification implements Verification { /** * Create Verification object for verification purposes + * * @param issuer * @param audience * @param expLeeway * @param iatLeeway * @return */ + @Override public Verification createVerifierForAccess(List issuer, List audience, long expLeeway, long iatLeeway) { return withIssuer(issuer.toArray(new String[issuer.size()])).withAudience(audience.toArray(new String[audience.size()])) @@ -85,6 +86,7 @@ public JWT build() { * @param clock the instance that will handle the current time. * @return a new JWT instance with a custom Clock. */ + @Override public JWT build(Clock clock) { addLeewayToDateClaims(); return new JWT(algorithm, claims, clock); 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..3a695b8 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/ExtendedJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/ExtendedJWT.java @@ -22,18 +22,18 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.GoogleVerification; import com.auth0.jwt.interfaces.Verification; - import java.util.List; -public class ExtendedJWT extends GoogleJWT implements GoogleVerification{ +public class ExtendedJWT extends GoogleJWT implements GoogleVerification { ExtendedJWT(Algorithm algorithm) throws IllegalArgumentException { super(algorithm); } + @Override public Verification createVerifierForExtended(String picture, String email, List issuer, - List audience, String name, long nbf, long expLeeway, long iatLeeway) { + List audience, String name, long nbf, long expLeeway, long iatLeeway) { Verification verification = createVerifierForGoogle(picture, email, issuer, audience, name, expLeeway, iatLeeway); return verification.withNbf(nbf); } 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..7c83c47 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 implements Verification { FbJWT(Algorithm algorithm) throws IllegalArgumentException { super(algorithm); @@ -32,10 +32,12 @@ public class FbJWT extends JWT.BaseVerification implements Verification{ /** * Create Verification object for verification purposes + * * @param userId * @param appId * @return */ + @Override public Verification createVerifierForFb(String userId, String appId) { return withUserId(userId).withAppId(appId); } @@ -46,6 +48,7 @@ public Verification createVerifierForFb(String userId, String appId) { * @param userId the required userId value * @return this same Verification instance. */ + @Override public Verification withUserId(String userId) { requireClaim("userId", userId); return this; @@ -57,6 +60,7 @@ public Verification withUserId(String userId) { * @param appId the required appId value * @return this same Verification instance. */ + @Override public Verification withAppId(String appId) { requireClaim("appId", appId); return this; @@ -101,6 +105,7 @@ public JWT build() { * @param clock the instance that will handle the current time. * @return a new JWT instance with a custom Clock. */ + @Override public JWT build(Clock clock) { addLeewayToDateClaims(); return new JWT(algorithm, claims, clock); 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..203f220 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java @@ -24,10 +24,10 @@ import com.auth0.jwt.interfaces.Clock; import com.auth0.jwt.interfaces.GoogleVerification; import com.auth0.jwt.interfaces.Verification; - +import com.auth0.jwt.interfaces.constants.Constants; import java.util.List; -public class GoogleJWT extends JWT.BaseVerification implements GoogleVerification{ +public class GoogleJWT extends JWT.BaseVerification implements GoogleVerification { GoogleJWT(Algorithm algorithm) throws IllegalArgumentException { super(algorithm); @@ -35,6 +35,7 @@ public class GoogleJWT extends JWT.BaseVerification implements GoogleVerificatio /** * Create Verification object for verification purposes + * * @param picture * @param email * @param issuer @@ -42,6 +43,7 @@ public class GoogleJWT extends JWT.BaseVerification implements GoogleVerificatio * @param name * @return */ + @Override public Verification createVerifierForGoogle(String picture, String email, List issuer, List audience, String name, long expLeeway, long iatLeeway) { return withPicture(picture).withName(name).withEmail(email).withIssuer(issuer.toArray(new String[issuer.size()])).withAudience(audience.toArray(new String[audience.size()])) @@ -56,7 +58,7 @@ public Verification createVerifierForGoogle(String picture, String email, List issuer, - List audience, long iatLeeway) { + List audience, long iatLeeway) { return withIssuer(issuer.toArray(new String[issuer.size()])).withAudience(audience.toArray(new String[audience.size()])) .acceptIssuedAt(iatLeeway); } @@ -84,6 +85,7 @@ public JWT build() { * @param clock the instance that will handle the current time. * @return a new JWT instance with a custom Clock. */ + @Override public JWT build(Clock clock) { addLeewayToDateClaims(); return new JWT(algorithm, claims, clock); 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..dc20a52 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/JWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/JWT.java @@ -20,18 +20,25 @@ package com.auth0.jwt.jwts; import com.auth0.jwt.ClockImpl; -import com.auth0.jwt.creators.EncodeType; -import com.auth0.jwt.creators.JWTCreator; import com.auth0.jwt.JWTDecoder; import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.exceptions.*; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.creators.EncodeType; +import com.auth0.jwt.creators.JWTCreator; +import com.auth0.jwt.exceptions.AlgorithmMismatchException; +import com.auth0.jwt.exceptions.InvalidClaimException; +import com.auth0.jwt.exceptions.SignatureVerificationException; +import com.auth0.jwt.exceptions.TokenExpiredException; import com.auth0.jwt.interfaces.Clock; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.verification.VerificationAndAssertion; - -import java.util.*; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @SuppressWarnings("WeakerAccess") public class JWT { 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..04db9da 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/RiscJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/RiscJWT.java @@ -23,7 +23,6 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.Clock; import com.auth0.jwt.interfaces.Verification; - import java.util.List; public class RiscJWT extends JWT.BaseVerification implements Verification { @@ -34,6 +33,7 @@ public class RiscJWT extends JWT.BaseVerification implements Verification { /** * Create Verification object for verification purposes + * * @param jti * @param issuer * @param audience @@ -41,19 +41,20 @@ public class RiscJWT extends JWT.BaseVerification implements Verification { * @param expLeeway * @return */ + @Override public Verification createVerifierForRisc(String jti, List issuer, List audience, long iatLeeway, long expLeeway, long nbf) { Verification verification = withJWTId(jti).withIssuer(issuer.toArray(new String[issuer.size()])).acceptIssuedAt(iatLeeway); - if(audience != null && !audience.isEmpty()) { + if (audience != null && !audience.isEmpty()) { verification.withAudience(audience.toArray(new String[audience.size()])); } - if(nbf >= 0) { + if (nbf >= 0) { verification.acceptNotBefore(iatLeeway); } - if(expLeeway >= 0) { + if (expLeeway >= 0) { verification.acceptExpiresAt(expLeeway); } @@ -99,6 +100,7 @@ public JWT build() { * @param clock the instance that will handle the current time. * @return a new JWT instance with a custom Clock. */ + @Override public JWT build(Clock clock) { addLeewayToDateClaims(); return new JWT(algorithm, claims, clock); 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..9a2c2ef 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/ScopedJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/ScopedJWT.java @@ -23,10 +23,10 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.Clock; import com.auth0.jwt.interfaces.Verification; - +import com.auth0.jwt.interfaces.constants.Constants; import java.util.List; -public class ScopedJWT extends JWT.BaseVerification implements Verification{ +public class ScopedJWT extends JWT.BaseVerification implements Verification { ScopedJWT(Algorithm algorithm) throws IllegalArgumentException { super(algorithm); @@ -34,11 +34,13 @@ public class ScopedJWT extends JWT.BaseVerification implements Verification{ /** * Create Verification object for verification purposes - * @issuer scope + * * @param issuer * @param audience * @return + * @issuer scope */ + @Override public Verification createVerifierForScoped(String scope, List issuer, List audience, long expLeeway, long iatLeeway) { return withScope(scope).withIssuer(issuer.toArray(new String[issuer.size()])).withAudience(audience.toArray(new String[audience.size()])) @@ -52,7 +54,7 @@ public Verification createVerifierForScoped(String scope, List issuer, * @return this same Verification instance. */ public Verification withScope(String scope) { - requireClaim("scope", scope); + requireClaim(Constants.SCOPE, scope); return this; } @@ -90,11 +92,11 @@ public JWT build() { /** * Creates a new and reusable instance of the JWT the configuration already provided. - * ONLY FOR TEST PURPOSES. * * @param clock the instance that will handle the current time. * @return a new JWT instance with a custom Clock. */ + @Override public JWT build(Clock clock) { addLeewayToDateClaims(); return new JWT(algorithm, claims, clock); diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java b/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java new file mode 100644 index 0000000..c504c0e --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java @@ -0,0 +1,238 @@ +package com.auth0.jwt.oicmsg; + +import com.auth0.jwt.exceptions.oicmsg_exceptions.HeaderError; +import com.auth0.jwt.exceptions.oicmsg_exceptions.SerializationNotPossible; +import java.security.spec.EllipticCurve; +import java.text.ParseException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * JSON Web key representation of a Elliptic curve key. + According to RFC 7517 a JWK representation of a EC key can look like + this:: + {"kty":"EC", + "crv":"P-256", + "x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", + "y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", + "d":"870MB6gfuTJ4HtUnUvYMyJpr5eUZNP4Bk43bVdj3eAE" + } + + Parameters according to https://tools.ietf.org/html/rfc7518#section-6.2 + */ +public class ECKey extends Key { + + private String crv; + private Object x; + private Object y; + private Object d; + private Object curve; + final private static Logger logger = LoggerFactory.getLogger(ECKey.class); + //The elliptic curve specific attributes + private static Set longs = new HashSet(Arrays.asList("x", "y", "d")); + protected static Set members = new HashSet<>(Arrays.asList("kty", "alg", "use", "kid", "crv", "x", "y", "d")); + public static Set publicMembers = new HashSet<>(Arrays.asList("kty", "alg", "use", "kid", "crv", "x", "y")); + protected static Set required = new HashSet<>(Arrays.asList("crv", "key", "x", "y")); + + public ECKey(String kty, String alg, String use, String kid, Key key, String crv, Object x, Object y, Object d, + Object curve, Map args) { + super(kty, alg, use, kid, "", "", "", key, args); + this.crv = crv; + this.x = x; + this.y = y; + this.d = d; + this.curve = curve; + + if (this.crv != null && this.curve == null) { + try { + this.verify(); + } catch (HeaderError headerError) { + headerError.printStackTrace(); + } + this.deserialize(); + } else if (this.getKey() != null && (this.crv == null && this.curve == null)) { + this.loadKey(key); + } + } + + public ECKey() { + this("EC", "", "", "", null, "", null, null, null, null, null); + } + + /** + * Starting with information gathered from the on-the-wire representation + of an elliptic curve key (a JWK) initiate an + cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey + or EllipticCurvePrivateKey instance. So we have to get from having:: + { + "kty":"EC", + "crv":"P-256", + "x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", + "y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", + "d":"870MB6gfuTJ4HtUnUvYMyJpr5eUZNP4Bk43bVdj3eAE" + } + to having a key that can be used for signing/verifying and/or + encrypting/decrypting. + If 'd' has value then we're dealing with a private key otherwise + a public key. 'x' and 'y' must have values. + If this.key has a value beforehand this will overwrite whatever + was there to begin with. + + x, y and d (if present) must be strings or bytes. + */ + public void deserialize() { + try { + if (!(this.x instanceof Number)) { + this.x = deser(this.x); + } + if (!(this.y instanceof Number)) { + this.y = deser(this.y); + } + } catch (ParseException e) { + logger.error("Couldn't parse value"); + } + + this.curve = byName(this.crv); + if (this.d != null) { + if (this.d instanceof String) { + this.d = deser(this.d); + } + } + } + + private EllipticCurve byName(String name) { + if (name.equals("P-256")) { + return EllipticCurve(); + } else if (name.equals("P-384")) { + return EllipticCurve(); + } else if (name.equals("P-521")) { + return EllipticCurve(); + } + } + + public List getKey(boolean isPrivate) { + if (isPrivate) { + return Arrays.asList(this.d); + } else { + return Arrays.asList(this.x, this.y); + } + } + + /** + * Go from a + cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey + or EllipticCurvePublicKey instance to a JWK representation. + * @param isPrivate: Whether we should include the private parts or not. + * @return A JWK as a hashmap + * @throws SerializationNotPossible + */ + public Object serialize(boolean isPrivate) throws SerializationNotPossible { + if (this.crv == null && this.curve == null) { + throw new SerializationNotPossible(); + } + + Map args = common(); + args.put("crv", this.curve.getClass().getName()); + args.put("x", longToBase64(this.x)); + args.put("y", longToBase64(this.y)); + + if (isPrivate && this.d != null) { + args.put("d", longToBase64(this.d)); + } + + return args; + } + + /** + * Load an Elliptic curve key + * @param key: An elliptic curve key instance + * @return + */ + public ECKey loadKey(Key key) { + this.curve = key; + //how to return multiple objects in Java? + return this; + } + + public List getDecryptionKey() { + return this.getKey(true); + } + + public List getEncryptionKey(boolean isPrivate) { + //both for encryption and decryption. + return this.getKey(isPrivate); + } + + public String getCrv() { + return crv; + } + + public void setCrv(String crv) { + this.crv = crv; + } + + public Object getX() { + return x; + } + + public void setX(Object x) { + this.x = x; + } + + public Object getY() { + return y; + } + + public void setY(Object y) { + this.y = y; + } + + public Object getD() { + return d; + } + + public void setD(Object d) { + this.d = d; + } + + public Object getCurve() { + return curve; + } + + public void setCurve(Object curve) { + this.curve = curve; + } + + public static Set getLongs() { + return longs; + } + + public static void setLongs(Set longs) { + ECKey.longs = longs; + } + + public static Set getMembers() { + return members; + } + + public static void setMembers(Set members) { + ECKey.members = members; + } + + public static void setPublicMembers(Set publicMembers) { + ECKey.publicMembers = publicMembers; + } + + public static Set getRequired() { + return required; + } + + public static void setRequired(Set required) { + ECKey.required = required; + } +} diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java b/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java new file mode 100644 index 0000000..5c708f3 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java @@ -0,0 +1,317 @@ +package com.auth0.jwt.oicmsg; + +import com.google.common.base.Strings; +import com.google.gson.Gson; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.junit.Assert; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Basic JSON Web key class. Jason Web keys are described in + RFC 7517 (https://tools.ietf.org/html/rfc7517). + The name of parameters used in this class are the same as + specified in RFC 7518 (https://tools.ietf.org/html/rfc7518). + */ +public class Key { + + final private static Logger logger = LoggerFactory.getLogger(Key.class); + protected String kty; + protected String alg; + protected String use; + protected String kid; + protected String x5c; + protected String x5t; + protected String x5u; + protected Key key; + protected long inactiveSince; + protected Map args; + private static final String SHA_256 = "SHA-256"; + private static final String SHA_384 = "SHA-384"; + private static final String SHA_512 = "SHA-512"; + private static Map longs = new HashMap(); + protected static Set members = new HashSet<>(Arrays.asList("kty", "alg", "use", "kid", "x5c", "x5t", "x5u")); + public static Set publicMembers = new HashSet<>(Arrays.asList("kty", "alg", "use", "kid", "x5c", "x5t", "x5u")); + protected static List required = Arrays.asList("kty"); + private static final List signs = Arrays.asList("+", "/", "="); + + public Key(String kty, String alg, String use, String kid, String x5c, String x5t, String x5u, Key key, Map args) { + this.kty = kty; + this.alg = alg; + this.use = use; + this.kid = kid; + this.x5c = x5c; + this.x5t = x5t; + this.x5u = x5u; + this.inactiveSince = 0; + this.key = key; + this.args = args; + } + + public Key() { + this("", "", "", "", "", "", "", null, null); + } + + public String getX5c() { + return x5c; + } + + public void setX5c(String x5c) { + this.x5c = x5c; + } + + public String getX5t() { + return x5t; + } + + public void setX5t(String x5t) { + this.x5t = x5t; + } + + public String getX5u() { + return x5u; + } + + public void setX5u(String x5u) { + this.x5u = x5u; + } + + public String getKty() { + return kty; + } + + public void setKty(String kty) { + this.kty = kty; + } + + public String getAlg() { + return alg; + } + + public void setAlg(String alg) { + this.alg = alg; + } + + public String getUse() { + return use; + } + + public void setUse(String use) { + this.use = use; + } + + public String getKid() { + return kid; + } + + public void setKid(String kid) { + this.kid = kid; + } + + public void setInactiveSince() { + this.inactiveSince = System.currentTimeMillis(); + } + + public long getInactiveSince() { + return inactiveSince; + } + + /** + * A wrapper for to_dict that makes sure that all the private information + as well as extra arguments are included. This method should *not* be + used for exporting information about the key. + * @return + */ + public Map toDict() { + Map hmap = serialize(); + for (String key : args.keySet()) { + hmap.put(key, args.get(key)); + } + return hmap; + } + + public Key serialize() { + Map hmap = common(); + this.key. + //TODO + } + + /** + * Return the set of parameters that are common to all types of keys. + * @return: hashmap + */ + public Map common() { + Map args = new HashMap<>(); + args.put("kty", this.kty); + if (!Strings.isNullOrEmpty(this.use)) { + args.put("use", this.use); + } + if (!Strings.isNullOrEmpty(this.kid)) { + args.put("kid", this.kid); + } + if (!Strings.isNullOrEmpty(this.alg)) { + args.put("alg", this.alg); + } + return args; + } + + @Override + public String toString() { + return this.toDict().toString(); + } + + /** + * Verify that the information gathered from the on-the-wire + representation is of the right type. + This is supposed to run before the info is deserialized. + * @return + * @throws HeaderError + */ + public boolean verify() throws HeaderError { + Object item = null; + for (String key : longs.keySet()) { + + try { + item = this.getClass().getField(key).get(this); + } catch (Exception e1) { + logger.error("Field " + key + " doesn't exist"); + } + if (item == null || item instanceof Number) { + continue; + } + + if (item instanceof Bytes) { + + //item = item.decode('utf-8') ??? + //TODO + } + + try { + base64URLToLong(item); + } catch (Exception e) { + return false; + } + for (String sign : signs) { + if (((String) item).contains(sign)) { + return false; + } + } + + if (!Strings.isNullOrEmpty(this.kid)) { + try { + Assert.assertTrue(this.kid instanceof String); + } catch (AssertionError error) { + throw new HeaderError("kid of wrong value type"); + } + } + } + + return true; + } + + private void base64URLToLong(Object item) { + + } + + /** + * Compare 2 Key instances to find out if they represent the same key + * @param other: The other Key instance + * @return True if they are the same otherwise False. + */ + @Override + public boolean equals(Object other) { + try { + Assert.assertTrue(other instanceof Key); + //Assert.assertTrue(); //TODO + Key otherKey = (Key) other; + Assert.assertEquals(this.getKty(), otherKey.kty); + Assert.assertEquals(this.getAlg(), otherKey.alg); + Assert.assertEquals(this.getUse(), otherKey.use); + Assert.assertEquals(this.getKid(), otherKey.kid); + Assert.assertEquals(this.getX5c(), otherKey.x5c); + Assert.assertEquals(this.getX5t(), otherKey.x5t); + Assert.assertEquals(this.getX5u(), otherKey.x5u); + } catch (AssertionError error) { + return false; + } + return true; + } + + public List getKeys() { + return new ArrayList<>(this.toDict().keySet()); + } + + /** + * Create a thumbprint of the key following the outline in + https://tools.ietf.org/html/draft-jones-jose-jwk-thumbprint-01 + * @param hashFunction: A hash function to use for hashing the + information + * @param members: Which attributes of the Key instance should + be included when computing the hash value. + * @return A base64 encode hash over a set of Key attributes + * @throws NoSuchFieldException + */ + public byte[] thumbprint(String hashFunction, List members) throws NoSuchFieldException { + if (members == null || members.isEmpty()) { + members = required; + } + + Collections.sort(members); + Key key = this.serialize(); + String value = null; + Map hmap = new HashMap<>(); + for (String member : members) { + value = key.getClass().getField(member).toString(); + hmap.put(member, value); + } + + String json = new Gson().toJson(hmap); + byte[] byteArr = null; + switch (hashFunction) { + case SHA_256: + byteArr = sha256_digest(json); + break; + case SHA_384: + byteArr = sha384_digest(json); + break; + case SHA_512: + byteArr = sha512_digest(json); + break; + default: + throw new IllegalArgumentException("improper hash function"); + } + + return byteArr; + } + + public byte[] thumbprint(String hashFunction) { + thumbprint(hashFunction, null); + } + + /** + * Construct a Key ID using the thumbprint method and add it to + the key attributes. + */ + public void addKid() { + this.kid = new String(Base64.encode(this.thumbprint("SHA-256"))); + } + + + //https://stackoverflow.com/questions/5729806/encode-string-to-utf-8 can't encode string to utf-8 + /*protected static void deser(Object item) { + if(item instanceof String) { + item.en + } + + + + return base64ToLong(item); + }*/ +} diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java new file mode 100644 index 0000000..5f0d861 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java @@ -0,0 +1,636 @@ +package com.auth0.jwt.oicmsg; + +import com.auth0.jwt.exceptions.oicmsg_exceptions.ImportException; +import com.auth0.jwt.exceptions.oicmsg_exceptions.TypeError; +import com.auth0.jwt.exceptions.oicmsg_exceptions.UnknownKeyType; +import com.auth0.jwt.exceptions.oicmsg_exceptions.UpdateFailed; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableMap; +import com.google.gson.Gson; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.security.KeyException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.util.EntityUtils; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import sun.reflect.generics.reflectiveObjects.NotImplementedException; + +/** + * Contains a set of keys that have a common origin. + The sources can be several: + - A dictionary provided at the initialization, see keys below. + - A list of dictionaries provided at initialization + - A file containing one of: JWKS, DER encoded key + - A URL pointing to a webpage from which a JWKS can be downloaded + */ +public class KeyBundle { + + final private static Logger logger = LoggerFactory.getLogger(KeyBundle.class); + private static final Map K2C = + ImmutableMap.of(RSA_KEY, new RSAKey(), + "EC", new ECKey(), + "oct", new SYMKey() + ); + private static final Map map = + ImmutableMap.of("dec", "enc", + "enc", "enc", + "ver", "sig", + "sig", "sig" + ); + private static final Set fileTypes = new HashSet(Arrays.asList("rsa", DER, JWKS)); + private java.util.List keys; + private Map> impJwks; + private String source; + private long cacheTime; + private boolean verifySSL; + private String fileFormat; + private String keyType; + private List keyUsage; + private boolean remote; + private long timeOut; + private String eTag; + private static final String JWKS = "jwks"; + private static final String JWK = "jwk"; + private static final String DER = "der"; + private static final String EC_KEY = "EC"; + private static final String RSA_KEY = "RSA"; + private static final String SYM_KEY = "SYMKey"; + private long lastUpdated; + + /** + * + * @param keys: A dictionary or a list of dictionaries + with the keys ["kty", "key", "alg", "use", "kid"] + * @param source: Where the key set can be fetched from + * @param verifySSL: Verify the SSL cert used by the server + * @param fileFormat: For a local file either "jwk" or "der" + * @param keyType: Iff local file and 'der' format what kind of key it is. + presently only 'rsa' is supported. + * @param keyUsage: What the key loaded from file should be used for. + Only applicable for DER files + * @throws ImportException + */ + public KeyBundle(List keys, String source, long cacheTime, boolean verifySSL, + String fileFormat, String keyType, List keyUsage) throws ImportException { + this.keys = keys; + this.cacheTime = cacheTime; + this.verifySSL = verifySSL; + this.fileFormat = fileFormat.toLowerCase(); + this.keyType = keyType; + this.keyUsage = keyUsage; + this.remote = false; + this.timeOut = 0; + this.impJwks = new HashMap>(); + this.lastUpdated = 0; + this.eTag = ""; + + if (keys != null) { + this.source = null; + //doKeys(this.keys); why is this here? + } else { + if ("file://".startsWith(source)) { + this.source = source.substring(7); + } else if ("http://".startsWith(source) || "https://".startsWith(source)) { + this.source = source; + this.remote = true; + } else if (!Strings.isNullOrEmpty(source)) { + this.source = null; + } else { + if (fileTypes.contains(fileFormat.toLowerCase())) { + File file = new File(source); + if (file.exists() && file.isFile()) { + this.source = source; + } else { + throw new ImportException("No such file exists"); + } + } else { + throw new ImportException("Unknown source"); + } + } + + if (!this.remote) { + if (this.JWKS.equals(fileFormat) || this.JWK.equals(fileFormat)) { + try { + this.doLocalJwk(this.source); + } catch (UpdateFailed updateFailed) { + logger.error("Local key updated from " + this.source + " failed."); + } + } else if (this.fileFormat.equals(DER)) { + doLocalDer(this.source, this.keyType, this.keyUsage); + } + } + } + } + + public KeyBundle() throws ImportException { + this(null, "", 300, true, JWK, RSA_KEY, null); + } + + public KeyBundle(List keyList, String keyType) throws ImportException { + this(keyList, "", 300, true, JWK, keyType, null); + } + + public KeyBundle(List keyList, String keyType, List usage) throws ImportException { + this(keyList, "", 300, true, JWK, keyType, usage); + } + + public KeyBundle(String source, boolean verifySSL) throws ImportException { + this(null, source, 300, verifySSL, JWK, RSA_KEY, null); + } + + public KeyBundle(String source, String fileFormat, List usage) throws ImportException { + this(null, source, 300, true, fileFormat, RSA_KEY, usage); + } + + /** + * Go from JWK description to binary keys + * @param keys + */ + public void doKeys(List keys) { + for (Key keyIndex : keys) { + final String kty = keyIndex.getKty(); + List usage = harmonizeUsage(Arrays.asList(keyIndex.getUse())); + keys.remove("use"); + boolean flag = false; + for (String use : usage) { + if (RSA_KEY.equalsIgnoreCase(kty)) { + key = new RSAKey(use); + } else if (EC_KEY.equalsIgnoreCase(kty)) { + key = new ECKey(use); + } else if (SYM_KEY.equalsIgnoreCase(kty)) { + key = new SYMKey(use); + } else { + throw new IllegalArgumentException("Encryption type: " + typeIndex + " isn't supported"); + } + this.keys.add(key); + flag = true; + } + + if (!flag) { + logger.warn("While loading keys, UnknownKeyType: " + kty); + } + } + } + + private static List harmonizeUsage(List uses) { + Set keys = map.keySet(); + Set usagesSet = new HashSet<>(); + for (String use : uses) { + if (keys.contains(use)) { + usagesSet.add(use); + } + } + return new ArrayList<>(usagesSet); + } + + /** + * Load a JWKS from a local file + * @param fileName + * @throws UpdateFailed + */ + public void doLocalJwk(String fileName) throws UpdateFailed { + JSONParser parser = new JSONParser(); + try { + Object obj = parser.parse(new FileReader( + fileName)); + JSONObject jsonObject = (JSONObject) obj; + JSONArray keys = (JSONArray) jsonObject.get("keys"); + Iterator iterator = keys.iterator(); + List keysList = new ArrayList(); + Gson gson = new Gson(); + while (iterator.hasNext()) { + keysList.add(gson.fromJson(iterator.next(), Key.class)); + } + doKeys(keysList); + } catch (Exception e) { + logger.error("Now 'keys' keyword in JWKS"); + throw new UpdateFailed("Local key updated from " + fileName + " failed."); + } finally { + this.lastUpdated = System.currentTimeMillis(); + } + } + + /** + * Load a DER encoded file and create a key from it. + * @param fileName + * @param keyType: Presently only 'rsa' is supported + * @param keyUsage: encryption ('enc') or signing ('sig') or both + * @throws NotImplementedException + */ + public void doLocalDer(String fileName, String keyType, List keyUsage) throws NotImplementedException { + RSAKey rsaKey = rsaLoad(fileName); + + if (!keyType.equalsIgnoreCase(RSA_KEY)) { + throw new NotImplementedException(); + } + + if (keyUsage.isEmpty()) { + keyUsage = new ArrayList() {{ + add("enc"); + add("sig"); + }}; + } else { + keyUsage = harmonizeUsage(keyUsage); + } + + for (String use : keyUsage) { + RSAKey key = new RSAKey().loadKey(rsaKey); + key.setUse(use); + this.keys.add(key); + } + this.lastUpdated = System.currentTimeMillis(); + } + + /** + * Load a JWKS from a webpage + * @return True or False if load was successful + * @throws UpdateFailed + * @throws KeyException + */ + public boolean doRemote() throws UpdateFailed, KeyException { + Map args = new HashMap<>(); + args.put("verify", this.verifySSL); + if (!this.eTag.isEmpty()) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("If-None-Match", this.eTag); + args.put("headers", jsonObject); + } + + int statusCode; + HttpResponse response; + try { + logger.debug("KeyBundle fetch keys from: " + this.source); + HttpClient httpclient = new DefaultHttpClient(); + HttpGet httpget = new HttpGet(this.source); + response = httpclient.execute(httpget); + statusCode = response.getStatusLine().getStatusCode(); + } catch (Exception e) { + logger.error(e.getMessage()); + throw new UpdateFailed("Couldn't make GET request to url: " + this.source); + } + + if (statusCode == 304) { + this.timeOut = System.currentTimeMillis() + this.cacheTime; + this.lastUpdated = System.currentTimeMillis(); + + List keys = this.impJwks.get("keys"); + if (keys != null) { + doKeys(keys); + } else { + logger.error("No 'keys' keyword in JWKS"); + throw new UpdateFailed("No 'keys' keyword in JWKS"); + } + } else if (statusCode == 200) { + this.timeOut = System.currentTimeMillis() + this.cacheTime; + try { + this.impJwks = parseRemoteResponse(response); + } catch (Exception exception) { + exception.printStackTrace(); + } + + if (!this.impJwks.keySet().contains("keys")) { + throw new UpdateFailed(this.source); + } + + logger.debug("Loaded JWKS: " + response.toString() + " from " + this.source); + List keys = this.impJwks.get("keys"); + if (keys != null) { + doKeys(keys); + } else { + logger.error("No 'keys' keyword in JWKS"); + throw new UpdateFailed("No 'keys' keyword in JWKS"); + } + + Header[] headers = response.getHeaders("Etag"); + if (headers != null) { + this.eTag = headers; + } else { + throw new KeyException("No 'Etag' keyword in headers"); + } + } else { + throw new UpdateFailed("Source: " + this.source + " status code: " + statusCode); + } + + this.lastUpdated = System.currentTimeMillis(); + return true; + } + + /** + * Parse JWKS from the HTTP response. + Should be overriden by subclasses for adding support of e.g. signed + JWKS. + * @param response: HTTP response from the 'jwks_uri' endpoint + * @return response parsed as JSON + * @throws IOException + * @throws ParseException + */ + private JSONObject parseRemoteResponse(HttpResponse response) throws IOException, ParseException { + if (!response.getHeaders("Content-Type").equals("application/json")) { + logger.warn("Wrong Content_type"); + } + + logger.debug(String.format("Loaded JWKS: %s from %s", response.toString(), this.source)); + + return (JSONObject) new JSONParser().parse(EntityUtils.toString(response.getEntity())); + } + + private boolean upToDate() { + + boolean result = false; + if (!this.keys.isEmpty()) { + if (this.remote && System.currentTimeMillis() > this.timeOut && update()) { + result = true; + } + } else if (this.remote) { + if (update()) { + result = true; + } + } + + return result; + } + + /** + * Reload the keys if necessary + This is a forced update, and it will only happen if cache time has not elapsed + Replaced keys will be marked as inactive and not removed. + * @return True or False + */ + public boolean update() { + boolean result = true; + if (!this.source.isEmpty()) { + List keys = this.keys; + this.keys = new ArrayList(); + try { + if (!this.remote) { + if (this.fileFormat.equals(JWKS)) { + this.doLocalJwk(this.source); + } else if (this.fileFormat.equals(DER)) { + doLocalDer(source, keyType, keyUsage); + } + } else { + result = doRemote(); + } + } catch (Exception exception) { + logger.error("Key bundle updated failed: " + exception.toString()); + this.keys = keys; + return false; + } + + for (Key key : keys) { + if (!keys.contains(key)) { + if (key.getInactiveSince() == Long.MIN_VALUE) { + key.setInactiveSince(); + } + } + this.keys.add(key); + } + } + return result; + } + + /** + * Return a list of keys. Either all keys or only keys of a specific type + * @param typ: Type of key (rsa, ec, oct, ..) + * @return If typ is undefined, return all the keys as a dictionary + otherwise the appropriate keys in a list + */ + public List get(String typ) { + + this.upToDate(); + List types = Arrays.asList(typ.toLowerCase(), typ.toUpperCase()); + + if (!typ.isEmpty()) { + List keys = new ArrayList<>(); + for (Key key : this.keys) { + if (types.contains(key.getKty())) { + keys.add(key); + } + } + return keys; + } else { + return this.keys; + } + } + + /** + * Return all keys after having updated them + * @return List of all keys + */ + public List getKeys() { + this.upToDate(); + return this.keys; + } + + public String getSource() { + return source; + } + + public List getActiveKeys() { + List activeKeys = new ArrayList<>(); + for (Key key : this.keys) { + if (key.getInactiveSince() == 0) { + activeKeys.add(key); + } + } + + return activeKeys; + } + + /** + * Remove keys that are of a specific kind or kind and value. + * @param typ: Type of key (rsa, ec, oct, ..) + */ + public void removeKeysByType(String typ) { + List types = Arrays.asList(typ.toLowerCase(), typ.toUpperCase()); + + for (Key key : this.keys) { + if (!types.contains(key.getKty())) { + this.keys.remove(key); + } + } + } + + @Override + public String toString() { + return this.jwks(); + } + + /** + * Create a JWKS + * @param isPrivate: Whether private key information should be included. + * @return: A JWKS representation of the keys in this bundle + */ + public String jwks(boolean isPrivate) { + this.upToDate(); + List keys = new ArrayList<>(); + Key key; + for (Key keyIndex : this.keys) { + if (isPrivate) { + key = keyIndex.serialize(isPrivate); + } else { + key = keyIndex.toDict(); + //TODO + } + } + } + + public String jwks() { + return jwks(false); + } + + /** + * Add a key to the list of keys in this bundle + * @param key: Key to be added + */ + public void append(Key key) { + this.keys.add(key); + } + + /** + * Remove a specific key from this bundle + * @param key: The key that should be removed + */ + public void remove(Key key) { + this.keys.remove(key); + } + + /** + * The number of keys + * @return: The number of keys + */ + public int getLength() { + return this.keys.size(); + } + + /** + * Return the key that is specified by key ID (kid) + * @param kid: The Key ID + * @return The key or None + */ + public Key getKeyWithKid(String kid) { + for (Key key : this.keys) { + if (key.getKid().equals(kid)) { + return key; + } + } + + //Try updating since there might have been an update to the key file + update(); + + for (Key key : this.keys) { + if (key.getKid().equals(kid)) { + return key; + } + } + + return null; + } + + /** + * Return a list of key IDs. Note that list may be shorter than + the list of keys. + * @return A list of all the key IDs that exists in this bundle + */ + public List getKids() { + this.upToDate(); + List kids = new ArrayList<>(); + for (Key key : this.keys) { + if (!key.getKid().isEmpty()) { + kids.add(key.getKid()); + } + } + + return kids; + } + + /** + * Mark a specific key as inactive based on the key's KeyID + * @param kid: The Key Identifier + */ + public void markAsInactive(String kid) { + Key key = getKeyWithKid(kid); + key.setInactiveSince(); + } + + /** + * Remove keys that should not be available anymore. + Outdated means that the key was marked as inactive at a time + that was longer ago than what is given in 'after'. + * @param after: The length of time the key will remain in the KeyBundle + before it should be removed. + * @param when: To make it easier to test + * @throws TypeError + */ + public void removeOutdated(float after, int when) throws TypeError { + long now; + if (when != 0) { + now = when; + } else { + now = System.currentTimeMillis(); + } + + List keys = new ArrayList<>(); + for (Key key : this.keys) { + if (!(key.getInactiveSince() && (key.getInactiveSince() + after < now))) { + keys.add(key); + } + } + + this.keys = keys; + } + + + /** + * Create a KeyBundle based on the content in a local file + * @param filename: Name of the file + * @param type: Type of content + * @param usage: What the key should be used for + * @return The created KeyBundle + * @throws ImportException + * @throws UnknownKeyType + */ + public KeyBundle keyBundleFromLocalFile(String filename, String type, List usage) throws ImportException, UnknownKeyType { + usage = harmonizeUsage(usage); + KeyBundle keyBundle; + type = type.toLowerCase(); + if (JWKS.equals(type)) { + keyBundle = new KeyBundle(filename, JWKS, usage); + } else if (DER.equals(type)) { + keyBundle = new KeyBundle(filename, DER, usage); + } else { + throw new UnknownKeyType("Unsupported key type"); + } + + return keyBundle; + } + + /** + * Write a JWK to a file. Will ignore symmetric keys !! + * @param kbl: List of KeyBundles + * @param target: Name of the file to which everything should be written + * @param isPrivate: Should the private parts also be exported + */ + public void dumpJwks(List kbl, String target, boolean isPrivate) { + throw new UnsupportedOperationException(); + } + + +} diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/KeyJar.java b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyJar.java new file mode 100644 index 0000000..d543839 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyJar.java @@ -0,0 +1,479 @@ +package com.auth0.jwt.oicmsg; + +import com.auth0.jwt.exceptions.oicmsg_exceptions.ImportException; +import com.auth0.jwt.exceptions.oicmsg_exceptions.TypeError; +import com.auth0.jwt.impl.JWTParser; +import com.auth0.jwt.jwts.JWT; +import com.google.common.base.Strings; +import java.security.KeyException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Assert; +import org.slf4j.LoggerFactory; + +/** + * A keyjar contains a number of keybundles + */ +public class KeyJar { + + private boolean verifySSL; + private KeyBundle keyBundle; + private float removeAfter; + private Map> issuerKeys; + private static final String OCT = "oct"; + private static final String ENC = "enc"; + private static final String DEC = "dec"; + private static final String SIG = "sig"; + private static final String EC = "EC"; + private static final String ALG = "alg"; + private static final String RSA = "RSA"; + final private static org.slf4j.Logger logger = LoggerFactory.getLogger(KeyJar.class); + + /** + * + * @param verifySSL: CA certificates, to be used for HTTPS + * @param keyBundle: Attempting SSL certificate verification + * @param removeAfter + */ + public KeyJar(boolean verifySSL, KeyBundle keyBundle, int removeAfter) { + this.verifySSL = verifySSL; + this.keyBundle = keyBundle; + this.removeAfter = removeAfter; + } + + public KeyJar() throws ImportException { + this.verifySSL = true; + this.keyBundle = new KeyBundle(); + this.removeAfter = 3600; + } + + /** + * Add a set of keys by url. This method will create a + `KeyBundle` instance with the url as source specification. + * @param owner: Who issued the keys + * @param url: Where can the key(s) be found + * @param args: extra parameters for instantiating KeyBundle + * @return A `KeyBundle` instance + * @throws KeyException + * @throws ImportException + */ + public KeyBundle addUrl(String owner, String url, Map args) throws KeyException, ImportException { + if (Strings.isNullOrEmpty(url)) { + throw new KeyException("No jwksUri"); + } + + KeyBundle keyBundle; + if (url.contains("/localhost:") || url.contains("/localhost/")) { + keyBundle = new KeyBundle(url, false); + } else { + keyBundle = new KeyBundle(url, verifySSL); + } + + addKeyBundle(owner, keyBundle); + + return keyBundle; + } + + /** + * Add a symmetric key. This is done by wrapping it in a key bundle + cloak since KeyJar does not handle keys directly but only through + key bundles. + * @param owner: Owner of the key + * @param key: The key + * @param usage: What the key can be used for signing/signature + verification (sig) and/or encryption/decryption (enc) + * @throws ImportException + */ + public void addSymmetricKey(String owner, Key key, List usage) throws ImportException { + if (!issuerKeys.containsKey(owner)) { + issuerKeys.put(owner, new ArrayList()); + } + + Key key = b64e(key.toString().getBytes()); + if (usage == null || usage.isEmpty()) { + List kbList = new ArrayList<>(); + List keyList = Arrays.asList(key); + KeyBundle kb = new KeyBundle(keyList, OCT); + kbList.add(kb); + issuerKeys.put(owner, kbList); + } else { + List kbList; + List keyList; + KeyBundle kb; + List usageList = new ArrayList<>(); + for (String use : usage) { + kbList = issuerKeys.get(owner); + keyList = Arrays.asList(key); + usageList.add(use); + kb = new KeyBundle(keyList, OCT, usageList); + kbList.add(kb); + issuerKeys.put(owner, kbList); + } + } + } + + /** + * Add a key bundle and bind it to an identifier + * @param owner: Owner of the keys in the keybundle + * @param keyBundle + */ + public void addKeyBundle(String owner, KeyBundle keyBundle) { + List kbList; + if (issuerKeys.get(owner) == null) { + kbList = Arrays.asList(keyBundle); + issuerKeys.put(owner, kbList); + } else { + kbList = issuerKeys.get(owner); + kbList.add(keyBundle); + issuerKeys.put(owner, kbList); + } + } + + /** + * Get all owner ID's and their key bundles + * @return list of 2-tuples (Owner ID., list of KeyBundles) + */ + public Collection> getItems() { + return this.issuerKeys.values(); + } + + /** + * Get all keys that match a set of search criteria + * @param keyUse: A key useful for this usage (enc, dec, sig, ver) + * @param keyType: Type of key (rsa, ec, oct, ..) + * @param owner: Who is the owner of the keys, "" == me + * @param kid: A Key Identifier + * @param args + * @return A possibly empty list of keys + */ + public List getKeys(String keyUse, String keyType, String owner, String kid, Map args) { + String use; + if (keyUse.equals(DEC) || keyUse.equals(ENC)) { + use = ENC; + } else { + use = SIG; + } + + List keyBundleList = null; + if (!Strings.isNullOrEmpty(owner)) { + keyBundleList = this.issuerKeys.get(owner); + + if (keyBundleList == null) { + if (owner.endsWith("/")) { + keyBundleList = this.issuerKeys.get(owner.substring(0, owner.length() - 1)); + } else { + keyBundleList = this.issuerKeys.get(owner + "/"); + } + } + } else { + keyBundleList = this.issuerKeys.get(owner); + } + + if (keyBundleList == null) { + return new ArrayList<>(); + } + + List keyListReturned = new ArrayList<>(); + List keyList = new ArrayList<>(); + for (KeyBundle keyBundle : keyBundleList) { + if (!Strings.isNullOrEmpty(keyType)) { + keyList = keyBundle.get(keyType); + } else { + keyList = keyBundle.getKeys(); + } + + for (Key key : keyList) { + //Skip inactive keys unless for signature verification + if (key.getInactiveSince() == 0 && !SIG.equals(keyUse)) { + continue; + } + if (key.getUse() != null || use.equals(key.getUse())) { + if (kid != null) { + if (key.getKid().equals(kid)) { + keyListReturned.add(key); + break; + } + } else { + keyListReturned.add(key); + } + } + } + } + + String name; + //if elliptic curve, have to check I have a key of the right curve + if (keyType.equals(EC) && args.containsKey(ALG)) { + name = "P-{}" + args.get(ALG).substring(2); + List tempKeyList = new ArrayList<>(); + for (Key key : keyList) { + try { + Assert.assertTrue(name.equals(((ECKey) key).getCrv())); + } catch (AssertionError error) { + continue; + } finally { + tempKeyList.add(key); + } + } + keyList = tempKeyList; + } + + //Add my symmetric keys + if (use.equals(ENC) && keyType.equals(OCT) && !Strings.isNullOrEmpty(owner)) { + for (KeyBundle keyBundle : this.issuerKeys.get("")) { + for (Key key : keyBundle.get(keyType)) { + if (key.getUse() == null || key.getUse().equals(use)) { + keyList.add(key); + } + } + } + } + + return keyList; + } + + public List getSigningKey(String keyType, String owner, String kid, Map args) { + return getKeys(SIG, keyType, owner, kid, args); + } + + public List getVerifyKey(String keyType, String owner, String kid, Map args) { + return getKeys("ver", keyType, owner, kid, args); + } + + public List getEncryptKey(String keyType, String owner, String kid, Map args) { + return getKeys(ENC, keyType, owner, kid, args); + } + + public List getDecryptKey(String keyType, String owner, String kid, Map args) { + return getKeys(DEC, keyType, owner, kid, args); + } + + public List keysByAlgAndUsage(String issuer, String algorithm, String usage) { + String keyType; + if (usage.equals(SIG) || usage.equals("ver")) { + keyType = algorithmToKeytypeForJWS(algorithm); + } else { + keyType = algorithmToKeytypeForJWE(algorithm); + } + + return getKeys(usage, keyType, issuer, null, null); + } + + public List getIssuerKeys(String issuer) { + List keyList = new ArrayList<>(); + for (KeyBundle keyBundle : this.issuerKeys.get(issuer)) { + keyList.addAll(keyBundle.getKeys()); + } + return keyList; + } + + private String algorithmToKeytypeForJWS(String algorithm) { + if (algorithm == null || algorithm.equalsIgnoreCase("none")) { + return "none"; + } else if (algorithm.startsWith("RS") || algorithm.startsWith("PS")) { + return RSA; + } else if (algorithm.startsWith("HS") || algorithm.startsWith("A")) { + return OCT; + } else if (algorithm.startsWith("ES") || algorithm.startsWith("ECDH-ES")) { + return EC; + } else { + return null; + } + } + + private String algorithmToKeytypeForJWE(String algorithm) { + if (algorithm.startsWith(RSA)) { + return RSA; + } else if (algorithm.startsWith("A")) { + return OCT; + } else if (algorithm.startsWith("ECDH")) { + return EC; + } else { + return null; + } + } + + public String matchOwner(String url) throws KeyException { + for (String key : this.issuerKeys.keySet()) { + if (url.startsWith(key)) { + return key; + } + } + + throw new KeyException(String.format("No keys for %s", url)); + } + + /** + * Fetch keys from another server + * @param pcr: The provider information + * @param issuer: The provider URL + * @param shouldReplace: If all previously gathered keys from this provider + should be replaced. + @return: hashmap with usage as key and keys as values + */ + public void loadKeys(Map pcr, String issuer, boolean shouldReplace) { + logger.debug("loading keys for issuer: " + issuer); + + if (shouldReplace || !this.issuerKeys.keySet().contains(issuer)) { + this.issuerKeys.put(issuer, new ArrayList()); + } + + //this.addUrl(null, issuer, pcr.get("jwks_uri")); ?? + } + + /** + * Find a key bundle based on the source of the keys + * @param source: A source url + * @param issuer: The issuer of keys + * @return + */ + public KeyBundle find(String source, String issuer) { + for (KeyBundle keyBundle : this.issuerKeys.get(issuer)) { + if (keyBundle.getSource().equals(source)) { + return keyBundle; + } + } + + return null; + } + + /** + * Produces a hashmap that later can be easily mapped into a + JSON string representing a JWKS. + * @param isPrivate + * @param issuer + * @return + */ + public Map> exportsJwks(boolean isPrivate, String issuer) { + List keys = new ArrayList<>(); + for (KeyBundle keyBundle : this.issuerKeys.get(issuer)) { + for (Key key : keyBundle.getKeys()) { + if (key.getInactiveSince() == 0) { + keys.addAll(key.serialize()); + } + } + } + + Map> keysMap = new HashMap<>(); + keysMap.put("keys", keys); + return keysMap; + } + + public Map> exportJwksAsJson(boolean isPrivate, String issuer) { + return this.exportsJwks(isPrivate, issuer); + } + + /** + * + * @param jwks: Dictionary representation of a JWKS + * @param issuer: Who 'owns' the JWKS + * @throws ImportException + */ + public void importJwks(Map jwks, String issuer) throws ImportException { + String keys = jwks.get("keys"); + List keyBundleList = this.issuerKeys.get(Constants.ISSUER); + if (keyBundleList == null) { + keyBundleList = new ArrayList<>(); + } + + keyBundleList.add(new KeyBundle(keys, this.verifySSL)); + this.issuerKeys.put(issuer, keyBundleList); + } + + public void importJwksAsJson(String js, String issuer) { + importJwks(); + } + + /** + * Goes through the complete list of issuers and for each of them removes + outdated keys. Outdated keys are keys that have been marked as inactive at a time that + is longer ago than some set number of seconds. The number of seconds carried in + the remove_after parameter. + * @param when + * @throws TypeError + */ + public void removeOutdated(int when) throws TypeError { + List keyBundleList; + for (String owner : this.issuerKeys.keySet()) { + keyBundleList = new ArrayList<>(); + for (KeyBundle keyBundle : this.issuerKeys.get(owner)) { + keyBundle.removeOutdated(this.removeAfter, when); + if (keyBundle.getLength() > 0) { + keyBundleList.add(keyBundle); + } + } + + if (keyBundleList.size() > 0) { + this.issuerKeys.put(owner, keyBundleList); + } else { + this.issuerKeys.remove(owner); + } + } + } + + public List addKey(List keys, String owner, String use, String keyType, String kid, + Map> noKidIssuer) { + if (!this.issuerKeys.keySet().contains(owner)) { + logger.error("Issuer " + owner + " not in keyjar"); + return keys; + } + + logger.debug("Key set summary for " + owner + " : " + keySummary(this, owner)); + + if (kid != null) { + for (Key key : this.getKeys(use, owner, kid, keyType, null)) { + if (key != null && !keys.contains(key)) { + keys.add(key); + } + } + return keys; + } else { + List keyList = this.getKeys(use, "", owner, keyType, null); + if (keyList.size() == 0) { + return keys; + } else if (keyList.size() == 1) { + if (!keys.contains(keyList.get(0))) { + keys.add(keyList.get(0)); + } + } else if (noKidIssuer != null) { + List allowedKids = noKidIssuer.get(owner); + if (allowedKids != null) { + for (Key key : keyList) { + if (allowedKids.contains(key.getKid())) { + keys.add(key); + } + } + } else { + keys.addAll(keyList); + } + } + } + return keys; + } + + /** + * Get decryption keys from a keyjar. These keys should be usable to decrypt an encrypted JWT. + * @param jwt: a JWT instance + * @param args: other keyword arguments + * @return: list of usable keys + */ + public void getJwtVerifyKeys(JWT jwt, Map args) { + List keyList = new ArrayList<>(); + JWTParser converter = new JWTParser(); + String keyType = algorithmToKeytypeForJWS(converter.parseHeader(jwttoString().getHeader().getAlgorithm().getName()); + String kid = jwt.getHeader().; + String nki = args.get("no_kid_issuer"); + + } + + public KeyJar copy() throws ImportException { + KeyJar keyJar = new KeyJar(); + for (String owner : this.issuerKeys.keySet()) { + //kj[owner] = [kb.copy() for kb in self[owner]]; how is kj[owner] being caled?? + } + return keyJar; + } +} diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java b/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java new file mode 100644 index 0000000..3d90f92 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java @@ -0,0 +1,250 @@ +package com.auth0.jwt.oicmsg; + +import com.auth0.jwt.exceptions.oicmsg_exceptions.DeserializationNotPossible; +import com.auth0.jwt.exceptions.oicmsg_exceptions.SerializationNotPossible; +import com.google.common.base.Strings; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.bouncycastle.util.encoders.Base64; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * JSON Web key representation of a RSA key + The name of parameters used in this class are the same as + specified in the RFC 7517. + + According to RFC7517 the JWK representation of a RSA (public key) can be + something like this: + + { + "kty":"RSA", + "use":"sig", + "kid":"1b94c", + "n":"vrjOfz9Ccdgx5nQudyhdoR17V-IubWMeOZCwX_jj0hgAsz2J_pqYW08 + PLbK_PdiVGKPrqzmDIsLI7sA25VEnHU1uCLNwBuUiCO11_-7dYbsr4iJmG0Q + u2j8DsVyT1azpJC_NG84Ty5KKthuCaPod7iI7w0LK9orSMhBEwwZDCxTWq4a + YWAchc8t-emd9qOvWtVMDC2BXksRngh6X5bUYLy6AyHKvj-nUy1wgzjYQDwH + MTplCoLtU-o-8SNnZ1tmRoGE9uJkBLdh5gFENabWnU5m1ZqZPdwS-qo-meMv + VfJb6jJVWRpl2SUtCnYG2C32qvbWbjZ_jBPD5eunqsIo1vQ", + "e":"AQAB", + } + + Parameters according to https://tools.ietf.org/html/rfc7518#section-6.3 + */ +public class RSAKey extends Key { + + final private static Logger logger = LoggerFactory.getLogger(RSAKey.class); + //The parameters that represent long ints in the key instances + private static Set longs = new HashSet(Arrays.asList("n", "e", "d", "p", "q", "dp", "dq", "di", "qi")); + private String n; + private String e; + private String d; + private String p; + private String q; + private String dp; + private String dq; + private String di; + private String qi; + private RSAKey key; + + public RSAKey(String kty, String alg, String use, String kid, String x5c, String x5t, String x5u, Key key, String n, + String e, String d, String p, String q, String dp, String dq, String di, String qi, Map args) { + super(kty, alg, use, kid, x5c, x5t, x5u, key, args); + //These are the RSA key specific parameters. They are always supposed to + //be strings or bytes + members.addAll(Arrays.asList("n", "e", "d", "p", "q")); + //the public members of the key + publicMembers.addAll(Arrays.asList("n", "e")); + required = new HashSet(Arrays.asList("kty", "n", "e")); + this.n = n; + this.e = e; + this.d = d; + this.p = p; + this.q = q; + this.dp = dp; + this.dq = dq; + this.di = di; + this.qi = qi; + + boolean hasPublicKeyParts = !this.n.isEmpty() && this.n.length() == this.e.length(); + boolean hasX509CertChain = this.getX5c().length() > 0; + + if (this.getKey() == null && (hasPublicKeyParts || hasX509CertChain)) { + this.deserialize(); + } else if (this.getKey() != null && !(this.n != null && this.e != null)) { + this.split(); + } + } + + public RSAKey(String use) { + this("RSA", "", use, "", "", "", "", null, "", "", "", "", "", "", "", "", "", null); + } + + /** + * Based on a text-based representation of an RSA key, this method + instantiates a cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey or + RSAPublicKey instance + * @throws DeserializationNotPossible + */ + public void deserialize() throws DeserializationNotPossible { + //first look for the public parts of a RSA key + if (this.n != null && this.e != null) { + Object item = null; + //loop over all the parameters that define a RSA key + for (String param : longs) { + try { + item = this.getClass().getField(param).get(this); + if (item == null || (item instanceof Number)) { + continue; + } else { + item = deserialize(item); + } + } catch (Exception e1) { + logger.error("Field " + param + " doesn't exist"); + } finally { + try { + this.getClass().getField(param).set(param, item); + } catch (Exception e1) { + logger.error("Field " + param + " doesn't exist"); + } + } + } + + List list = Arrays.asList(this.n, this.e); + if (!Strings.isNullOrEmpty(this.d)) { + list.add(this.d); + } + if (!Strings.isNullOrEmpty(this.p)) { + list.add(this.p); + if (!Strings.isNullOrEmpty(this.q)) { + list.add(this.q); + } + this.key = RSA.construct(tuple(list)); //TODO + } else { + this.key = RSA.construct(list) //TODO + } + } else if (this.x5c != null) { + Base64.decode((int) this.x5c.getBytes()[0]); + + //verify the cert thumbprint + if (this.x5t != null) { + if (Base64.decode() !=) + + } + + this.key =; + this.split(); + //verify chain + if (this.x5c.length() > 1) { + + } + } else { + throw new DeserializationNotPossible(); + } + } + + /** + * Given a cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey or + RSAPublicKey instance, construct the JWK representation. + * @param isPrivate: Should I do the private part or not + * @return A JWK as a hashmap + * @throws SerializationNotPossible + */ + public Map serialize(boolean isPrivate) throws SerializationNotPossible { + if (this.key == null) { + throw new SerializationNotPossible(); + } + + Map args = common(); + + publicMembers.addAll(longs); + List publicLongs = new ArrayList<>(publicMembers); + for (String param : publicLongs) { + try { + Object item = this.getClass().getField(param).get(this); + if (item != null) { + args.put(param, longToBase64(item)); + } + } catch (Exception e1) { + logger.error("Field " + param + " doesn't exist"); + } + } + + if (isPrivate) { + for (String param : longs) { + if (!isPrivate && Arrays.asList("d", "p", "q", "dp", "dq", "di", + "qi").contains(param)) { + continue; + } + try { + Object item = this.getClass().getField(param).get(this); + if (item != null) { + args.put(param, longToBase64(item)); + } + } catch (Exception e1) { + logger.error("Field " + param + " doesn't exist"); + } + + } + } + + return args; + } + + private void split() { + this.n = this.key.n; + this.e = this.key.e; + + this.d = this.key.d; + Object item = null; + for (String param : Arrays.asList("p", "q")) { + try { + item = this.getClass().getField(param).get(this); + } catch (Exception e1) { + logger.error("Field " + param + " doesn't exist"); + } finally { + if (item != null) { + //set attribute (which is in the form of a string) to a value + } + } + } + } + + /** + * Load a RSA key. Try to serialize the key before binding it to this + instance. + * @param key: An RSA key instance + * @return RSAKey instance + */ + public RSAKey loadKey(RSAKey key) { + this.key = key; + this.split(); + return key; + } + + /** + * Make sure there is a key instance present that can be used for + encrypting/signing. + * @return + */ + public Key encryptionKey() { + if (this.key == null) { + deserialize(); + } + + return this.key; + } + + private String longToBase64(Object item) { + } + + @Override + public Map serialize() { + return serialize(false); + } +} diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java b/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java new file mode 100644 index 0000000..5b1f263 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java @@ -0,0 +1,89 @@ +package com.auth0.jwt.oicmsg; + +import com.auth0.jwt.exceptions.oicmsg_exceptions.JWKException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * JSON Web key representation of a Symmetric key. + According to RFC 7517 a JWK representation of a symmetric key can look like + this:: + { + "kty":"oct", + "alg":"A128KW", + "k":"GawgguFyGrWKav7AX4VKUg" + } + */ +public class SYMKey extends Key { + + final private static Logger logger = LoggerFactory.getLogger(SYMKey.class); + protected static Set members = new HashSet<>(Arrays.asList("kty", "alg", "use", "kid", "k")); + public static Set publicMembers = new HashSet<>(Arrays.asList("kty", "alg", "use", "kid", "k")); + protected static Set required = new HashSet<>(Arrays.asList("k", "kty")); + private String k; + private static Map alg2Keylen = new HashMap() {{ + put("A128KW", 16); + put("A192KW", 24); + put("A256KW", 32); + put("HS256", 32); + put("HS384", 48); + put("HS512", 64); + }}; + + public SYMKey(String kty, String alg, String use, String kid, Key key, String x5c, + String x5t, String x5u, String k, Map args) { + super(kty, alg, use, kid, x5c, x5t, x5u, key, args); + this.k = k; + + if (this.key == null) { + this.key = b64d(this.k.getBytes()); + } + } + + public void deserialize() { + this.key = b64d(this.k.getBytes()); + } + + public Map serialize(boolean isPrivate) { + Map args = common(); + String k = Utils.urlSafeEncode(this.k); + args.put("k", k); + return args; + } + + /** + * Return an encryption key as per + http://openid.net/specs/openid-connect-core-1_0.html#Encryption + + * @param alg + * @return + * @throws JWKException + */ + public String encryptionKey(String alg) throws JWKException { + if (this.key == null) { + deserialize(); + } + + int size = alg2Keylen.get(alg); + + String encryptedKey; + if (size <= 32) { + encryptedKey = sha256_digest(this.key).substring(0, size); + } else if (size <= 48) { + encryptedKey = sha384_digest(this.key).substring(0, size); + } else if (size <= 64) { + encryptedKey = sha512_digest(this.key).substring(0, size); + } else { + throw new JWKException("No support for symmetric keys > 512 bits"); + } + + logger.debug(String.format("Symmetric encryption key: %s", as_unicode(b64e(encryptedKey))); + + return encryptedKey; + } +} diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/Utils.java b/lib/src/main/java/com/auth0/jwt/oicmsg/Utils.java new file mode 100644 index 0000000..aa1e92f --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/Utils.java @@ -0,0 +1,38 @@ +package com.auth0.jwt.oicmsg; + +import org.apache.commons.codec.binary.Base64; + +public class Utils { + + public static String urlSafeEncode(String value) { + value = Base64.encodeBase64URLSafeString(value.getBytes()); + StringBuilder sb = new StringBuilder(value); + for (int i = sb.length() - 1; + i >= 0; + i--) { + if (sb.charAt(i) == '=') { + sb.deleteCharAt(i); + } else { + break; + } + } + + return sb.toString(); + } + + public static byte[] urlSafeDecode(String value) { + byte[] stringToBytes = Base64.decodeBase64(value.getBytes()); + StringBuilder sb = new StringBuilder(new String(stringToBytes)); + for (int i = sb.length() - 1; + i >= 0; + i--) { + if (sb.charAt(i) == '=') { + sb.deleteCharAt(i); + } else { + break; + } + } + + return String.valueOf(sb).getBytes(); + } +} 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..5387d46 100644 --- a/lib/src/main/java/com/auth0/jwt/verification/VerificationAndAssertion.java +++ b/lib/src/main/java/com/auth0/jwt/verification/VerificationAndAssertion.java @@ -23,11 +23,10 @@ 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.interfaces.Claim; import com.auth0.jwt.interfaces.Clock; import com.auth0.jwt.interfaces.DecodedJWT; - +import com.auth0.jwt.interfaces.constants.PublicClaims; import java.util.Arrays; import java.util.Date; import java.util.List; diff --git a/lib/src/test/java/com/auth0/jwt/ClockImplTest.java b/lib/src/test/java/com/auth0/jwt/ClockImplTest.java index 6fdb01b..19c610f 100644 --- a/lib/src/test/java/com/auth0/jwt/ClockImplTest.java +++ b/lib/src/test/java/com/auth0/jwt/ClockImplTest.java @@ -19,19 +19,18 @@ 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 { @Test - public void shouldGetToday() throws Exception{ + public void shouldGetToday() throws Exception { Clock clock = new ClockImpl(); Date clockToday = clock.getToday(); assertThat(clockToday, is(notNullValue())); diff --git a/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java b/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java index 64120dd..cc93bb8 100644 --- a/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java +++ b/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java @@ -19,9 +19,21 @@ 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.interfaces.constants.Constants; 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 +41,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 { @@ -98,7 +102,7 @@ public DecodedJWT call() throws Exception { @Test public void shouldPassHMAC256Verification() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); String token = "eyJhbGciOiJIUzI1NiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.mZ0m_N1J4PgeqWmi903JuUoDRZDBPB7HwkS4nVyWH1M"; @@ -108,7 +112,7 @@ public void shouldPassHMAC256Verification() throws Exception { @Test public void shouldPassHMAC384Verification() throws Exception { String token = "eyJhbGciOiJIUzM4NCIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.uztpK_wUMYJhrRv8SV-1LU4aPnwl-EM1q-wJnqgyb5DHoDteP6lN_gE1xnZJH5vw"; - Algorithm algorithm = Algorithm.HMAC384("secret"); + Algorithm algorithm = Algorithm.HMAC384(Constants.SECRET); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); concurrentVerify(jwt, token); @@ -117,7 +121,7 @@ public void shouldPassHMAC384Verification() throws Exception { @Test public void shouldPassHMAC512Verification() throws Exception { String token = "eyJhbGciOiJIUzUxMiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.VUo2Z9SWDV-XcOc_Hr6Lff3vl7L9e5Vb8ThXpmGDFjHxe3Dr1ZBmUChYF-xVA7cAdX1P_D4ZCUcsv3IefpVaJw"; - Algorithm algorithm = Algorithm.HMAC512("secret"); + Algorithm algorithm = Algorithm.HMAC512(Constants.SECRET); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); concurrentVerify(jwt, token); diff --git a/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java b/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java index 8ff3844..0511c70 100644 --- a/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java +++ b/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java @@ -19,27 +19,32 @@ package com.auth0.jwt; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; +import com.auth0.jwt.interfaces.constants.Constants; import com.auth0.jwt.jwts.JWT; +import java.nio.charset.StandardCharsets; +import java.util.Date; +import java.util.Map; import org.apache.commons.codec.binary.Base64; import org.hamcrest.collection.IsCollectionWithSize; import org.hamcrest.core.IsCollectionContaining; import org.junit.Assert; -import static org.junit.Assert.assertTrue; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.nio.charset.StandardCharsets; -import java.util.Date; -import java.util.Map; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; - public class JWTDecoderTest { @Rule @@ -48,7 +53,7 @@ public class JWTDecoderTest { @Test public void getSubject() throws Exception { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).withNonStandardClaim("admin", true).withNonStandardClaim("name", "John Doe").build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).withNonStandardClaim("admin", true).withNonStandardClaim("name", "John Doe").build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT.getSubject(), is(notNullValue())); assertTrue(decodedJWT.getSubject().contains("1234567890")); @@ -59,7 +64,7 @@ public void getSubject() throws Exception { public void shouldThrowIfLessThan3Parts() throws Exception { exception.expect(JWTDecodeException.class); exception.expectMessage("The token was expected to have 3 parts, but got 2."); - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).withNonStandardClaim("admin", true).withNonStandardClaim("name", "John Doe").build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).withNonStandardClaim("admin", true).withNonStandardClaim("name", "John Doe").build(); DecodedJWT decodedJWT = jwt.decode("two.parts"); } @@ -67,7 +72,7 @@ public void shouldThrowIfLessThan3Parts() throws Exception { public void shouldThrowIfMoreThan3Parts() throws Exception { exception.expect(JWTDecodeException.class); exception.expectMessage("The token was expected to have 3 parts, but got 4."); - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).withNonStandardClaim("admin", true).withNonStandardClaim("name", "John Doe").build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).withNonStandardClaim("admin", true).withNonStandardClaim("name", "John Doe").build(); DecodedJWT decodedJWT = jwt.decode("this.has.four.parts"); } @@ -94,7 +99,7 @@ public void shouldThrowIfHeaderHasInvalidJSONFormat() throws Exception { @Test public void shouldGetStringToken() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.e30.XmNK3GpH3Ys_7wsYBfq4C3M6goz71I7dTgUkuIa5lyQ"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertThat(decodedJWT.getToken(), is(notNullValue())); @@ -104,7 +109,7 @@ public void shouldGetStringToken() throws Exception { @Test public void shouldGetHeader() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.e30.XmNK3GpH3Ys_7wsYBfq4C3M6goz71I7dTgUkuIa5lyQ"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertThat(decodedJWT.getHeader(), is("eyJhbGciOiJIUzI1NiJ9")); @@ -113,7 +118,7 @@ public void shouldGetHeader() throws Exception { @Test public void shouldGetPayload() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.e30.XmNK3GpH3Ys_7wsYBfq4C3M6goz71I7dTgUkuIa5lyQ"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertThat(decodedJWT.getPayload(), is("e30")); @@ -122,7 +127,7 @@ public void shouldGetPayload() throws Exception { @Test public void shouldGetSignature() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.e30.XmNK3GpH3Ys_7wsYBfq4C3M6goz71I7dTgUkuIa5lyQ"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertThat(decodedJWT.getSignature(), is("XmNK3GpH3Ys_7wsYBfq4C3M6goz71I7dTgUkuIa5lyQ")); @@ -133,7 +138,7 @@ public void shouldGetSignature() throws Exception { @Test public void shouldGetIssuer() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJKb2huIERvZSJ9.SgXosfRR_IwCgHq5lF3tlM-JHtpucWCRSaVuoHTbWbQ"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertTrue(decodedJWT.getIssuer().contains("John Doe")); @@ -142,7 +147,7 @@ public void shouldGetIssuer() throws Exception { @Test public void shouldGetSubject() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJUb2szbnMifQ.RudAxkslimoOY3BLl2Ghny3BrUKu9I1ZrXzCZGDJtNs"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertTrue(decodedJWT.getSubject().contains("Tok3ns")); @@ -151,7 +156,7 @@ public void shouldGetSubject() throws Exception { @Test public void shouldGetArrayAudience() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOlsiSG9wZSIsIlRyYXZpcyIsIlNvbG9tb24iXX0.Tm4W8WnfPjlmHSmKFakdij0on2rWPETpoM7Sh0u6-S4"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertThat(decodedJWT.getAudience(), is(IsCollectionWithSize.hasSize(3))); @@ -161,7 +166,7 @@ public void shouldGetArrayAudience() throws Exception { @Test public void shouldGetStringAudience() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJKYWNrIFJleWVzIn0.a4I9BBhPt1OB1GW67g2P1bEHgi6zgOjGUL4LvhE9Dgc"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertThat(decodedJWT.getAudience(), is(IsCollectionWithSize.hasSize(1))); @@ -171,7 +176,7 @@ public void shouldGetStringAudience() throws Exception { @Test public void shouldGetExpirationTime() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NzY3MjcwODZ9.L9dcPHEDQew2u9MkDCORFkfDGcSOsgoPqNY-LUMLEHg"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).acceptExpiresAt(1476727086).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).acceptExpiresAt(1476727086).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertThat(decodedJWT.getExpiresAt(), is(instanceOf(Date.class))); @@ -184,7 +189,7 @@ public void shouldGetExpirationTime() throws Exception { @Test public void shouldGetNotBefore() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYmYiOjE0NzY3MjcwODZ9.tkpD3iCPQPVqjnjpDVp2bJMBAgpVCG9ZjlBuMitass0"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).acceptNotBefore(1476727086).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).acceptNotBefore(1476727086).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertThat(decodedJWT.getNotBefore(), is(instanceOf(Date.class))); @@ -197,7 +202,7 @@ public void shouldGetNotBefore() throws Exception { @Test public void shouldGetIssuedAt() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE0NzY3MjcwODZ9.KPjGoW665E8V5_27Jugab8qSTxLk2cgquhPCBfAP0_w"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).acceptIssuedAt(1476727086).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).acceptIssuedAt(1476727086).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertThat(decodedJWT.getIssuedAt(), is(instanceOf(Date.class))); @@ -210,7 +215,7 @@ public void shouldGetIssuedAt() throws Exception { @Test public void shouldGetId() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMjM0NTY3ODkwIn0.m3zgEfVUFOd-CvL3xG5BuOWLzb0zMQZCqiVNQQOPOvA"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertThat(decodedJWT.getId(), is("1234567890")); @@ -219,7 +224,7 @@ public void shouldGetId() throws Exception { @Test public void shouldGetContentType() throws Exception { String token = "eyJhbGciOiJIUzI1NiIsImN0eSI6ImF3ZXNvbWUifQ.e30.AIm-pJDOaAyct9qKMlN-lQieqNDqc3d4erqUZc5SHAs"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertThat(decodedJWT.getContentType(), is("awesome")); @@ -228,7 +233,7 @@ public void shouldGetContentType() throws Exception { @Test public void shouldGetType() throws Exception { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.e30.WdFmrzx8b9v_a-r6EHC2PTAaWywgm_8LiP8RBRhYwkI"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertThat(decodedJWT.getType(), is("JWS")); @@ -237,7 +242,7 @@ public void shouldGetType() throws Exception { @Test public void shouldGetAlgorithm() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.e30.XmNK3GpH3Ys_7wsYBfq4C3M6goz71I7dTgUkuIa5lyQ"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertThat(decodedJWT.getAlgorithm(), is("HS256")); @@ -249,7 +254,7 @@ public void shouldGetAlgorithm() throws Exception { @Test public void shouldGetValidClaim() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.eyJvYmplY3QiOnsibmFtZSI6ImpvaG4ifX0.lrU1gZlOdlmTTeZwq0VI-pZx2iV46UWYd5-lCjy6-c4"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertThat(decodedJWT.getClaim("object"), is(notNullValue())); @@ -260,7 +265,7 @@ public void shouldGetValidClaim() throws Exception { @Test public void shouldNotGetNullClaimIfClaimIsEmptyObject() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.eyJvYmplY3QiOnt9fQ.d3nUeeL_69QsrHL0ZWij612LHEQxD8EZg1rNoY3a4aI"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); assertThat(decodedJWT.getClaim("object"), is(notNullValue())); @@ -270,7 +275,7 @@ public void shouldNotGetNullClaimIfClaimIsEmptyObject() throws Exception { @Test public void shouldGetCustomClaimOfTypeInteger() throws Exception { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoxMjN9.XZAudnA7h3_Al5kJydzLjw6RzZC3Q6OvnLEYlhNW7HA"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); Assert.assertThat(decodedJWT, is(notNullValue())); Assert.assertThat(decodedJWT.getClaim("name").asInt(), is(123)); @@ -279,7 +284,7 @@ public void shouldGetCustomClaimOfTypeInteger() throws Exception { @Test public void shouldGetCustomClaimOfTypeDouble() throws Exception { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoyMy40NX0.7pyX2OmEGaU9q15T8bGFqRm-d3RVTYnqmZNZtxMKSlA"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); Assert.assertThat(decodedJWT, is(notNullValue())); Assert.assertThat(decodedJWT.getClaim("name").asDouble(), is(23.45)); @@ -288,7 +293,7 @@ public void shouldGetCustomClaimOfTypeDouble() throws Exception { @Test public void shouldGetCustomClaimOfTypeBoolean() throws Exception { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjp0cnVlfQ.FwQ8VfsZNRqBa9PXMinSIQplfLU4-rkCLfIlTLg_MV0"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); Assert.assertThat(decodedJWT, is(notNullValue())); Assert.assertThat(decodedJWT.getClaim("name").asBoolean(), is(true)); @@ -297,7 +302,7 @@ public void shouldGetCustomClaimOfTypeBoolean() throws Exception { @Test public void shouldGetCustomClaimOfTypeDate() throws Exception { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoxNDc4ODkxNTIxfQ.mhioumeok8fghQEhTKF3QtQAksSvZ_9wIhJmgZLhJ6c"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); Date date = new Date(1478891521000L); Assert.assertThat(decodedJWT, is(notNullValue())); @@ -307,7 +312,7 @@ public void shouldGetCustomClaimOfTypeDate() throws Exception { @Test public void shouldGetCustomArrayClaimOfTypeString() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjpbInRleHQiLCIxMjMiLCJ0cnVlIl19.lxM8EcmK1uSZRAPd0HUhXGZJdauRmZmLjoeqz4J9yAA"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); Assert.assertThat(decodedJWT, is(notNullValue())); Assert.assertThat(decodedJWT.getClaim("name").asArray(String.class), arrayContaining("text", "123", "true")); @@ -316,7 +321,7 @@ public void shouldGetCustomArrayClaimOfTypeString() throws Exception { @Test public void shouldGetCustomArrayClaimOfTypeInteger() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjpbMSwyLDNdfQ.UEuMKRQYrzKAiPpPLhIVawWkKWA1zj0_GderrWUIyFE"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); Assert.assertThat(decodedJWT, is(notNullValue())); Assert.assertThat(decodedJWT.getClaim("name").asArray(Integer.class), arrayContaining(1, 2, 3)); @@ -325,7 +330,7 @@ public void shouldGetCustomArrayClaimOfTypeInteger() throws Exception { @Test public void shouldGetCustomMapClaim() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjp7InN0cmluZyI6InZhbHVlIiwibnVtYmVyIjoxLCJib29sZWFuIjp0cnVlfX0.-8aIaXd2-rp1lLuDEQmCeisCBX9X_zbqdPn2llGxNoc"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); Assert.assertThat(decodedJWT, is(notNullValue())); Map map = decodedJWT.getClaim("name").asMap(); @@ -337,10 +342,10 @@ public void shouldGetCustomMapClaim() throws Exception { @Test public void shouldGetAvailableClaims() throws Exception { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOiIxMjM0NTY3ODkwIiwiaWF0IjoiMTIzNDU2Nzg5MCIsIm5iZiI6IjEyMzQ1Njc4OTAiLCJqdGkiOiJodHRwczovL2p3dC5pby8iLCJhdWQiOiJodHRwczovL2RvbWFpbi5hdXRoMC5jb20iLCJzdWIiOiJsb2dpbiIsImlzcyI6ImF1dGgwIiwiZXh0cmFDbGFpbSI6IkpvaG4gRG9lIn0.TX9Ct4feGp9YyeGK9Zl91tO0YBOrguJ4As9jeqgHdZQ"; - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(token); assertThat(decodedJWT, is(notNullValue())); - Map claims = decodedJWT.getClaims(); + Map claims = decodedJWT.getClaims(); assertThat(claims, is(notNullValue())); assertThat(claims, is(instanceOf(Map.class))); assertThat(claims.get("exp"), is(notNullValue())); @@ -355,10 +360,10 @@ public void shouldGetAvailableClaims() throws Exception { //Helper Methods - private DecodedJWT customJWT(String jsonHeader, String jsonPayload, String signature) throws Exception{ + private DecodedJWT customJWT(String jsonHeader, String jsonPayload, String signature) throws Exception { String header = Base64.encodeBase64URLSafeString(jsonHeader.getBytes(StandardCharsets.UTF_8)); String body = Base64.encodeBase64URLSafeString(jsonPayload.getBytes(StandardCharsets.UTF_8)); - JWT jwt = JWT.require(Algorithm.HMAC256("secret")).build(); + JWT jwt = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build(); DecodedJWT decodedJWT = jwt.decode(String.format("%s.%s.%s", header, body, signature)); return decodedJWT; } diff --git a/lib/src/test/java/com/auth0/jwt/JWTTest.java b/lib/src/test/java/com/auth0/jwt/JWTTest.java index b368d43..238e1de 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 @@ -70,7 +56,7 @@ public void testCreateVerifierForScoped() { public void testCreateVerifierForImplicit() { thrown.expect(UnsupportedOperationException.class); thrown.expectMessage("you shouldn't be calling this method"); - JWT.require(Algorithm.none()).createVerifierForImplicit(null, null, 5); + JWT.require(Algorithm.none()).createVerifierForImplicit(null, null, 5); } @Test diff --git a/lib/src/test/java/com/auth0/jwt/JsonMatcher.java b/lib/src/test/java/com/auth0/jwt/JsonMatcher.java index 8a79a23..f8e84ac 100644 --- a/lib/src/test/java/com/auth0/jwt/JsonMatcher.java +++ b/lib/src/test/java/com/auth0/jwt/JsonMatcher.java @@ -19,14 +19,13 @@ package com.auth0.jwt; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.TypeSafeDiagnosingMatcher; - import java.lang.reflect.Array; import java.util.Iterator; import java.util.List; import java.util.Map; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hamcrest.TypeSafeDiagnosingMatcher; public class JsonMatcher extends TypeSafeDiagnosingMatcher { @@ -112,7 +111,9 @@ private String objectToString(Object value) { private String arrayToString(Object[] array) { StringBuilder sb = new StringBuilder(); sb.append("["); - for (int i = 0; i < array.length; i++) { + for (int i = 0; + i < array.length; + i++) { Object o = array[i]; sb.append(objectToString(o)); if (i + 1 < array.length) { diff --git a/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java b/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java index bc298eb..f26196b 100644 --- a/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java +++ b/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java @@ -21,25 +21,25 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static java.util.Arrays.asList; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.creators.GoogleJwtCreator; -import com.auth0.jwt.creators.GoogleJwtCreatorTest; import com.auth0.jwt.exceptions.InvalidClaimException; -import com.auth0.jwt.impl.PublicClaims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.GoogleVerification; +import com.auth0.jwt.interfaces.constants.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; 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 { @@ -53,12 +53,12 @@ public void testComplainOnNone() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("The Algorithm cannot be null."); - String token = JWT.create().withIssuer("accounts.fake.com").withSubject("subject") - .withAudience("audience") + String token = JWT.create().withIssuer("accounts.fake.com").withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .sign(null); GoogleVerification verification = GoogleJWT.require(null); - JWT verifier = verification.createVerifierForGoogle(GoogleJwtCreatorTest.PICTURE, GoogleJwtCreatorTest.EMAIL, asList("accounts.fake.com"), asList("audience"), - GoogleJwtCreatorTest.NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList("accounts.fake.com"), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -68,53 +68,53 @@ public void testVerifyingWithEmptyKey() throws Exception { thrown.expectMessage("Empty key"); Algorithm algorithm = Algorithm.HMAC256(""); String token = GoogleJwtCreator.build() - .withPicture(GoogleJwtCreatorTest.PICTURE) - .withEmail(GoogleJwtCreatorTest.EMAIL) + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) .withIssuer("accounts.fake.com") - .withSubject("subject") - .withAudience("audience") + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(GoogleJwtCreatorTest.NAME) + .withName(Constants.NAME) .withNonStandardClaim("nonStandardClaim", "nonStandardClaimValue") .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(GoogleJwtCreatorTest.PICTURE, GoogleJwtCreatorTest.EMAIL,asList("accounts.fake.com"), asList("audience"), - GoogleJwtCreatorTest.NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList("accounts.fake.com"), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @Test public void testConfigurableToMultipleKeys() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() - .withPicture(GoogleJwtCreatorTest.PICTURE) - .withEmail(GoogleJwtCreatorTest.EMAIL) - .withSubject("subject", "subject2") - .withAudience("audience", "audience2") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withSubject(Constants.SUBJECT, "subject2") + .withAudience(Constants.AUDIENCE, "audience2") .withExp(exp) .withIat(iat) - .withName(GoogleJwtCreatorTest.NAME) - .withIssuer("issuer", "issuer2") + .withName(Constants.NAME) + .withIssuer(Constants.ISSUER, "issuer2") .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(GoogleJwtCreatorTest.PICTURE, GoogleJwtCreatorTest.EMAIL, asList("issuer", "issuer2"), asList("audience", "audience2"), - GoogleJwtCreatorTest.NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER, "issuer2"), asList(Constants.AUDIENCE, "audience2"), + Constants.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)); + Map claims = jwt.getClaims(); + assertTrue(claims.get(Constants.PICTURE).asString().equals(Constants.PICTURE)); + assertTrue(claims.get(Constants.EMAIL).asString().equals(Constants.EMAIL)); List issuers = claims.get(PublicClaims.ISSUER).asList(String.class); - assertTrue(issuers.get(0).equals("issuer")); + assertTrue(issuers.get(0).equals(Constants.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(0).equals(Constants.SUBJECT)); assertTrue(subjects.get(1).equals("subject2")); List audience = claims.get(PublicClaims.AUDIENCE).asList(String.class); - assertTrue(audience.get(0).equals("audience")); + assertTrue(audience.get(0).equals(Constants.AUDIENCE)); assertTrue(audience.get(1).equals("audience2")); assertTrue(claims.get(PublicClaims.EXPIRES_AT).asDate().toString().equals(exp.toString())); - assertTrue(claims.get(GoogleJwtCreatorTest.NAME).asString().equals(GoogleJwtCreatorTest.NAME)); + assertTrue(claims.get(Constants.NAME).asString().equals(Constants.NAME)); } @Test @@ -122,21 +122,21 @@ public void testConfigurableToIncorrectNumberMultipleKeysForAudience() throws Ex thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'aud' value doesn't contain the required audience."); - Algorithm algorithm = Algorithm.HMAC256("secret"); - String[] arr = {"accounts.fake.com", "subject"}; + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); + String[] arr = {"accounts.fake.com", Constants.SUBJECT}; String token = GoogleJwtCreator.build() - .withPicture(GoogleJwtCreatorTest.PICTURE) - .withEmail(GoogleJwtCreatorTest.EMAIL) - .withSubject("subject", "subject2") - .withAudience("audience", "audience2") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withSubject(Constants.SUBJECT, "subject2") + .withAudience(Constants.AUDIENCE, "audience2") .withExp(exp) .withIat(iat) - .withName(GoogleJwtCreatorTest.NAME) - .withIssuer("issuer", "issuer2") + .withName(Constants.NAME) + .withIssuer(Constants.ISSUER, "issuer2") .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(GoogleJwtCreatorTest.PICTURE, GoogleJwtCreatorTest.EMAIL, asList("issuer", "issuer2"), asList("audience"), - GoogleJwtCreatorTest.NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER, "issuer2"), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -145,21 +145,21 @@ public void testConfigurableToIncorrectValueMultipleKeysForAudience() throws Exc thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'aud' value doesn't contain the required audience."); - Algorithm algorithm = Algorithm.HMAC256("secret"); - String[] arr = {"accounts.fake.com", "subject"}; + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); + String[] arr = {"accounts.fake.com", Constants.SUBJECT}; String token = GoogleJwtCreator.build() - .withPicture(GoogleJwtCreatorTest.PICTURE) - .withEmail(GoogleJwtCreatorTest.EMAIL) - .withSubject("subject", "subject2") - .withAudience("audience", "audience2") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withSubject(Constants.SUBJECT, "subject2") + .withAudience(Constants.AUDIENCE, "audience2") .withExp(exp) .withIat(iat) - .withName(GoogleJwtCreatorTest.NAME) - .withIssuer("issuer", "issuer2") + .withName(Constants.NAME) + .withIssuer(Constants.ISSUER, "issuer2") .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(GoogleJwtCreatorTest.PICTURE, GoogleJwtCreatorTest.EMAIL, asList("issuer", "issuer2"), asList("audience", "audience3"), - GoogleJwtCreatorTest.NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER, "issuer2"), asList(Constants.AUDIENCE, "audience3"), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } } \ No newline at end of file diff --git a/lib/src/test/java/com/auth0/jwt/PemUtils.java b/lib/src/test/java/com/auth0/jwt/PemUtils.java index 7b23244..9a109a1 100644 --- a/lib/src/test/java/com/auth0/jwt/PemUtils.java +++ b/lib/src/test/java/com/auth0/jwt/PemUtils.java @@ -19,9 +19,6 @@ package com.auth0.jwt; -import org.bouncycastle.util.io.pem.PemObject; -import org.bouncycastle.util.io.pem.PemReader; - import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; @@ -34,6 +31,8 @@ import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; +import org.bouncycastle.util.io.pem.PemObject; +import org.bouncycastle.util.io.pem.PemReader; public class PemUtils { diff --git a/lib/src/test/java/com/auth0/jwt/TimeUtil.java b/lib/src/test/java/com/auth0/jwt/TimeUtil.java index db50e89..f3dba93 100644 --- a/lib/src/test/java/com/auth0/jwt/TimeUtil.java +++ b/lib/src/test/java/com/auth0/jwt/TimeUtil.java @@ -41,7 +41,7 @@ public static Date generateRandomIatDateInPast() { } public static int randBetween(int start, int end) { - return start + (int)Math.round(Math.random() * (end - start)); + return start + (int) Math.round(Math.random() * (end - start)); } } diff --git a/lib/src/test/java/com/auth0/jwt/TokenUtilsTest.java b/lib/src/test/java/com/auth0/jwt/TokenUtilsTest.java index c0f375e..8782e1a 100644 --- a/lib/src/test/java/com/auth0/jwt/TokenUtilsTest.java +++ b/lib/src/test/java/com/auth0/jwt/TokenUtilsTest.java @@ -19,14 +19,17 @@ 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 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/UserPojo.java b/lib/src/test/java/com/auth0/jwt/UserPojo.java index 99e8a0f..1cc1360 100644 --- a/lib/src/test/java/com/auth0/jwt/UserPojo.java +++ b/lib/src/test/java/com/auth0/jwt/UserPojo.java @@ -35,8 +35,12 @@ public UserPojo(String name, int id) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } UserPojo userPojo = (UserPojo) o; 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..aaa2e67 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,27 @@ 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 com.auth0.jwt.interfaces.constants.Constants; +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 @@ -227,7 +234,7 @@ public void shouldThrowECDSA512InstanceWithNullKeyProvider() throws Exception { @Test public void shouldCreateHMAC256AlgorithmWithBytes() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret".getBytes(StandardCharsets.UTF_8)); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET.getBytes(StandardCharsets.UTF_8)); assertThat(algorithm, is(notNullValue())); assertThat(algorithm, is(instanceOf(HMACAlgorithm.class))); @@ -237,7 +244,7 @@ public void shouldCreateHMAC256AlgorithmWithBytes() throws Exception { @Test public void shouldCreateHMAC384AlgorithmWithBytes() throws Exception { - Algorithm algorithm = Algorithm.HMAC384("secret".getBytes(StandardCharsets.UTF_8)); + Algorithm algorithm = Algorithm.HMAC384(Constants.SECRET.getBytes(StandardCharsets.UTF_8)); assertThat(algorithm, is(notNullValue())); assertThat(algorithm, is(instanceOf(HMACAlgorithm.class))); @@ -247,7 +254,7 @@ public void shouldCreateHMAC384AlgorithmWithBytes() throws Exception { @Test public void shouldCreateHMAC512AlgorithmWithBytes() throws Exception { - Algorithm algorithm = Algorithm.HMAC512("secret".getBytes(StandardCharsets.UTF_8)); + Algorithm algorithm = Algorithm.HMAC512(Constants.SECRET.getBytes(StandardCharsets.UTF_8)); assertThat(algorithm, is(notNullValue())); assertThat(algorithm, is(instanceOf(HMACAlgorithm.class))); @@ -257,7 +264,7 @@ public void shouldCreateHMAC512AlgorithmWithBytes() throws Exception { @Test public void shouldCreateHMAC256AlgorithmWithString() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); assertThat(algorithm, is(notNullValue())); assertThat(algorithm, is(instanceOf(HMACAlgorithm.class))); @@ -267,7 +274,7 @@ public void shouldCreateHMAC256AlgorithmWithString() throws Exception { @Test public void shouldCreateHMAC384AlgorithmWithString() throws Exception { - Algorithm algorithm = Algorithm.HMAC384("secret"); + Algorithm algorithm = Algorithm.HMAC384(Constants.SECRET); assertThat(algorithm, is(notNullValue())); assertThat(algorithm, is(instanceOf(HMACAlgorithm.class))); @@ -277,7 +284,7 @@ public void shouldCreateHMAC384AlgorithmWithString() throws Exception { @Test public void shouldCreateHMAC512AlgorithmWithString() throws Exception { - Algorithm algorithm = Algorithm.HMAC512("secret"); + Algorithm algorithm = Algorithm.HMAC512(Constants.SECRET); assertThat(algorithm, is(notNullValue())); assertThat(algorithm, is(instanceOf(HMACAlgorithm.class))); 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..fa4b0af 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/ECDSAAlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/ECDSAAlgorithmTest.java @@ -19,6 +19,19 @@ package com.auth0.jwt.algorithms; +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.creators.EncodeType; import com.auth0.jwt.exceptions.AlgorithmMismatchException; import com.auth0.jwt.exceptions.SignatureGenerationException; @@ -26,6 +39,17 @@ 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 +58,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 { @@ -105,7 +111,7 @@ public void shouldThrowOnECDSA256VerificationWithDERSignature() throws Exception @Test public void shouldPassECDSA256VerificationWithJOSESignatureWithBothKeys() throws Exception { - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g"; + String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g"; 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); @@ -119,7 +125,7 @@ public void shouldThrowOnECDSA256VerificationWithDERSignatureWithBothKeys() thro exception.expectCause(isA(SignatureException.class)); exception.expectCause(hasMessage(is("Invalid JOSE signature format."))); - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.MEYCIQDiJWTf5jS/hFPj/0hpCWn7x1n/h+xPMjKWCs9MMusS9AIhAMcFPJVLe2A9uvb8hl8sRO2IpGoKDRpDmyH14ixNPAHW"; + String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.MEYCIQDiJWTf5jS/hFPj/0hpCWn7x1n/h+xPMjKWCs9MMusS9AIhAMcFPJVLe2A9uvb8hl8sRO2IpGoKDRpDmyH14ixNPAHW"; 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); @@ -131,7 +137,7 @@ public void shouldPassECDSA256VerificationWithProvidedPublicKey() throws Excepti ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class); PublicKey publicKey = readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"); when(provider.getPublicKeyById("my-key-id")).thenReturn((ECPublicKey) publicKey); - String token = "eyJhbGciOiJFUzI1NiIsImtpZCI6Im15LWtleS1pZCJ9.eyJpc3MiOiJhdXRoMCJ9.D_oU4CB0ZEsxHOjcWnmS3ZJvlTzm6WcGFx-HASxnvcB2Xu2WjI-axqXH9xKq45aPBDs330JpRhJmqBSc2K8MXQ"; + String token = "eyJhbGciOiJFUzI1NiIsImtpZCI6Im15LWtleS1pZCJ9.eyJpc3MiOiJhdXRoMCJ9.D_oU4CB0ZEsxHOjcWnmS3ZJvlTzm6WcGFx-HASxnvcB2Xu2WjI-axqXH9xKq45aPBDs330JpRhJmqBSc2K8MXQ"; Algorithm algorithm = Algorithm.ECDSA256(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); @@ -146,7 +152,7 @@ public void shouldFailECDSA256VerificationWhenProvidedPublicKeyIsNull() throws E exception.expectCause(hasMessage(is("The given Public Key is null."))); ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class); when(provider.getPublicKeyById("my-key-id")).thenReturn(null); - String token = "eyJhbGciOiJFUzI1NiIsImtpZCI6Im15LWtleS1pZCJ9.eyJpc3MiOiJhdXRoMCJ9.D_oU4CB0ZEsxHOjcWnmS3ZJvlTzm6WcGFx-HASxnvcB2Xu2WjI-axqXH9xKq45aPBDs330JpRhJmqBSc2K8MXQ"; + String token = "eyJhbGciOiJFUzI1NiIsImtpZCI6Im15LWtleS1pZCJ9.eyJpc3MiOiJhdXRoMCJ9.D_oU4CB0ZEsxHOjcWnmS3ZJvlTzm6WcGFx-HASxnvcB2Xu2WjI-axqXH9xKq45aPBDs330JpRhJmqBSc2K8MXQ"; Algorithm algorithm = Algorithm.ECDSA256(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); @@ -157,7 +163,7 @@ public void shouldFailECDSA256VerificationWhenProvidedPublicKeyIsNull() throws E public void shouldFailECDSA256VerificationWithInvalidPublicKey() throws Exception { exception.expect(SignatureVerificationException.class); exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA256withECDSA"); - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.W9qfN1b80B9hnMo49WL8THrOsf1vEjOhapeFemPMGySzxTcgfyudS5esgeBTO908X5SLdAr5jMwPUPBs9b6nNg"; + String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.W9qfN1b80B9hnMo49WL8THrOsf1vEjOhapeFemPMGySzxTcgfyudS5esgeBTO908X5SLdAr5jMwPUPBs9b6nNg"; 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); @@ -170,7 +176,7 @@ public void shouldFailECDSA256VerificationWhenUsingPrivateKey() throws Exception exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA256withECDSA"); exception.expectCause(isA(IllegalStateException.class)); exception.expectCause(hasMessage(is("The given Public Key is null."))); - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.W9qfN1b80B9hnMo49WL8THrOsf1vEjOhapeFemPMGySzxTcgfyudS5esgeBTO908X5SLdAr5jMwPUPBs9b6nNg"; + String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.W9qfN1b80B9hnMo49WL8THrOsf1vEjOhapeFemPMGySzxTcgfyudS5esgeBTO908X5SLdAr5jMwPUPBs9b6nNg"; Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); @@ -187,7 +193,7 @@ public void shouldFailECDSA256VerificationOnInvalidJOSESignatureLength() throws byte[] bytes = new byte[63]; new SecureRandom().nextBytes(bytes); String signature = Base64.encodeBase64URLSafeString(bytes); - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; + String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; 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); @@ -202,7 +208,7 @@ public void shouldFailECDSA256VerificationOnInvalidJOSESignature() throws Except byte[] bytes = new byte[64]; new SecureRandom().nextBytes(bytes); String signature = Base64.encodeBase64URLSafeString(bytes); - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; + String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; 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); @@ -218,7 +224,7 @@ public void shouldFailECDSA256VerificationOnInvalidDERSignature() throws Excepti bytes[0] = 0x30; new SecureRandom().nextBytes(bytes); String signature = Base64.encodeBase64URLSafeString(bytes); - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; + String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; 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); @@ -227,7 +233,7 @@ public void shouldFailECDSA256VerificationOnInvalidDERSignature() throws Excepti @Test public void shouldPassECDSA384VerificationWithJOSESignature() throws Exception { - String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9.50UU5VKNdF1wfykY8jQBKpvuHZoe6IZBJm5NvoB8bR-hnRg6ti-CHbmvoRtlLfnHfwITa_8cJMy6TenMC2g63GQHytc8rYoXqbwtS4R0Ko_AXbLFUmfxnGnMC6v4MS_z"; + String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9.50UU5VKNdF1wfykY8jQBKpvuHZoe6IZBJm5NvoB8bR-hnRg6ti-CHbmvoRtlLfnHfwITa_8cJMy6TenMC2g63GQHytc8rYoXqbwtS4R0Ko_AXbLFUmfxnGnMC6v4MS_z"; ECKey key = (ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC"); Algorithm algorithm = Algorithm.ECDSA384(key); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); @@ -242,7 +248,7 @@ public void shouldThrowOnECDSA384VerificationWithDERSignature() throws Exception exception.expectCause(isA(SignatureException.class)); exception.expectCause(hasMessage(is("Invalid JOSE signature format."))); - String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9.MGUCMQDnRRTlUo10XXB/KRjyNAEqm+4dmh7ohkEmbk2+gHxtH6GdGDq2L4Idua+hG2Ut+ccCMH8CE2v/HCTMuk3pzAtoOtxkB8rXPK2KF6m8LUuEdCqPwF2yxVJn8ZxpzAur+DEv8w=="; + String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9.MGUCMQDnRRTlUo10XXB/KRjyNAEqm+4dmh7ohkEmbk2+gHxtH6GdGDq2L4Idua+hG2Ut+ccCMH8CE2v/HCTMuk3pzAtoOtxkB8rXPK2KF6m8LUuEdCqPwF2yxVJn8ZxpzAur+DEv8w=="; ECKey key = (ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC"); Algorithm algorithm = Algorithm.ECDSA384(key); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); @@ -252,7 +258,7 @@ public void shouldThrowOnECDSA384VerificationWithDERSignature() throws Exception @Test public void shouldPassECDSA384VerificationWithJOSESignatureWithBothKeys() throws Exception { - String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9.50UU5VKNdF1wfykY8jQBKpvuHZoe6IZBJm5NvoB8bR-hnRg6ti-CHbmvoRtlLfnHfwITa_8cJMy6TenMC2g63GQHytc8rYoXqbwtS4R0Ko_AXbLFUmfxnGnMC6v4MS_z"; + String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9.50UU5VKNdF1wfykY8jQBKpvuHZoe6IZBJm5NvoB8bR-hnRg6ti-CHbmvoRtlLfnHfwITa_8cJMy6TenMC2g63GQHytc8rYoXqbwtS4R0Ko_AXbLFUmfxnGnMC6v4MS_z"; 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); @@ -266,7 +272,7 @@ public void shouldThrowOnECDSA384VerificationWithDERSignatureWithBothKeys() thro exception.expectCause(isA(SignatureException.class)); exception.expectCause(hasMessage(is("Invalid JOSE signature format."))); - String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9.MGUCMQDnRRTlUo10XXB/KRjyNAEqm+4dmh7ohkEmbk2+gHxtH6GdGDq2L4Idua+hG2Ut+ccCMH8CE2v/HCTMuk3pzAtoOtxkB8rXPK2KF6m8LUuEdCqPwF2yxVJn8ZxpzAur+DEv8w=="; + String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9.MGUCMQDnRRTlUo10XXB/KRjyNAEqm+4dmh7ohkEmbk2+gHxtH6GdGDq2L4Idua+hG2Ut+ccCMH8CE2v/HCTMuk3pzAtoOtxkB8rXPK2KF6m8LUuEdCqPwF2yxVJn8ZxpzAur+DEv8w=="; 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); @@ -278,7 +284,7 @@ public void shouldPassECDSA384VerificationWithProvidedPublicKey() throws Excepti ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class); PublicKey publicKey = readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC"); when(provider.getPublicKeyById("my-key-id")).thenReturn((ECPublicKey) publicKey); - String token = "eyJhbGciOiJFUzM4NCIsImtpZCI6Im15LWtleS1pZCJ9.eyJpc3MiOiJhdXRoMCJ9.9kjGuFTPx3ylfpqL0eY9H7TGmPepjQOBKI8UPoEvby6N7dDLF5HxLohosNxxFymNT7LzpeSgOPAB0wJEwG2Nl2ukgdUOpZOf492wog_i5ZcZmAykd3g1QH7onrzd69GU"; + String token = "eyJhbGciOiJFUzM4NCIsImtpZCI6Im15LWtleS1pZCJ9.eyJpc3MiOiJhdXRoMCJ9.9kjGuFTPx3ylfpqL0eY9H7TGmPepjQOBKI8UPoEvby6N7dDLF5HxLohosNxxFymNT7LzpeSgOPAB0wJEwG2Nl2ukgdUOpZOf492wog_i5ZcZmAykd3g1QH7onrzd69GU"; Algorithm algorithm = Algorithm.ECDSA384(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); @@ -293,7 +299,7 @@ public void shouldFailECDSA384VerificationWhenProvidedPublicKeyIsNull() throws E exception.expectCause(hasMessage(is("The given Public Key is null."))); ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class); when(provider.getPublicKeyById("my-key-id")).thenReturn(null); - String token = "eyJhbGciOiJFUzM4NCIsImtpZCI6Im15LWtleS1pZCJ9.eyJpc3MiOiJhdXRoMCJ9.9kjGuFTPx3ylfpqL0eY9H7TGmPepjQOBKI8UPoEvby6N7dDLF5HxLohosNxxFymNT7LzpeSgOPAB0wJEwG2Nl2ukgdUOpZOf492wog_i5ZcZmAykd3g1QH7onrzd69GU"; + String token = "eyJhbGciOiJFUzM4NCIsImtpZCI6Im15LWtleS1pZCJ9.eyJpc3MiOiJhdXRoMCJ9.9kjGuFTPx3ylfpqL0eY9H7TGmPepjQOBKI8UPoEvby6N7dDLF5HxLohosNxxFymNT7LzpeSgOPAB0wJEwG2Nl2ukgdUOpZOf492wog_i5ZcZmAykd3g1QH7onrzd69GU"; Algorithm algorithm = Algorithm.ECDSA384(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); @@ -304,7 +310,7 @@ public void shouldFailECDSA384VerificationWhenProvidedPublicKeyIsNull() throws E public void shouldFailECDSA384VerificationWithInvalidPublicKey() throws Exception { exception.expect(SignatureVerificationException.class); exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA384withECDSA"); - String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9._k5h1KyO-NE0R2_HAw0-XEc0bGT5atv29SxHhOGC9JDqUHeUdptfCK_ljQ01nLVt2OQWT2SwGs-TuyHDFmhPmPGFZ9wboxvq_ieopmYqhQilNAu-WF-frioiRz9733fU"; + String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9._k5h1KyO-NE0R2_HAw0-XEc0bGT5atv29SxHhOGC9JDqUHeUdptfCK_ljQ01nLVt2OQWT2SwGs-TuyHDFmhPmPGFZ9wboxvq_ieopmYqhQilNAu-WF-frioiRz9733fU"; 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); @@ -317,7 +323,7 @@ public void shouldFailECDSA384VerificationWhenUsingPrivateKey() throws Exception exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA384withECDSA"); exception.expectCause(isA(IllegalStateException.class)); exception.expectCause(hasMessage(is("The given Public Key is null."))); - String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9._k5h1KyO-NE0R2_HAw0-XEc0bGT5atv29SxHhOGC9JDqUHeUdptfCK_ljQ01nLVt2OQWT2SwGs-TuyHDFmhPmPGFZ9wboxvq_ieopmYqhQilNAu-WF-frioiRz9733fU"; + String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9._k5h1KyO-NE0R2_HAw0-XEc0bGT5atv29SxHhOGC9JDqUHeUdptfCK_ljQ01nLVt2OQWT2SwGs-TuyHDFmhPmPGFZ9wboxvq_ieopmYqhQilNAu-WF-frioiRz9733fU"; Algorithm algorithm = Algorithm.ECDSA384((ECKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_384, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); @@ -332,7 +338,7 @@ public void shouldFailECDSA384VerificationOnInvalidJOSESignatureLength() throws byte[] bytes = new byte[95]; new SecureRandom().nextBytes(bytes); String signature = Base64.encodeBase64URLSafeString(bytes); - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; + String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; 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); @@ -347,7 +353,7 @@ public void shouldFailECDSA384VerificationOnInvalidJOSESignature() throws Except byte[] bytes = new byte[96]; new SecureRandom().nextBytes(bytes); String signature = Base64.encodeBase64URLSafeString(bytes); - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; + String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; 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); @@ -363,7 +369,7 @@ public void shouldFailECDSA384VerificationOnInvalidDERSignature() throws Excepti new SecureRandom().nextBytes(bytes); bytes[0] = 0x30; String signature = Base64.encodeBase64URLSafeString(bytes); - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; + String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; 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); @@ -372,7 +378,7 @@ public void shouldFailECDSA384VerificationOnInvalidDERSignature() throws Excepti @Test public void shouldPassECDSA512VerificationWithJOSESignature() throws Exception { - String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.AeCJPDIsSHhwRSGZCY6rspi8zekOw0K9qYMNridP1Fu9uhrA1QrG-EUxXlE06yvmh2R7Rz0aE7kxBwrnq8L8aOBCAYAsqhzPeUvyp8fXjjgs0Eto5I0mndE2QHlgcMSFASyjHbU8wD2Rq7ZNzGQ5b2MZfpv030WGUajT-aZYWFUJHVg2"; + String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.AeCJPDIsSHhwRSGZCY6rspi8zekOw0K9qYMNridP1Fu9uhrA1QrG-EUxXlE06yvmh2R7Rz0aE7kxBwrnq8L8aOBCAYAsqhzPeUvyp8fXjjgs0Eto5I0mndE2QHlgcMSFASyjHbU8wD2Rq7ZNzGQ5b2MZfpv030WGUajT-aZYWFUJHVg2"; ECKey key = (ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"); Algorithm algorithm = Algorithm.ECDSA512(key); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); @@ -387,7 +393,7 @@ public void shouldThrowOnECDSA512VerificationWithDERSignature() throws Exception exception.expectCause(isA(SignatureException.class)); exception.expectCause(hasMessage(is("Invalid JOSE signature format."))); - String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.MIGIAkIB4Ik8MixIeHBFIZkJjquymLzN6Q7DQr2pgw2uJ0/UW726GsDVCsb4RTFeUTTrK+aHZHtHPRoTuTEHCuerwvxo4EICQgGALKocz3lL8qfH1444LNBLaOSNJp3RNkB5YHDEhQEsox21PMA9kau2TcxkOW9jGX6b9N9FhlGo0/mmWFhVCR1YNg=="; + String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.MIGIAkIB4Ik8MixIeHBFIZkJjquymLzN6Q7DQr2pgw2uJ0/UW726GsDVCsb4RTFeUTTrK+aHZHtHPRoTuTEHCuerwvxo4EICQgGALKocz3lL8qfH1444LNBLaOSNJp3RNkB5YHDEhQEsox21PMA9kau2TcxkOW9jGX6b9N9FhlGo0/mmWFhVCR1YNg=="; ECKey key = (ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"); Algorithm algorithm = Algorithm.ECDSA512(key); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); @@ -397,7 +403,7 @@ public void shouldThrowOnECDSA512VerificationWithDERSignature() throws Exception @Test public void shouldPassECDSA512VerificationWithJOSESignatureWithBothKeys() throws Exception { - String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.AeCJPDIsSHhwRSGZCY6rspi8zekOw0K9qYMNridP1Fu9uhrA1QrG-EUxXlE06yvmh2R7Rz0aE7kxBwrnq8L8aOBCAYAsqhzPeUvyp8fXjjgs0Eto5I0mndE2QHlgcMSFASyjHbU8wD2Rq7ZNzGQ5b2MZfpv030WGUajT-aZYWFUJHVg2"; + String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.AeCJPDIsSHhwRSGZCY6rspi8zekOw0K9qYMNridP1Fu9uhrA1QrG-EUxXlE06yvmh2R7Rz0aE7kxBwrnq8L8aOBCAYAsqhzPeUvyp8fXjjgs0Eto5I0mndE2QHlgcMSFASyjHbU8wD2Rq7ZNzGQ5b2MZfpv030WGUajT-aZYWFUJHVg2"; 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); @@ -411,7 +417,7 @@ public void shouldThrowECDSA512VerificationWithDERSignatureWithBothKeys() throws exception.expectCause(isA(SignatureException.class)); exception.expectCause(hasMessage(is("Invalid JOSE signature format."))); - String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.MIGIAkIB4Ik8MixIeHBFIZkJjquymLzN6Q7DQr2pgw2uJ0/UW726GsDVCsb4RTFeUTTrK+aHZHtHPRoTuTEHCuerwvxo4EICQgGALKocz3lL8qfH1444LNBLaOSNJp3RNkB5YHDEhQEsox21PMA9kau2TcxkOW9jGX6b9N9FhlGo0/mmWFhVCR1YNg=="; + String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.MIGIAkIB4Ik8MixIeHBFIZkJjquymLzN6Q7DQr2pgw2uJ0/UW726GsDVCsb4RTFeUTTrK+aHZHtHPRoTuTEHCuerwvxo4EICQgGALKocz3lL8qfH1444LNBLaOSNJp3RNkB5YHDEhQEsox21PMA9kau2TcxkOW9jGX6b9N9FhlGo0/mmWFhVCR1YNg=="; 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); @@ -423,7 +429,7 @@ public void shouldPassECDSA512VerificationWithProvidedPublicKey() throws Excepti ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class); PublicKey publicKey = readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"); when(provider.getPublicKeyById("my-key-id")).thenReturn((ECPublicKey) publicKey); - String token = "eyJhbGciOiJFUzUxMiIsImtpZCI6Im15LWtleS1pZCJ9.eyJpc3MiOiJhdXRoMCJ9.AGxEwbsYa2bQ7Y7DAcTQnVD8PmLSlhJ20jg2OfdyPnqdXI8SgBaG6lGciq3_pofFhs1HEoFoJ33Jcluha24oMHIvAfwu8qbv_Wq3L2eI9Q0L0p6ul8Pd_BS8adRa2PgLc36xXGcRc7ID5YH-CYaQfsTp5YIaF0Po3h0QyCoQ6ZiYQkqm"; + String token = "eyJhbGciOiJFUzUxMiIsImtpZCI6Im15LWtleS1pZCJ9.eyJpc3MiOiJhdXRoMCJ9.AGxEwbsYa2bQ7Y7DAcTQnVD8PmLSlhJ20jg2OfdyPnqdXI8SgBaG6lGciq3_pofFhs1HEoFoJ33Jcluha24oMHIvAfwu8qbv_Wq3L2eI9Q0L0p6ul8Pd_BS8adRa2PgLc36xXGcRc7ID5YH-CYaQfsTp5YIaF0Po3h0QyCoQ6ZiYQkqm"; Algorithm algorithm = Algorithm.ECDSA512(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); @@ -438,7 +444,7 @@ public void shouldFailECDSA512VerificationWhenProvidedPublicKeyIsNull() throws E exception.expectCause(hasMessage(is("The given Public Key is null."))); ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class); when(provider.getPublicKeyById("my-key-id")).thenReturn(null); - String token = "eyJhbGciOiJFUzUxMiIsImtpZCI6Im15LWtleS1pZCJ9.eyJpc3MiOiJhdXRoMCJ9.AGxEwbsYa2bQ7Y7DAcTQnVD8PmLSlhJ20jg2OfdyPnqdXI8SgBaG6lGciq3_pofFhs1HEoFoJ33Jcluha24oMHIvAfwu8qbv_Wq3L2eI9Q0L0p6ul8Pd_BS8adRa2PgLc36xXGcRc7ID5YH-CYaQfsTp5YIaF0Po3h0QyCoQ6ZiYQkqm"; + String token = "eyJhbGciOiJFUzUxMiIsImtpZCI6Im15LWtleS1pZCJ9.eyJpc3MiOiJhdXRoMCJ9.AGxEwbsYa2bQ7Y7DAcTQnVD8PmLSlhJ20jg2OfdyPnqdXI8SgBaG6lGciq3_pofFhs1HEoFoJ33Jcluha24oMHIvAfwu8qbv_Wq3L2eI9Q0L0p6ul8Pd_BS8adRa2PgLc36xXGcRc7ID5YH-CYaQfsTp5YIaF0Po3h0QyCoQ6ZiYQkqm"; Algorithm algorithm = Algorithm.ECDSA512(provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); @@ -449,7 +455,7 @@ public void shouldFailECDSA512VerificationWhenProvidedPublicKeyIsNull() throws E public void shouldFailECDSA512VerificationWithInvalidPublicKey() throws Exception { exception.expect(SignatureVerificationException.class); exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA512withECDSA"); - String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.AZgdopFFsN0amCSs2kOucXdpylD31DEm5ChK1PG0_gq5Mf47MrvVph8zHSVuvcrXzcE1U3VxeCg89mYW1H33Y-8iAF0QFkdfTUQIWKNObH543WNMYYssv3OtOj0znPv8atDbaF8DMYAtcT1qdmaSJRhx-egRE9HGZkinPh9CfLLLt58X"; + String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.AZgdopFFsN0amCSs2kOucXdpylD31DEm5ChK1PG0_gq5Mf47MrvVph8zHSVuvcrXzcE1U3VxeCg89mYW1H33Y-8iAF0QFkdfTUQIWKNObH543WNMYYssv3OtOj0znPv8atDbaF8DMYAtcT1qdmaSJRhx-egRE9HGZkinPh9CfLLLt58X"; 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); @@ -462,7 +468,7 @@ public void shouldFailECDSA512VerificationWhenUsingPrivateKey() throws Exception exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA512withECDSA"); exception.expectCause(isA(IllegalStateException.class)); exception.expectCause(hasMessage(is("The given Public Key is null."))); - String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.AZgdopFFsN0amCSs2kOucXdpylD31DEm5ChK1PG0_gq5Mf47MrvVph8zHSVuvcrXzcE1U3VxeCg89mYW1H33Y-8iAF0QFkdfTUQIWKNObH543WNMYYssv3OtOj0znPv8atDbaF8DMYAtcT1qdmaSJRhx-egRE9HGZkinPh9CfLLLt58X"; + String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.AZgdopFFsN0amCSs2kOucXdpylD31DEm5ChK1PG0_gq5Mf47MrvVph8zHSVuvcrXzcE1U3VxeCg89mYW1H33Y-8iAF0QFkdfTUQIWKNObH543WNMYYssv3OtOj0znPv8atDbaF8DMYAtcT1qdmaSJRhx-egRE9HGZkinPh9CfLLLt58X"; Algorithm algorithm = Algorithm.ECDSA512((ECKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); @@ -477,7 +483,7 @@ public void shouldFailECDSA512VerificationOnInvalidJOSESignatureLength() throws byte[] bytes = new byte[131]; new SecureRandom().nextBytes(bytes); String signature = Base64.encodeBase64URLSafeString(bytes); - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; + String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; 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); @@ -492,7 +498,7 @@ public void shouldFailECDSA512VerificationOnInvalidJOSESignature() throws Except byte[] bytes = new byte[132]; new SecureRandom().nextBytes(bytes); String signature = Base64.encodeBase64URLSafeString(bytes); - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; + String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; 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); @@ -508,7 +514,7 @@ public void shouldFailECDSA512VerificationOnInvalidDERSignature() throws Excepti new SecureRandom().nextBytes(bytes); bytes[0] = 0x30; String signature = Base64.encodeBase64URLSafeString(bytes); - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; + String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; 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); @@ -525,7 +531,7 @@ public void shouldFailJOSEToDERConversionOnInvalidJOSESignatureLength() throws E byte[] bytes = new byte[256]; new SecureRandom().nextBytes(bytes); String signature = Base64.encodeBase64URLSafeString(bytes); - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; + String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; ECPublicKey publicKey = (ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"); ECPrivateKey privateKey = mock(ECPrivateKey.class); @@ -549,7 +555,7 @@ public void shouldThrowOnVerifyWhenSignatureAlgorithmDoesNotExists() throws Exce ECPrivateKey privateKey = mock(ECPrivateKey.class); ECDSAKeyProvider provider = ECDSAAlgorithm.providerForKeys(publicKey, privateKey); Algorithm algorithm = new ECDSAAlgorithm(crypto, "some-alg", "some-algorithm", 32, provider); - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g"; + 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); @@ -568,7 +574,7 @@ public void shouldThrowOnVerifyWhenThePublicKeyIsInvalid() throws Exception { ECPrivateKey privateKey = mock(ECPrivateKey.class); ECDSAKeyProvider provider = ECDSAAlgorithm.providerForKeys(publicKey, privateKey); Algorithm algorithm = new ECDSAAlgorithm(crypto, "some-alg", "some-algorithm", 32, provider); - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g"; + 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); @@ -587,7 +593,7 @@ public void shouldThrowOnVerifyWhenTheSignatureIsNotPrepared() throws Exception ECPrivateKey privateKey = mock(ECPrivateKey.class); ECDSAKeyProvider provider = ECDSAAlgorithm.providerForKeys(publicKey, privateKey); Algorithm algorithm = new ECDSAAlgorithm(crypto, "some-alg", "some-algorithm", 32, provider); - String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g"; + 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); @@ -607,7 +613,7 @@ public void shouldDoECDSA256Signing() throws Exception { byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = algorithmSign.sign(contentBytes); String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes); - String token = String.format("%s.%s", jwtContent, jwtSignature); + String token = String.format("%s.%s", jwtContent, jwtSignature); assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithmVerify).withIssuer("auth0").build(); @@ -622,7 +628,7 @@ public void shouldDoECDSA256SigningWithBothKeys() throws Exception { byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = algorithm.sign(contentBytes); String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes); - String token = String.format("%s.%s", jwtContent, jwtSignature); + String token = String.format("%s.%s", jwtContent, jwtSignature); assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); @@ -642,7 +648,7 @@ public void shouldDoECDSA256SigningWithProvidedPrivateKey() throws Exception { byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = algorithm.sign(contentBytes); String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes); - String token = String.format("%s.%s", jwtContent, jwtSignature); + String token = String.format("%s.%s", jwtContent, jwtSignature); assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); @@ -682,7 +688,7 @@ public void shouldDoECDSA384Signing() throws Exception { byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = algorithmSign.sign(contentBytes); String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes); - String token = String.format("%s.%s", jwtContent, jwtSignature); + String token = String.format("%s.%s", jwtContent, jwtSignature); assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithmVerify).withIssuer("auth0").build(); @@ -697,7 +703,7 @@ public void shouldDoECDSA384SigningWithBothKeys() throws Exception { byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = algorithm.sign(contentBytes); String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes); - String token = String.format("%s.%s", jwtContent, jwtSignature); + String token = String.format("%s.%s", jwtContent, jwtSignature); assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); @@ -717,7 +723,7 @@ public void shouldDoECDSA384SigningWithProvidedPrivateKey() throws Exception { byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = algorithm.sign(contentBytes); String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes); - String token = String.format("%s.%s", jwtContent, jwtSignature); + String token = String.format("%s.%s", jwtContent, jwtSignature); assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); @@ -757,7 +763,7 @@ public void shouldDoECDSA512Signing() throws Exception { byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = algorithmSign.sign(contentBytes); String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes); - String token = String.format("%s.%s", jwtContent, jwtSignature); + String token = String.format("%s.%s", jwtContent, jwtSignature); assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithmVerify).withIssuer("auth0").build(); @@ -772,7 +778,7 @@ public void shouldDoECDSA512SigningWithBothKeys() throws Exception { byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = algorithm.sign(contentBytes); String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes); - String token = String.format("%s.%s", jwtContent, jwtSignature); + String token = String.format("%s.%s", jwtContent, jwtSignature); assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); @@ -793,7 +799,7 @@ public void shouldDoECDSA512SigningWithProvidedPrivateKey() throws Exception { byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = algorithm.sign(contentBytes); String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes); - String token = String.format("%s.%s", jwtContent, jwtSignature); + String token = String.format("%s.%s", jwtContent, jwtSignature); assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); @@ -958,11 +964,13 @@ public void shouldSignAndVerifyWithECDSA256() throws Exception { ECDSAAlgorithm algorithm256 = (ECDSAAlgorithm) Algorithm.ECDSA256((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC")); String content256 = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9"; - for (int i = 0; i < 10; i++) { + for (int i = 0; + i < 10; + i++) { byte[] signature = algorithm256.sign(content256.getBytes()); String signature256 = Base64.encodeBase64URLSafeString((signature)); - String token = content256 + "." + signature256; + String token = content256 + "." + signature256; JWT jwt = JWT.require(algorithm256).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm256.verify(decoded, EncodeType.Base64); @@ -974,11 +982,13 @@ public void shouldSignAndVerifyWithECDSA384() throws Exception { ECDSAAlgorithm algorithm384 = (ECDSAAlgorithm) Algorithm.ECDSA384((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_384, "EC")); String content384 = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9"; - for (int i = 0; i < 10; i++) { + for (int i = 0; + i < 10; + i++) { byte[] signature = algorithm384.sign(content384.getBytes()); String signature384 = Base64.encodeBase64URLSafeString((signature)); - String token = content384 + "." + signature384; + String token = content384 + "." + signature384; JWT jwt = JWT.require(algorithm384).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm384.verify(decoded, EncodeType.Base64); @@ -990,11 +1000,13 @@ public void shouldSignAndVerifyWithECDSA512() throws Exception { ECDSAAlgorithm algorithm512 = (ECDSAAlgorithm) Algorithm.ECDSA512((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC")); String content512 = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9"; - for (int i = 0; i < 10; i++) { + for (int i = 0; + i < 10; + i++) { byte[] signature = algorithm512.sign(content512.getBytes()); String signature512 = Base64.encodeBase64URLSafeString((signature)); - String token = content512 + "." + signature512; + String token = content512 + "." + signature512; JWT jwt = JWT.require(algorithm512).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm512.verify(decoded, EncodeType.Base64); diff --git a/lib/src/test/java/com/auth0/jwt/algorithms/ECDSABouncyCastleProviderTests.java b/lib/src/test/java/com/auth0/jwt/algorithms/ECDSABouncyCastleProviderTests.java index d6a37c7..4e7348d 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 { @@ -975,7 +987,9 @@ public void shouldSignAndVerifyWithECDSA256() throws Exception { ECDSAAlgorithm algorithm256 = (ECDSAAlgorithm) Algorithm.ECDSA256((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC")); String content256 = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9"; - for (int i = 0; i < 10; i++) { + for (int i = 0; + i < 10; + i++) { byte[] signature = algorithm256.sign(content256.getBytes()); String signature256 = Base64.encodeBase64URLSafeString((signature)); @@ -991,7 +1005,9 @@ public void shouldSignAndVerifyWithECDSA384() throws Exception { ECDSAAlgorithm algorithm384 = (ECDSAAlgorithm) Algorithm.ECDSA384((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_384, "EC")); String content384 = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9"; - for (int i = 0; i < 10; i++) { + for (int i = 0; + i < 10; + i++) { byte[] signature = algorithm384.sign(content384.getBytes()); String signature384 = Base64.encodeBase64URLSafeString((signature)); @@ -1007,7 +1023,9 @@ public void shouldSignAndVerifyWithECDSA512() throws Exception { ECDSAAlgorithm algorithm512 = (ECDSAAlgorithm) Algorithm.ECDSA512((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC")); String content512 = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9"; - for (int i = 0; i < 10; i++) { + for (int i = 0; + i < 10; + i++) { byte[] signature = algorithm512.sign(content512.getBytes()); String signature512 = Base64.encodeBase64URLSafeString((signature)); 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..7346315 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,32 @@ package com.auth0.jwt.algorithms; +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.creators.EncodeType; 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.constants.Constants; 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 { @@ -60,8 +63,8 @@ public void shouldGetStringBytes() throws Exception { @Test 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)); + Algorithm algorithmString = Algorithm.HMAC256(Constants.SECRET); + Algorithm algorithmBytes = Algorithm.HMAC256(Constants.SECRET.getBytes(StandardCharsets.UTF_8)); JWT jwt = JWT.require(algorithmString).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithmString.verify(decoded, EncodeType.Base64); @@ -93,8 +96,8 @@ public void shouldFailHMAC256VerificationWithInvalidSecretBytes() throws Excepti @Test public void shouldPassHMAC384Verification() throws Exception { String token = "eyJhbGciOiJIUzM4NCIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.uztpK_wUMYJhrRv8SV-1LU4aPnwl-EM1q-wJnqgyb5DHoDteP6lN_gE1xnZJH5vw"; - Algorithm algorithmString = Algorithm.HMAC384("secret"); - Algorithm algorithmBytes = Algorithm.HMAC384("secret".getBytes(StandardCharsets.UTF_8)); + Algorithm algorithmString = Algorithm.HMAC384(Constants.SECRET); + Algorithm algorithmBytes = Algorithm.HMAC384(Constants.SECRET.getBytes(StandardCharsets.UTF_8)); JWT jwt = JWT.require(algorithmString).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithmString.verify(decoded, EncodeType.Base64); @@ -126,8 +129,8 @@ public void shouldFailHMAC384VerificationWithInvalidSecretBytes() throws Excepti @Test public void shouldPassHMAC512Verification() throws Exception { String token = "eyJhbGciOiJIUzUxMiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.VUo2Z9SWDV-XcOc_Hr6Lff3vl7L9e5Vb8ThXpmGDFjHxe3Dr1ZBmUChYF-xVA7cAdX1P_D4ZCUcsv3IefpVaJw"; - Algorithm algorithmString = Algorithm.HMAC512("secret"); - Algorithm algorithmBytes = Algorithm.HMAC512("secret".getBytes(StandardCharsets.UTF_8)); + Algorithm algorithmString = Algorithm.HMAC512(Constants.SECRET); + Algorithm algorithmBytes = Algorithm.HMAC512(Constants.SECRET.getBytes(StandardCharsets.UTF_8)); JWT jwt = JWT.require(algorithmString).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithmString.verify(decoded, EncodeType.Base64); @@ -166,7 +169,7 @@ public void shouldThrowOnVerifyWhenTheSecretIsInvalid() throws Exception { when(crypto.verifySignatureFor(anyString(), any(byte[].class), any(byte[].class), any(byte[].class))) .thenThrow(InvalidKeyException.class); - Algorithm algorithm = new HMACAlgorithm(crypto, "some-alg", "some-algorithm", "secret".getBytes(StandardCharsets.UTF_8)); + Algorithm algorithm = new HMACAlgorithm(crypto, "some-alg", "some-algorithm", Constants.SECRET.getBytes(StandardCharsets.UTF_8)); String token = "eyJhbGciOiJIUzI1NiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.mZ0m_N1J4PgeqWmi903JuUoDRZDBPB7HwkS4nVyWH1M"; JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); @@ -182,7 +185,7 @@ public void shouldThrowOnVerifyWhenTheSecretIsInvalid() throws Exception { @Test public void shouldDoHMAC256SigningWithBytes() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret".getBytes(StandardCharsets.UTF_8)); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET.getBytes(StandardCharsets.UTF_8)); String jwtContent = String.format("%s.%s", HS256Header, auth0IssPayload); byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); @@ -200,7 +203,7 @@ public void shouldDoHMAC256SigningWithBytes() throws Exception { @Test public void shouldDoHMAC384SigningWithBytes() throws Exception { - Algorithm algorithm = Algorithm.HMAC384("secret".getBytes(StandardCharsets.UTF_8)); + Algorithm algorithm = Algorithm.HMAC384(Constants.SECRET.getBytes(StandardCharsets.UTF_8)); String jwtContent = String.format("%s.%s", HS384Header, auth0IssPayload); byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); @@ -218,7 +221,7 @@ public void shouldDoHMAC384SigningWithBytes() throws Exception { @Test public void shouldDoHMAC512SigningWithBytes() throws Exception { - Algorithm algorithm = Algorithm.HMAC512("secret".getBytes(StandardCharsets.UTF_8)); + Algorithm algorithm = Algorithm.HMAC512(Constants.SECRET.getBytes(StandardCharsets.UTF_8)); String jwtContent = String.format("%s.%s", HS512Header, auth0IssPayload); byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); @@ -236,7 +239,7 @@ public void shouldDoHMAC512SigningWithBytes() throws Exception { @Test public void shouldDoHMAC256SigningWithString() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String jwtContent = String.format("%s.%s", HS256Header, auth0IssPayload); byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); @@ -254,7 +257,7 @@ public void shouldDoHMAC256SigningWithString() throws Exception { @Test public void shouldDoHMAC384SigningWithString() throws Exception { - Algorithm algorithm = Algorithm.HMAC384("secret"); + Algorithm algorithm = Algorithm.HMAC384(Constants.SECRET); String jwtContent = String.format("%s.%s", HS384Header, auth0IssPayload); byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); @@ -272,7 +275,7 @@ public void shouldDoHMAC384SigningWithString() throws Exception { @Test public void shouldDoHMAC512SigningWithString() throws Exception { - Algorithm algorithm = Algorithm.HMAC512("secret"); + Algorithm algorithm = Algorithm.HMAC512(Constants.SECRET); String jwtContent = String.format("%s.%s", HS512Header, auth0IssPayload); byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); @@ -298,7 +301,7 @@ public void shouldThrowOnSignWhenSignatureAlgorithmDoesNotExists() throws Except when(crypto.createSignatureFor(anyString(), any(byte[].class), any(byte[].class))) .thenThrow(NoSuchAlgorithmException.class); - Algorithm algorithm = new HMACAlgorithm(crypto, "some-alg", "some-algorithm", "secret".getBytes(StandardCharsets.UTF_8)); + Algorithm algorithm = new HMACAlgorithm(crypto, "some-alg", "some-algorithm", Constants.SECRET.getBytes(StandardCharsets.UTF_8)); algorithm.sign(new byte[0]); } @@ -312,13 +315,13 @@ public void shouldThrowOnSignWhenTheSecretIsInvalid() throws Exception { when(crypto.createSignatureFor(anyString(), any(byte[].class), any(byte[].class))) .thenThrow(InvalidKeyException.class); - Algorithm algorithm = new HMACAlgorithm(crypto, "some-alg", "some-algorithm", "secret".getBytes(StandardCharsets.UTF_8)); + Algorithm algorithm = new HMACAlgorithm(crypto, "some-alg", "some-algorithm", Constants.SECRET.getBytes(StandardCharsets.UTF_8)); algorithm.sign(new byte[0]); } @Test public void shouldReturnNullSigningKeyId() throws Exception { - assertThat(Algorithm.HMAC256("secret").getSigningKeyId(), is(nullValue())); + assertThat(Algorithm.HMAC256(Constants.SECRET).getSigningKeyId(), is(nullValue())); } } \ No newline at end of file diff --git a/lib/src/test/java/com/auth0/jwt/algorithms/NoneAlgorithmTest.java b/lib/src/test/java/com/auth0/jwt/algorithms/NoneAlgorithmTest.java index aea4415..67f8c7d 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/NoneAlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/NoneAlgorithmTest.java @@ -19,6 +19,10 @@ package com.auth0.jwt.algorithms; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + import com.auth0.jwt.creators.EncodeType; import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.exceptions.SignatureVerificationException; @@ -28,10 +32,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; - public class NoneAlgorithmTest { @Rule 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..8178b9b 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/RSAAlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/RSAAlgorithmTest.java @@ -19,6 +19,19 @@ package com.auth0.jwt.algorithms; +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.creators.EncodeType; import com.auth0.jwt.exceptions.AlgorithmMismatchException; import com.auth0.jwt.exceptions.SignatureGenerationException; @@ -26,26 +39,19 @@ 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 b9e7087..fdc54ce 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java @@ -21,24 +21,26 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static java.util.Arrays.asList; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.impl.PublicClaims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; -import com.auth0.jwt.jwts.JWT; +import com.auth0.jwt.interfaces.constants.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; 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 @@ -49,16 +51,16 @@ public class AccessJwtCreatorTest { @Test public void testAccessJwtCreatorAllStandardClaimsMustBeRequired() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = AccessJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = AccessJWT.require(algorithm); - JWT verifier = verification.createVerifierForAccess(asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForAccess(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -66,16 +68,16 @@ public void testAccessJwtCreatorAllStandardClaimsMustBeRequired() throws Excepti @Test public void testAccessJwtCreatorBase16Encoding() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = AccessJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .signBase16Encoding(algorithm); Verification verification = AccessJWT.require(algorithm); - JWT verifier = verification.createVerifierForAccess(asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForAccess(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode16Bytes(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -83,16 +85,16 @@ public void testAccessJwtCreatorBase16Encoding() throws Exception { @Test public void testAccessJwtCreatorBase32Encoding() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = AccessJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .signBase32Encoding(algorithm); Verification verification = AccessJWT.require(algorithm); - JWT verifier = verification.createVerifierForAccess(asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForAccess(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode32Bytes(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -102,16 +104,16 @@ public void testAccessJwtCreatorBase32Encoding() throws Exception { public void testAccessJwtCreatorInvalidIssuer() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'iss' value doesn't match the required one."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = AccessJwtCreator.build() .withIssuer("invalid") - .withSubject("subject") - .withAudience("audience") + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = AccessJWT.require(algorithm); - JWT verifier = verification.createVerifierForAccess(asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForAccess(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -119,16 +121,16 @@ public void testAccessJwtCreatorInvalidIssuer() throws Exception { public void testAccessJwtCreatorInvalidAudience() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'aud' value doesn't contain the required audience."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = AccessJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) .withAudience("invalid") .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = AccessJWT.require(algorithm); - JWT verifier = verification.createVerifierForAccess(asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForAccess(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -139,16 +141,16 @@ public void testAccessJwtCreatorNoneAlgorithmNotAllowed() throws Exception { Algorithm algorithm = Algorithm.none(); String token = AccessJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .setIsNoneAlgorithmAllowed(false) .sign(algorithm); Verification verification = AccessJWT.require(algorithm); - JWT verifier = verification.createVerifierForAccess(asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForAccess(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -159,15 +161,15 @@ public void testAccessJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() th Algorithm algorithm = Algorithm.none(); String token = AccessJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = AccessJWT.require(algorithm); - JWT verifier = verification.createVerifierForAccess(asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForAccess(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -175,15 +177,15 @@ public void testAccessJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() th public void testAccessJwtCreatorNoneAlgorithmAllowed() throws Exception { Algorithm algorithm = Algorithm.none(); String token = AccessJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .setIsNoneAlgorithmAllowed(true) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = AccessJWT.require(algorithm); - JWT verifier = verification.createVerifierForAccess(asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForAccess(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -191,17 +193,17 @@ public void testAccessJwtCreatorNoneAlgorithmAllowed() throws Exception { @Test public void testAccessJwtCreatorArrayClaim() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = AccessJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withArrayClaim("arrayKey", "arrayValue1", "arrayValue2") .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = AccessJWT.require(algorithm); - JWT verifier = verification.createVerifierForAccess(asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForAccess(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -209,17 +211,17 @@ public void testAccessJwtCreatorArrayClaim() throws Exception { @Test public void testAccessJwtCreatorNonStandardClaimStringValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = AccessJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", "nonStandardClaimValue") .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = AccessJWT.require(algorithm); - JWT verifier = verification.createVerifierForAccess(asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForAccess(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -227,17 +229,17 @@ public void testAccessJwtCreatorNonStandardClaimStringValue() throws Exception { @Test public void testAccessJwtCreatorNonStandardClaimIntegerValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = AccessJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", 999) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = AccessJWT.require(algorithm); - JWT verifier = verification.createVerifierForAccess(asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForAccess(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -245,17 +247,17 @@ public void testAccessJwtCreatorNonStandardClaimIntegerValue() throws Exception @Test public void testAccessJwtCreatorNonStandardClaimDoubleValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = AccessJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", 9.99) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = AccessJWT.require(algorithm); - JWT verifier = verification.createVerifierForAccess(asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForAccess(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -263,17 +265,17 @@ public void testAccessJwtCreatorNonStandardClaimDoubleValue() throws Exception { @Test public void testAccessJwtCreatorNonStandardClaimLongValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = AccessJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", 999L) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = AccessJWT.require(algorithm); - JWT verifier = verification.createVerifierForAccess(asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForAccess(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -281,17 +283,17 @@ public void testAccessJwtCreatorNonStandardClaimLongValue() throws Exception { @Test public void testAccessJwtCreatorNonStandardClaimBooleanValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = AccessJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", true) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = AccessJWT.require(algorithm); - JWT verifier = verification.createVerifierForAccess(asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForAccess(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -299,17 +301,17 @@ public void testAccessJwtCreatorNonStandardClaimBooleanValue() throws Exception @Test public void testAccessJwtCreatorNonStandardClaimDateValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = AccessJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", new Date()) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = AccessJWT.require(algorithm); - JWT verifier = verification.createVerifierForAccess(asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForAccess(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -326,26 +328,26 @@ public void testAccessJwtCreatorExpTimeHasPassed() throws Exception { long expLong = date.getTime(); Date expDate = new Date(expLong); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = AccessJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", new Date()) .withExp(expDate) .withIat(iat) .sign(algorithm); Verification verification = AccessJWT.require(algorithm); - JWT verifier = verification.createVerifierForAccess(asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForAccess(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); } - private static void verifyClaims(Map claims, Date exp) { - assertTrue(claims.get(PublicClaims.ISSUER).asList(String.class).get(0).equals("issuer")); - assertTrue(claims.get(PublicClaims.SUBJECT).asList(String.class).get(0).equals("subject")); - assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals("audience")); + private static void verifyClaims(Map claims, Date exp) { + assertTrue(claims.get(PublicClaims.ISSUER).asList(String.class).get(0).equals(Constants.ISSUER)); + assertTrue(claims.get(PublicClaims.SUBJECT).asList(String.class).get(0).equals(Constants.SUBJECT)); + assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals(Constants.AUDIENCE)); assertTrue(claims.get(PublicClaims.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..6c93219 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,26 @@ 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 java.util.Arrays.asList; + import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.impl.PublicClaims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.GoogleVerification; -import com.auth0.jwt.interfaces.Verification; -import com.auth0.jwt.jwts.AccessJWT; +import com.auth0.jwt.interfaces.constants.Constants; 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 { @@ -53,21 +50,21 @@ public class ExtendedJwtCreatorTest { @Test public void testExtendedJwtCreatorAllStandardClaimsMustBeRequired() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ExtendedJwtCreator.build() .withNbf(nbf) //this must be called first since ExtendedJwtCreator.build() returns an instance of ExtendedJwtCreator - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -75,21 +72,21 @@ public void testExtendedJwtCreatorAllStandardClaimsMustBeRequired() throws Excep @Test public void testExtendedJwtCreatorBase16Encoding() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ExtendedJwtCreator.build() .withNbf(nbf) //this must be called first since ExtendedJwtCreator.build() returns an instance of ExtendedJwtCreator - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .signBase16Encoding(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode16Bytes(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -97,21 +94,21 @@ public void testExtendedJwtCreatorBase16Encoding() throws Exception { @Test public void testExtendedJwtCreatorBase32Encoding() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ExtendedJwtCreator.build() .withNbf(nbf) //this must be called first since ExtendedJwtCreator.build() returns an instance of ExtendedJwtCreator - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .signBase32Encoding(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode32Bytes(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -121,21 +118,21 @@ public void testExtendedJwtCreatorBase32Encoding() throws Exception { public void testExtendedJwtCreatorInvalidIssuer() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'iss' value doesn't match the required one."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ExtendedJwtCreator.build() .withNbf(nbf) //this must be called first since ExtendedJwtCreator.build() returns an instance of ExtendedJwtCreator - .withPicture(PICTURE) - .withEmail(EMAIL) + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) .withIssuer("invalid") - .withSubject("subject") - .withAudience("audience") + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -143,21 +140,21 @@ public void testExtendedJwtCreatorInvalidIssuer() throws Exception { public void testExtendedJwtCreatorInvalidPicture() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'picture' value doesn't match the required one."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ExtendedJwtCreator.build() .withNbf(nbf) //this must be called first since ExtendedJwtCreator.build() returns an instance of ExtendedJwtCreator .withPicture("invalid") - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -165,21 +162,21 @@ public void testExtendedJwtCreatorInvalidPicture() throws Exception { public void testExtendedJwtCreatorInvalidEmail() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'email' value doesn't match the required one."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ExtendedJwtCreator.build() .withNbf(nbf) //this must be called first since ExtendedJwtCreator.build() returns an instance of ExtendedJwtCreator - .withPicture(PICTURE) + .withPicture(Constants.PICTURE) .withEmail("invalid") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -189,21 +186,21 @@ public void testExtendedJwtCreatorInvalidEmail() throws Exception { public void testExtendedJwtCreatorInvalidAudience() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'aud' value doesn't contain the required audience."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ExtendedJwtCreator.build() .withNbf(nbf) //this must be called first since ExtendedJwtCreator.build() returns an instance of ExtendedJwtCreator - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) .withAudience("invalid") .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -213,21 +210,21 @@ public void testExtendedJwtCreatorInvalidAudience() throws Exception { public void testExtendedJwtCreatorInvalidName() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'name' value doesn't match the required one."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ExtendedJwtCreator.build() .withNbf(nbf) //this must be called first since ExtendedJwtCreator.build() returns an instance of ExtendedJwtCreator - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .withName("invalid") .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -241,20 +238,20 @@ public void testExtendedJwtCreatorNoneAlgorithmNotAllowed() throws Exception { Algorithm algorithm = Algorithm.none(); String token = ExtendedJwtCreator.build() .withNbf(nbf) - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .setIsNoneAlgorithmAllowed(false) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -266,20 +263,20 @@ public void testExtendedJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() Algorithm algorithm = Algorithm.none(); String token = ExtendedJwtCreator.build() .withNbf(nbf) - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .setIsNoneAlgorithmAllowed(false) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -288,20 +285,20 @@ public void testExtendedJwtCreatorNoneAlgorithmAllowed() throws Exception { Algorithm algorithm = Algorithm.none(); String token = ExtendedJwtCreator.build() .withNbf(nbf) - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .setIsNoneAlgorithmAllowed(true) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -309,133 +306,133 @@ public void testExtendedJwtCreatorNoneAlgorithmAllowed() throws Exception { @Test public void testExtendedJwtCreatorNonStandardClaimStringValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ExtendedJwtCreator.build() .withNbf(nbf) - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .withNonStandardClaim("nonStandardClaim", "nonStandardClaimValue") .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @Test public void testExtendedJwtCreatorNonStandardClaimIntegerValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ExtendedJwtCreator.build() .withNbf(nbf) - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .withNonStandardClaim("nonStandardClaim", 999) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @Test public void testExtendedJwtCreatorNonStandardClaimLongValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ExtendedJwtCreator.build() .withNbf(nbf) - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .withNonStandardClaim("nonStandardClaim", 999L) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @Test public void testExtendedJwtCreatorNonStandardClaimDoubleValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ExtendedJwtCreator.build() .withNbf(nbf) - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .withNonStandardClaim("nonStandardClaim", 9.99) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @Test public void testExtendedJwtCreatorNonStandardClaimBooleanValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ExtendedJwtCreator.build() .withNbf(nbf) - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .withNonStandardClaim("nonStandardClaim", true) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @Test public void testExtendedJwtCreatorNonStandardClaimDateValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ExtendedJwtCreator.build() .withNbf(nbf) - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .withNonStandardClaim("nonStandardClaim", new Date()) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -450,23 +447,23 @@ public void testExtendedJwtCreatorExpTimeHasPassed() throws Exception { long expLong = date.getTime(); Date expDate = new Date(expLong); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ExtendedJwtCreator.build() .withNbf(nbf) - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(expDate) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .withNonStandardClaim("nonStandardClaim", new Date()) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1, 1).build(); + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } } 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..9926c8b 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/FbJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/FbJwtCreatorTest.java @@ -21,24 +21,25 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static com.auth0.jwt.interfaces.constants.Constants.SECRET; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.creators.FbJwtCreator; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.impl.PublicClaims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; +import com.auth0.jwt.interfaces.constants.PublicClaims; 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 @@ -50,7 +51,7 @@ public class FbJwtCreatorTest { @Test public void testFbJwtCreatorAllStandardClaimsMustBeRequired() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(SECRET); String token = FbJwtCreator.build() .withExp(exp) .withIat(iat) @@ -66,7 +67,7 @@ public void testFbJwtCreatorAllStandardClaimsMustBeRequired() throws Exception { @Test public void testFbJwtCreatorBase16Encoding() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(SECRET); String token = FbJwtCreator.build() .withExp(exp) .withIat(iat) @@ -82,7 +83,7 @@ public void testFbJwtCreatorBase16Encoding() throws Exception { @Test public void testFbJwtCreatorBase32Encoding() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(SECRET); String token = FbJwtCreator.build() .withExp(exp) .withIat(iat) @@ -100,7 +101,7 @@ public void testFbJwtCreatorBase32Encoding() throws Exception { public void testFbJwtCreatorInvalidUserId() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'userId' value doesn't match the required one."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(SECRET); String token = FbJwtCreator.build() .withExp(exp) .withIat(iat) @@ -116,7 +117,7 @@ public void testFbJwtCreatorInvalidUserId() throws Exception { public void testFbJwtCreatorInvalidAppId() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'appId' value doesn't match the required one."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(SECRET); String token = FbJwtCreator.build() .withExp(exp) .withIat(iat) @@ -132,7 +133,7 @@ public void testFbJwtCreatorInvalidAppId() throws Exception { public void testFbJwtCreatorUserIdNotProvided() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("Standard claim: UserId has not been set"); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(SECRET); String token = FbJwtCreator.build() .withExp(exp) .withIat(iat) @@ -197,7 +198,7 @@ public void testFbJwtCreatorNoneAlgorithmAllowed() throws Exception { @Test public void testFbJwtCreatorArrayClaim() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(SECRET); String token = FbJwtCreator.build() .withExp(exp) .withIat(iat) @@ -215,7 +216,7 @@ public void testFbJwtCreatorArrayClaim() throws Exception { @Test public void testFbJwtCreatorNonStandardClaimStringValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(SECRET); String token = FbJwtCreator.build() .withExp(exp) .withIat(iat) @@ -233,7 +234,7 @@ public void testFbJwtCreatorNonStandardClaimStringValue() throws Exception { @Test public void testFbJwtCreatorNonStandardClaimIntegerValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(SECRET); String token = FbJwtCreator.build() .withExp(exp) .withIat(iat) @@ -251,7 +252,7 @@ public void testFbJwtCreatorNonStandardClaimIntegerValue() throws Exception { @Test public void testFbJwtCreatorNonStandardClaimLongValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(SECRET); String token = FbJwtCreator.build() .withExp(exp) .withIat(iat) @@ -269,7 +270,7 @@ public void testFbJwtCreatorNonStandardClaimLongValue() throws Exception { @Test public void testFbJwtCreatorNonStandardClaimDoubleValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(SECRET); String token = FbJwtCreator.build() .withExp(exp) .withIat(iat) @@ -287,7 +288,7 @@ public void testFbJwtCreatorNonStandardClaimDoubleValue() throws Exception { @Test public void testFbJwtCreatorNonStandardClaimBooleanValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(SECRET); String token = FbJwtCreator.build() .withExp(exp) .withIat(iat) @@ -305,7 +306,7 @@ public void testFbJwtCreatorNonStandardClaimBooleanValue() throws Exception { @Test public void testFbJwtCreatorNonStandardClaimDateValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(SECRET); String token = FbJwtCreator.build() .withExp(exp) .withIat(iat) @@ -320,6 +321,7 @@ public void testFbJwtCreatorNonStandardClaimDateValue() throws Exception { Map claims = jwt.getClaims(); verifyClaims(claims); } + @Test public void testFbJwtCreatorExpTimeHasPassed() throws Exception { thrown.expect(TokenExpiredException.class); @@ -331,7 +333,7 @@ public void testFbJwtCreatorExpTimeHasPassed() throws Exception { long expLong = date.getTime(); Date expDate = new Date(expLong); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(SECRET); String token = FbJwtCreator.build() .withExp(expDate) .withIat(iat) @@ -348,7 +350,7 @@ public void testFbJwtCreatorExpTimeHasPassed() throws Exception { } - private static void verifyClaims(Map claims) { + 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())); 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..0cb98e0 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java @@ -21,53 +21,50 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static java.util.Arrays.asList; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.creators.GoogleJwtCreator; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.impl.PublicClaims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.GoogleVerification; +import com.auth0.jwt.interfaces.constants.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; 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 = "picture"; - public static final String EMAIL = "email"; - public static final String NAME = "name"; @Test public void testGoogleJwtCreatorAllStandardClaimsMustBeRequired() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -75,20 +72,20 @@ public void testGoogleJwtCreatorAllStandardClaimsMustBeRequired() throws Excepti @Test public void testGoogleJwtCreatorBase16Encoding() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .signBase16Encoding(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode16Bytes(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -96,20 +93,20 @@ public void testGoogleJwtCreatorBase16Encoding() throws Exception { @Test public void testGoogleJwtCreatorBase32Encoding() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .signBase32Encoding(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode32Bytes(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -120,20 +117,20 @@ public void testGoogleJwtCreatorWhenCertainRequiredClaimIsntProvided() throws Ex thrown.expect(Exception.class); thrown.expectMessage("Standard claim: Picture has not been set"); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -144,20 +141,20 @@ public void testGoogleJwtCreatorNoneAlgorithmNotAllowed() throws Exception { Algorithm algorithm = Algorithm.none(); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .setIsNoneAlgorithmAllowed(false) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -168,19 +165,19 @@ public void testGoogleJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() th Algorithm algorithm = Algorithm.none(); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -188,20 +185,20 @@ public void testGoogleJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() th public void testGoogleJwtCreatorNoneAlgorithmAllowed() throws Exception { Algorithm algorithm = Algorithm.none(); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .setIsNoneAlgorithmAllowed(true) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -211,21 +208,21 @@ public void testGoogleJwtCreatorNoneAlgorithmAllowed() throws Exception { public void testGoogleJwtCreatorArrayClaim() throws Exception { Algorithm algorithm = Algorithm.none(); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .setIsNoneAlgorithmAllowed(true) .withArrayClaim("arrayKey", "arrayValue1", "arrayValue2") - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -238,20 +235,20 @@ public void testGoogleJwtCreatorInvalidIssuer() throws Exception { Algorithm algorithm = Algorithm.none(); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) .withIssuer("invalid") - .withSubject("subject") - .withAudience("audience") + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .setIsNoneAlgorithmAllowed(true) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -260,21 +257,21 @@ public void testGoogleJwtCreatorInvalidAudience() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'aud' value doesn't contain the required audience."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) .withAudience("invalid") .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -283,21 +280,21 @@ public void testGoogleJwtCreatorInvalidPicture() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'picture' value doesn't match the required one."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() .withPicture("invalid") - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -306,21 +303,21 @@ public void testGoogleJwtCreatorInvalidEmail() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'email' value doesn't match the required one."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) + .withPicture(Constants.PICTURE) .withEmail("invalid") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -329,41 +326,41 @@ public void testGoogleJwtCreatorInvalidName() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'name' value doesn't match the required one."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .withName("invalid") .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @Test public void testGoogleJwtCreatorNonStandardClaimString() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .withNonStandardClaim("nonStandardClaim", "nonStandardClaimValue") .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -371,21 +368,21 @@ public void testGoogleJwtCreatorNonStandardClaimString() throws Exception { @Test public void testGoogleJwtCreatorNonStandardClaimBoolean() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .withNonStandardClaim("nonStandardClaim", true) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -393,21 +390,21 @@ public void testGoogleJwtCreatorNonStandardClaimBoolean() throws Exception { @Test public void testGoogleJwtCreatorNonStandardClaimInteger() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .withNonStandardClaim("nonStandardClaim", 999) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -415,21 +412,21 @@ public void testGoogleJwtCreatorNonStandardClaimInteger() throws Exception { @Test public void testGoogleJwtCreatorNonStandardClaimLong() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .withNonStandardClaim("nonStandardClaim", 999L) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -437,21 +434,21 @@ public void testGoogleJwtCreatorNonStandardClaimLong() throws Exception { @Test public void testGoogleJwtCreatorNonStandardClaimDouble() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .withNonStandardClaim("nonStandardClaim", 9.99) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -459,21 +456,21 @@ public void testGoogleJwtCreatorNonStandardClaimDouble() throws Exception { @Test public void testGoogleJwtCreatorNonStandardClaimDate() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .withNonStandardClaim("nonStandardClaim", new Date()) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -490,20 +487,20 @@ public void testGoogleJwtCreatorExpTimeHasPassed() throws Exception { long expLong = date.getTime(); Date expDate = new Date(expLong); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(expDate) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -518,38 +515,38 @@ public void testGoogleJwtCreatorTokenCantBeUsedBefore() throws Exception { long expLong = date.getTime(); Date iatDate = new Date(expLong); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = GoogleJwtCreator.build() - .withPicture(PICTURE) - .withEmail(EMAIL) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withPicture(Constants.PICTURE) + .withEmail(Constants.EMAIL) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iatDate) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); - JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + JWT verifier = verification.createVerifierForGoogle(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), + Constants.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @Test - public void testCreateVerifierForExtended() throws Exception{ + public void testCreateVerifierForExtended() throws Exception { thrown.expect(UnsupportedOperationException.class); thrown.expectMessage("you shouldn't be calling this method"); - GoogleVerification verification = GoogleJWT.require(Algorithm.HMAC256("secret")); + GoogleVerification verification = GoogleJWT.require(Algorithm.HMAC256(Constants.SECRET)); verification.createVerifierForExtended(null, null, null, null, null, 1L, 1L, 1L); } - protected static void verifyClaims(Map claims, Date exp) { - assertTrue(claims.get(PICTURE).asString().equals(PICTURE)); - assertTrue(claims.get(EMAIL).asString().equals(EMAIL)); - assertTrue(claims.get(PublicClaims.ISSUER).asList(String.class).get(0).equals("issuer")); - assertTrue(claims.get(PublicClaims.SUBJECT).asList(String.class).get(0).equals("subject")); - assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals("audience")); + protected static void verifyClaims(Map claims, Date exp) { + assertTrue(claims.get(Constants.PICTURE).asString().equals(Constants.PICTURE)); + assertTrue(claims.get(Constants.EMAIL).asString().equals(Constants.EMAIL)); + assertTrue(claims.get(PublicClaims.ISSUER).asList(String.class).get(0).equals(Constants.ISSUER)); + assertTrue(claims.get(PublicClaims.SUBJECT).asList(String.class).get(0).equals(Constants.SUBJECT)); + assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals(Constants.AUDIENCE)); assertTrue(claims.get(PublicClaims.EXPIRES_AT).asDate().toString().equals(exp.toString())); - assertTrue(claims.get(NAME).asString().equals(NAME)); + assertTrue(claims.get(Constants.NAME).asString().equals(Constants.NAME)); } } \ No newline at end of file diff --git a/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java b/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java index bb7a332..f0b8592 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java @@ -19,24 +19,26 @@ package com.auth0.jwt.creators; -import com.auth0.jwt.TimeUtil; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static java.util.Arrays.asList; +import static org.junit.Assert.assertTrue; + +import com.auth0.jwt.TimeUtil; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; -import com.auth0.jwt.impl.PublicClaims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; +import com.auth0.jwt.interfaces.constants.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; 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 @@ -46,15 +48,15 @@ public class ImplicitJwtCreatorTest { @Test public void testImplicitJwtCreatorAllStandardClaimsMustBeRequired() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ImplicitJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withIat(iat) .sign(algorithm); Verification verification = ImplicitJWT.require(algorithm); - JWT verifier = verification.createVerifierForImplicit(asList("issuer"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims); @@ -62,15 +64,15 @@ public void testImplicitJwtCreatorAllStandardClaimsMustBeRequired() throws Excep @Test public void testImplicitJwtCreatorBase16Encoding() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ImplicitJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withIat(iat) .signBase16Encoding(algorithm); Verification verification = ImplicitJWT.require(algorithm); - JWT verifier = verification.createVerifierForImplicit(asList("issuer"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode16Bytes(token); Map claims = jwt.getClaims(); verifyClaims(claims); @@ -78,15 +80,15 @@ public void testImplicitJwtCreatorBase16Encoding() throws Exception { @Test public void testImplicitJwtCreatorBase32Encoding() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ImplicitJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withIat(iat) .signBase32Encoding(algorithm); Verification verification = ImplicitJWT.require(algorithm); - JWT verifier = verification.createVerifierForImplicit(asList("issuer"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode32Bytes(token); Map claims = jwt.getClaims(); verifyClaims(claims); @@ -96,15 +98,15 @@ public void testImplicitJwtCreatorBase32Encoding() throws Exception { public void testImplicitJwtCreatorInvalidIssuer() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'iss' value doesn't match the required one."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ImplicitJwtCreator.build() .withIssuer("invalid") - .withSubject("subject") - .withAudience("audience") + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withIat(iat) .sign(algorithm); Verification verification = ImplicitJWT.require(algorithm); - JWT verifier = verification.createVerifierForImplicit(asList("issuer"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims); @@ -114,15 +116,15 @@ public void testImplicitJwtCreatorInvalidIssuer() throws Exception { public void testImplicitJwtCreatorInvalidAudience() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'aud' value doesn't contain the required audience."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ImplicitJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) .withAudience("invalid") .withIat(iat) .sign(algorithm); Verification verification = ImplicitJWT.require(algorithm); - JWT verifier = verification.createVerifierForImplicit(asList("issuer"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims); @@ -132,14 +134,14 @@ public void testImplicitJwtCreatorInvalidAudience() throws Exception { public void testImplicitJwtCreatorIssuerNotProvided() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("Standard claim: Issuer has not been set"); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ImplicitJwtCreator.build() - .withSubject("subject") - .withAudience("audience") + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withIat(iat) .sign(algorithm); Verification verification = ImplicitJWT.require(algorithm); - JWT verifier = verification.createVerifierForImplicit(asList("issuer"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims); @@ -152,15 +154,15 @@ public void testImplicitJwtCreatorNoneAlgorithmNotAllowed() throws Exception { Algorithm algorithm = Algorithm.none(); String token = ImplicitJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .setIsNoneAlgorithmAllowed(false) .withIat(iat) .sign(algorithm); Verification verification = ImplicitJWT.require(algorithm); - JWT verifier = verification.createVerifierForImplicit(asList("issuer"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -171,13 +173,13 @@ public void testImplicitJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() Algorithm algorithm = Algorithm.none(); String token = ImplicitJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withIat(iat) .sign(algorithm); Verification verification = ImplicitJWT.require(algorithm); - JWT verifier = verification.createVerifierForImplicit(asList("issuer"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -185,14 +187,14 @@ public void testImplicitJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() public void testImplicitJwtCreatorNoneAlgorithmAllowed() throws Exception { Algorithm algorithm = Algorithm.none(); String token = ImplicitJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .setIsNoneAlgorithmAllowed(true) .withIat(iat) .sign(algorithm); Verification verification = ImplicitJWT.require(algorithm); - JWT verifier = verification.createVerifierForImplicit(asList("issuer"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims); @@ -200,16 +202,16 @@ public void testImplicitJwtCreatorNoneAlgorithmAllowed() throws Exception { @Test public void testImplicitJwtCreatorArrayClaim() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ImplicitJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withIat(TimeUtil.generateRandomIatDateInPast()) .withArrayClaim("arrayKey", "arrayValue1", "arrayValue2") .sign(algorithm); Verification verification = ImplicitJWT.require(algorithm); - JWT verifier = verification.createVerifierForImplicit(asList("issuer"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims); @@ -217,16 +219,16 @@ public void testImplicitJwtCreatorArrayClaim() throws Exception { @Test public void testImplicitJwtCreatorNonStandardClaimStringValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ImplicitJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withIat(TimeUtil.generateRandomIatDateInPast()) .withNonStandardClaim("nonStandardClaim", "nonStandardClaimValue") .sign(algorithm); Verification verification = ImplicitJWT.require(algorithm); - JWT verifier = verification.createVerifierForImplicit(asList("issuer"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims); @@ -234,16 +236,16 @@ public void testImplicitJwtCreatorNonStandardClaimStringValue() throws Exception @Test public void testImplicitJwtCreatorNonStandardClaimIntegerValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ImplicitJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withIat(TimeUtil.generateRandomIatDateInPast()) .withNonStandardClaim("nonStandardClaim", 999) .sign(algorithm); Verification verification = ImplicitJWT.require(algorithm); - JWT verifier = verification.createVerifierForImplicit(asList("issuer"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims); @@ -251,16 +253,16 @@ public void testImplicitJwtCreatorNonStandardClaimIntegerValue() throws Exceptio @Test public void testImplicitJwtCreatorNonStandardClaimLongValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ImplicitJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withIat(TimeUtil.generateRandomIatDateInPast()) .withNonStandardClaim("nonStandardClaim", 999L) .sign(algorithm); Verification verification = ImplicitJWT.require(algorithm); - JWT verifier = verification.createVerifierForImplicit(asList("issuer"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims); @@ -268,16 +270,16 @@ public void testImplicitJwtCreatorNonStandardClaimLongValue() throws Exception { @Test public void testImplicitJwtCreatorNonStandardClaimDoubleValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ImplicitJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withIat(TimeUtil.generateRandomIatDateInPast()) .withNonStandardClaim("nonStandardClaim", 9.99) .sign(algorithm); Verification verification = ImplicitJWT.require(algorithm); - JWT verifier = verification.createVerifierForImplicit(asList("issuer"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims); @@ -285,16 +287,16 @@ public void testImplicitJwtCreatorNonStandardClaimDoubleValue() throws Exception @Test public void testImplicitJwtCreatorNonStandardClaimBooleanValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ImplicitJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withIat(TimeUtil.generateRandomIatDateInPast()) .withNonStandardClaim("nonStandardClaim", true) .sign(algorithm); Verification verification = ImplicitJWT.require(algorithm); - JWT verifier = verification.createVerifierForImplicit(asList("issuer"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims); @@ -302,24 +304,24 @@ public void testImplicitJwtCreatorNonStandardClaimBooleanValue() throws Exceptio @Test public void testImplicitJwtCreatorNonStandardClaimDateValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ImplicitJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withIat(TimeUtil.generateRandomIatDateInPast()) .withNonStandardClaim("nonStandardClaim", new Date()) .sign(algorithm); Verification verification = ImplicitJWT.require(algorithm); - JWT verifier = verification.createVerifierForImplicit(asList("issuer"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims); } - private static void verifyClaims(Map claims) { - assertTrue(claims.get(PublicClaims.ISSUER).asList(String.class).get(0).equals("issuer")); - assertTrue(claims.get(PublicClaims.SUBJECT).asList(String.class).get(0).equals("subject")); - assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals("audience")); + private static void verifyClaims(Map claims) { + assertTrue(claims.get(PublicClaims.ISSUER).asList(String.class).get(0).equals(Constants.ISSUER)); + assertTrue(claims.get(PublicClaims.SUBJECT).asList(String.class).get(0).equals(Constants.SUBJECT)); + assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals(Constants.AUDIENCE)); } } \ No newline at end of file diff --git a/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java b/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java index 7404e67..7d3aaf6 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java @@ -19,30 +19,29 @@ package com.auth0.jwt.creators; +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.when; + import com.auth0.jwt.JsonMatcher; 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.ECDSAKeyProvider; import com.auth0.jwt.interfaces.RSAKeyProvider; -import org.apache.commons.codec.binary.Base64; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - +import com.auth0.jwt.interfaces.constants.Constants; import java.nio.charset.StandardCharsets; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.RSAPrivateKey; import java.util.Date; import java.util.HashMap; import java.util.Map; - -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.when; +import org.apache.commons.codec.binary.Base64; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; public class JWTCreatorTest { @@ -68,7 +67,7 @@ public void shouldAddHeaderClaim() throws Exception { header.put("asd", 123); String signed = JWTCreator.init() .withHeader(header) - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(signed, is(notNullValue())); String[] parts = signed.split("\\."); @@ -80,7 +79,7 @@ public void shouldAddHeaderClaim() throws Exception { public void shouldAddKeyId() throws Exception { String signed = JWTCreator.init() .withKeyId("56a8bd44da435300010000015f5ed") - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(signed, is(notNullValue())); String[] parts = signed.split("\\."); @@ -158,7 +157,7 @@ public void shouldNotOverwriteKeyIdIfAddedFromECDSAAlgorithms() throws Exception public void shouldAddIssuer() throws Exception { String signed = JWTCreator.init() .withIssuer("auth0") - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(signed, is(notNullValue())); assertThat(TokenUtils.splitToken(signed)[1], is("eyJpc3MiOlsiYXV0aDAiXX0")); @@ -168,7 +167,7 @@ public void shouldAddIssuer() throws Exception { public void shouldAddSubject() throws Exception { String signed = JWTCreator.init() .withSubject("1234567890") - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(signed, is(notNullValue())); assertThat(TokenUtils.splitToken(signed)[1], is("eyJzdWIiOlsiMTIzNDU2Nzg5MCJdfQ")); @@ -178,7 +177,7 @@ public void shouldAddSubject() throws Exception { public void shouldAddAudience() throws Exception { String signed = JWTCreator.init() .withAudience("Mark") - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(signed, is(notNullValue())); assertThat(TokenUtils.splitToken(signed)[1], is("eyJhdWQiOiJNYXJrIn0")); @@ -186,7 +185,7 @@ public void shouldAddAudience() throws Exception { String signedArr = JWTCreator.init() .withAudience("Mark", "David") - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(signedArr, is(notNullValue())); assertThat(TokenUtils.splitToken(signedArr)[1], is("eyJhdWQiOlsiTWFyayIsIkRhdmlkIl19")); @@ -196,7 +195,7 @@ public void shouldAddAudience() throws Exception { public void shouldAddExpiresAt() throws Exception { String signed = JWTCreator.init() .withExpiresAt(new Date(1477592000)) - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(signed, is(notNullValue())); assertThat(TokenUtils.splitToken(signed)[1], is("eyJleHAiOjE0Nzc1OTJ9")); @@ -206,7 +205,7 @@ public void shouldAddExpiresAt() throws Exception { public void shouldAddNotBefore() throws Exception { String signed = JWTCreator.init() .withNotBefore(new Date(1477592000)) - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(signed, is(notNullValue())); assertThat(TokenUtils.splitToken(signed)[1], is("eyJuYmYiOjE0Nzc1OTJ9")); @@ -216,7 +215,7 @@ public void shouldAddNotBefore() throws Exception { public void shouldAddIssuedAt() throws Exception { String signed = JWTCreator.init() .withIssuedAt(new Date(1477592000)) - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(signed, is(notNullValue())); assertThat(TokenUtils.splitToken(signed)[1], is("eyJpYXQiOjE0Nzc1OTJ9")); @@ -226,7 +225,7 @@ public void shouldAddIssuedAt() throws Exception { public void shouldAddJWTId() throws Exception { String signed = JWTCreator.init() .withJWTId("jwt_id_123") - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(signed, is(notNullValue())); assertThat(TokenUtils.splitToken(signed)[1], is("eyJqdGkiOiJqd3RfaWRfMTIzIn0")); @@ -237,7 +236,7 @@ public void shouldRemoveClaimWhenPassingNull() throws Exception { String signed = JWTCreator.init() .withIssuer("iss") .withIssuer(null) - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(signed, is(notNullValue())); assertThat(TokenUtils.splitToken(signed)[1], is("e30")); @@ -246,7 +245,7 @@ public void shouldRemoveClaimWhenPassingNull() throws Exception { @Test public void shouldSetCorrectAlgorithmInTheHeader() throws Exception { String signed = JWTCreator.init() - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(signed, is(notNullValue())); String[] parts = signed.split("\\."); @@ -257,7 +256,7 @@ public void shouldSetCorrectAlgorithmInTheHeader() throws Exception { @Test public void shouldSetCorrectTypeInTheHeader() throws Exception { String signed = JWTCreator.init() - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(signed, is(notNullValue())); String[] parts = signed.split("\\."); @@ -285,7 +284,7 @@ public void shouldThrowOnNullCustomClaimName() throws Exception { public void shouldAcceptCustomClaimOfTypeString() throws Exception { String jwt = JWTCreator.init() .withNonStandardClaim("name", "value") - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); @@ -296,7 +295,7 @@ public void shouldAcceptCustomClaimOfTypeString() throws Exception { public void shouldAcceptCustomClaimOfTypeInteger() throws Exception { String jwt = JWTCreator.init() .withNonStandardClaim("name", 123) - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); @@ -307,7 +306,7 @@ public void shouldAcceptCustomClaimOfTypeInteger() throws Exception { public void shouldAcceptCustomClaimOfTypeLong() throws Exception { String jwt = JWTCreator.init() .withNonStandardClaim("name", Long.MAX_VALUE) - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); @@ -318,7 +317,7 @@ public void shouldAcceptCustomClaimOfTypeLong() throws Exception { public void shouldAcceptCustomClaimOfTypeDouble() throws Exception { String jwt = JWTCreator.init() .withNonStandardClaim("name", 23.45) - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); @@ -329,7 +328,7 @@ public void shouldAcceptCustomClaimOfTypeDouble() throws Exception { public void shouldAcceptCustomClaimOfTypeBoolean() throws Exception { String jwt = JWTCreator.init() .withNonStandardClaim("name", true) - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); @@ -341,7 +340,7 @@ public void shouldAcceptCustomClaimOfTypeDate() throws Exception { Date date = new Date(1478891521000L); String jwt = JWTCreator.init() .withNonStandardClaim("name", date) - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); @@ -352,7 +351,7 @@ public void shouldAcceptCustomClaimOfTypeDate() throws Exception { public void shouldAcceptCustomArrayClaimOfTypeString() throws Exception { String jwt = JWTCreator.init() .withArrayClaim("name", new String[]{"text", "123", "true"}) - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); @@ -363,7 +362,7 @@ public void shouldAcceptCustomArrayClaimOfTypeString() throws Exception { public void shouldAcceptCustomArrayClaimOfTypeInteger() throws Exception { String jwt = JWTCreator.init() .withArrayClaim("name", new Integer[]{1, 2, 3}) - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); @@ -374,7 +373,7 @@ public void shouldAcceptCustomArrayClaimOfTypeInteger() throws Exception { public void shouldAcceptCustomArrayClaimOfTypeLong() throws Exception { String jwt = JWTCreator.init() .withArrayClaim("name", new Long[]{1L, 2L, 3L}) - .sign(Algorithm.HMAC256("secret")); + .sign(Algorithm.HMAC256(Constants.SECRET)); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); 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..e52393f 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/RiscJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/RiscJwtCreatorTest.java @@ -21,24 +21,26 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static java.util.Arrays.asList; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.impl.PublicClaims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; +import com.auth0.jwt.interfaces.constants.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; 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 @@ -50,18 +52,18 @@ public class RiscJwtCreatorTest { @Test public void testRiscJwtCreatorAllStandardClaimsMustBeRequired() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = RiscJwtCreator.build() .withJWTId(jti) .withNbf(nbf) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -69,18 +71,18 @@ public void testRiscJwtCreatorAllStandardClaimsMustBeRequired() throws Exception @Test public void testRiscJwtCreatorBase16Encoding() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = RiscJwtCreator.build() .withJWTId(jti) .withNbf(nbf) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .signBase16Encoding(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode16Bytes(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -88,18 +90,18 @@ public void testRiscJwtCreatorBase16Encoding() throws Exception { @Test public void testRiscJwtCreatorBase32Encoding() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = RiscJwtCreator.build() .withJWTId(jti) .withNbf(nbf) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .signBase32Encoding(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode32Bytes(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -110,17 +112,17 @@ public void testRiscJwtCreatorJtiNotProvidedButRequired() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("Jti has not been set"); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = RiscJwtCreator.build() .withNbf(nbf) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -131,16 +133,16 @@ public void testRiscJwtCreatorExpNotProvidedButNotRequired() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("Jti has not been set"); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = RiscJwtCreator.build() .withNbf(nbf) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withIat(iat) .sign(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, -1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, -1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -150,18 +152,18 @@ public void testRiscJwtCreatorExpNotProvidedButNotRequired() throws Exception { public void testRiscJwtCreatorInvalidIssuer() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'iss' value doesn't match the required one."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = RiscJwtCreator.build() .withJWTId(jti) .withNbf(nbf) .withIssuer("invalid") - .withSubject("subject") - .withAudience("audience") + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -169,18 +171,18 @@ public void testRiscJwtCreatorInvalidIssuer() throws Exception { public void testRiscJwtCreatorInvalidAudience() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'aud' value doesn't contain the required audience."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = RiscJwtCreator.build() .withJWTId(jti) .withNbf(nbf) - .withIssuer("issuer") - .withSubject("subject") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) .withAudience("invalid") .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -193,15 +195,15 @@ public void testRiscJwtCreatorNoneAlgorithmNotAllowed() throws Exception { String token = RiscJwtCreator.build() .withJWTId(jti) .withNbf(nbf) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .setIsNoneAlgorithmAllowed(false) .sign(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -214,14 +216,14 @@ public void testRiscJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() thro String token = RiscJwtCreator.build() .withJWTId(jti) .withNbf(nbf) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -231,32 +233,32 @@ public void testRiscJwtCreatorNoneAlgorithmAllowed() throws Exception { String token = RiscJwtCreator.build() .withJWTId(jti) .withNbf(nbf) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .setIsNoneAlgorithmAllowed(true) .sign(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @Test public void testRiscJwtCreatorArrayClaim() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = RiscJwtCreator.build() .withJWTId(jti) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withArrayClaim("arrayKey", "arrayValue1", "arrayValue2") .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -264,18 +266,18 @@ public void testRiscJwtCreatorArrayClaim() throws Exception { @Test public void testRiscJwtCreatorNonStandardClaimStringValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = RiscJwtCreator.build() .withJWTId(jti) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", "nonStandardClaimValue") .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -283,18 +285,18 @@ public void testRiscJwtCreatorNonStandardClaimStringValue() throws Exception { @Test public void testRiscJwtCreatorNonStandardClaimIntegerValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = RiscJwtCreator.build() .withJWTId(jti) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", 999) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -302,18 +304,18 @@ public void testRiscJwtCreatorNonStandardClaimIntegerValue() throws Exception { @Test public void testRiscJwtCreatorNonStandardClaimDoubleValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = RiscJwtCreator.build() .withJWTId(jti) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", 9.99) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -321,18 +323,18 @@ public void testRiscJwtCreatorNonStandardClaimDoubleValue() throws Exception { @Test public void testRiscJwtCreatorNonStandardClaimLongValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = RiscJwtCreator.build() .withJWTId(jti) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", 999L) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -340,18 +342,18 @@ public void testRiscJwtCreatorNonStandardClaimLongValue() throws Exception { @Test public void testRiscJwtCreatorNonStandardClaimBooleanValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = RiscJwtCreator.build() .withJWTId(jti) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", true) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -359,18 +361,18 @@ public void testRiscJwtCreatorNonStandardClaimBooleanValue() throws Exception { @Test public void testRiscJwtCreatorNonStandardClaimDateValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = RiscJwtCreator.build() .withJWTId(jti) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", new Date()) .withExp(exp) .withIat(iat) .sign(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -387,27 +389,27 @@ public void testRiscJwtCreatorExpTimeHasPassed() throws Exception { long expLong = date.getTime(); Date expDate = new Date(expLong); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = RiscJwtCreator.build() .withJWTId(jti) - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", new Date()) .withExp(expDate) .withIat(iat) .sign(algorithm); Verification verification = RiscJWT.require(algorithm); - JWT verifier = verification.createVerifierForRisc(jti, asList("issuer"), asList("audience"), 1, 1, 1).build(); + JWT verifier = verification.createVerifierForRisc(jti, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); } - private static void verifyClaims(Map claims, Date exp) { - assertTrue(claims.get(PublicClaims.ISSUER).asList(String.class).get(0).equals("issuer")); - assertTrue(claims.get(PublicClaims.SUBJECT).asList(String.class).get(0).equals("subject")); - assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals("audience")); + private static void verifyClaims(Map claims, Date exp) { + assertTrue(claims.get(PublicClaims.ISSUER).asList(String.class).get(0).equals(Constants.ISSUER)); + assertTrue(claims.get(PublicClaims.SUBJECT).asList(String.class).get(0).equals(Constants.SUBJECT)); + assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals(Constants.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..d48ae2d 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java @@ -21,25 +21,26 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static java.util.Arrays.asList; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.creators.ScopedJwtCreator; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.impl.PublicClaims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; +import com.auth0.jwt.interfaces.constants.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; 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 @@ -50,17 +51,17 @@ public class ScopedJwtCreatorTest { @Test public void testScopedJwtCreatorAllStandardClaimsMustBeRequired() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ScopedJwtCreator.build() - .withScope("scope") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withScope(Constants.SCOPE) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -68,17 +69,17 @@ public void testScopedJwtCreatorAllStandardClaimsMustBeRequired() throws Excepti @Test public void testScopedJwtCreatorBase16Encoding() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ScopedJwtCreator.build() - .withScope("scope") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withScope(Constants.SCOPE) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode16Bytes(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -86,17 +87,17 @@ public void testScopedJwtCreatorBase16Encoding() throws Exception { @Test public void testScopedJwtCreatorBase32Encoding() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ScopedJwtCreator.build() - .withScope("scope") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withScope(Constants.SCOPE) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode32Bytes(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -106,17 +107,17 @@ public void testScopedJwtCreatorBase32Encoding() throws Exception { public void testScopedJwtCreatorInvalidScope() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'scope' value doesn't match the required one."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ScopedJwtCreator.build() .withScope("invalid") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -124,17 +125,17 @@ public void testScopedJwtCreatorInvalidScope() throws Exception { public void testScopedJwtCreatorInvalidIssuer() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'iss' value doesn't match the required one."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ScopedJwtCreator.build() - .withScope("scope") + .withScope(Constants.SCOPE) .withIssuer("invalid") - .withSubject("subject") - .withAudience("audience") + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -142,17 +143,17 @@ public void testScopedJwtCreatorInvalidIssuer() throws Exception { public void testScopedJwtCreatorInvalidAudience() throws Exception { thrown.expect(InvalidClaimException.class); thrown.expectMessage("The Claim 'aud' value doesn't contain the required audience."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ScopedJwtCreator.build() - .withScope("scope") - .withIssuer("issuer") - .withSubject("subject") + .withScope(Constants.SCOPE) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) .withAudience("invalid") .withExp(exp) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -160,16 +161,16 @@ public void testScopedJwtCreatorInvalidAudience() throws Exception { public void testScopedJwtCreatorScopeNotProvided() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("Standard claim: Scope has not been set"); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ScopedJwtCreator.build() - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -182,17 +183,17 @@ public void testScopedJwtCreatorNoneAlgorithmNotAllowed() throws Exception { Algorithm algorithm = Algorithm.none(); String token = ScopedJwtCreator.build() - .withScope("scope") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withScope(Constants.SCOPE) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) .setIsNoneAlgorithmAllowed(false) .sign(algorithm); Verification verification = ScopedJWT.require(algorithm); - JWT verifier = verification.createVerifierForScoped("scope", asList("issuer"), asList("audience"), 1, 1).build(); + JWT verifier = verification.createVerifierForScoped(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -203,16 +204,16 @@ public void testScopedJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() th Algorithm algorithm = Algorithm.none(); String token = ScopedJwtCreator.build() - .withScope("scope") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withScope(Constants.SCOPE) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withExp(exp) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -220,16 +221,16 @@ public void testScopedJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() th public void testScopedJwtCreatorNoneAlgorithmAllowed() throws Exception { Algorithm algorithm = Algorithm.none(); String token = ScopedJwtCreator.build() - .withScope("scope") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withScope(Constants.SCOPE) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .setIsNoneAlgorithmAllowed(true) .withExp(exp) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -237,18 +238,18 @@ public void testScopedJwtCreatorNoneAlgorithmAllowed() throws Exception { @Test public void testScopedJwtCreatorArrayClaim() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ScopedJwtCreator.build() - .withScope("scope") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withScope(Constants.SCOPE) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withArrayClaim("arrayKey", "arrayValue1", "arrayValue2") .withExp(exp) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -256,18 +257,18 @@ public void testScopedJwtCreatorArrayClaim() throws Exception { @Test public void testScopedJwtCreatorNonStandardClaimStringValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ScopedJwtCreator.build() - .withScope("scope") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withScope(Constants.SCOPE) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", "nonStandardClaimValue") .withExp(exp) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -275,18 +276,18 @@ public void testScopedJwtCreatorNonStandardClaimStringValue() throws Exception { @Test public void testScopedJwtCreatorNonStandardClaimIntegerValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ScopedJwtCreator.build() - .withScope("scope") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withScope(Constants.SCOPE) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", 999) .withExp(exp) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -294,18 +295,18 @@ public void testScopedJwtCreatorNonStandardClaimIntegerValue() throws Exception @Test public void testScopedJwtCreatorNonStandardClaimDoubleValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ScopedJwtCreator.build() - .withScope("scope") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withScope(Constants.SCOPE) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", 9.99) .withExp(exp) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -313,18 +314,18 @@ public void testScopedJwtCreatorNonStandardClaimDoubleValue() throws Exception { @Test public void testScopedJwtCreatorNonStandardClaimLongValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ScopedJwtCreator.build() - .withScope("scope") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withScope(Constants.SCOPE) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", 999L) .withExp(exp) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -332,18 +333,18 @@ public void testScopedJwtCreatorNonStandardClaimLongValue() throws Exception { @Test public void testScopedJwtCreatorNonStandardClaimBooleanValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ScopedJwtCreator.build() - .withScope("scope") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withScope(Constants.SCOPE) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", true) .withExp(exp) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -351,18 +352,18 @@ public void testScopedJwtCreatorNonStandardClaimBooleanValue() throws Exception @Test public void testScopedJwtCreatorNonStandardClaimDateValue() throws Exception { - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ScopedJwtCreator.build() - .withScope("scope") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withScope(Constants.SCOPE) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", new Date()) .withExp(exp) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -379,27 +380,27 @@ public void testScopedJwtCreatorExpTimeHasPassed() throws Exception { long expLong = date.getTime(); Date expDate = new Date(expLong); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ScopedJwtCreator.build() - .withScope("scope") - .withIssuer("issuer") - .withSubject("subject") - .withAudience("audience") + .withScope(Constants.SCOPE) + .withIssuer(Constants.ISSUER) + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withNonStandardClaim("nonStandardClaim", new Date()) .withExp(expDate) .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(Constants.SCOPE, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, expDate); } - private static void verifyClaims(Map claims, Date exp) { - assertTrue(claims.get(PublicClaims.ISSUER).asList(String.class).get(0).equals("issuer")); - assertTrue(claims.get(PublicClaims.SUBJECT).asList(String.class).get(0).equals("subject")); - assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals("audience")); + private static void verifyClaims(Map claims, Date exp) { + assertTrue(claims.get(PublicClaims.ISSUER).asList(String.class).get(0).equals(Constants.ISSUER)); + assertTrue(claims.get(PublicClaims.SUBJECT).asList(String.class).get(0).equals(Constants.SUBJECT)); + assertTrue(claims.get(PublicClaims.AUDIENCE).asString().equals(Constants.AUDIENCE)); assertTrue(claims.get(PublicClaims.EXPIRES_AT).asDate().toString().equals(exp.toString())); } } \ No newline at end of file diff --git a/lib/src/test/java/com/auth0/jwt/impl/BasicHeaderTest.java b/lib/src/test/java/com/auth0/jwt/impl/BasicHeaderTest.java index bd2c59c..5221c1b 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/BasicHeaderTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/BasicHeaderTest.java @@ -19,20 +19,22 @@ package com.auth0.jwt.impl; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.TextNode; +import java.util.HashMap; +import java.util.Map; import org.hamcrest.collection.IsMapContaining; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.util.HashMap; -import java.util.Map; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; - public class BasicHeaderTest { @Rule diff --git a/lib/src/test/java/com/auth0/jwt/impl/ClaimsHolderTest.java b/lib/src/test/java/com/auth0/jwt/impl/ClaimsHolderTest.java index fbdae57..7429937 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/ClaimsHolderTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/ClaimsHolderTest.java @@ -19,14 +19,15 @@ package com.auth0.jwt.impl; -import org.hamcrest.collection.IsMapContaining; -import org.junit.Test; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; import java.util.HashMap; import java.util.Map; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; +import org.hamcrest.collection.IsMapContaining; +import org.junit.Test; public class ClaimsHolderTest { diff --git a/lib/src/test/java/com/auth0/jwt/impl/HeaderDeserializerTest.java b/lib/src/test/java/com/auth0/jwt/impl/HeaderDeserializerTest.java index 63c72a7..ddc009a 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 2e755d6..66f0deb 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/NullClaimTest.java b/lib/src/test/java/com/auth0/jwt/impl/NullClaimTest.java index c7557a7..1de72d3 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/NullClaimTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/NullClaimTest.java @@ -19,13 +19,13 @@ package com.auth0.jwt.impl; -import org.junit.Before; -import org.junit.Test; - import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; +import org.junit.Before; +import org.junit.Test; + public class NullClaimTest { private NullClaim claim; 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..fb641b6 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 b81fc3f..ac054ad 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,29 @@ 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.auth0.jwt.interfaces.constants.Constants; 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 @@ -56,7 +59,7 @@ public void setUp() throws Exception { issuedAt = Mockito.mock(Date.class); Map tree = new HashMap<>(); tree.put("extraClaim", new TextNode("extraValue")); - payload = new PayloadImpl(Collections.singletonList("issuer"), Collections.singletonList("subject"), Collections.singletonList("audience"), expiresAt, notBefore, issuedAt, "jwtId", tree); + payload = new PayloadImpl(Collections.singletonList(Constants.ISSUER), Collections.singletonList(Constants.SUBJECT), Collections.singletonList(Constants.AUDIENCE), expiresAt, notBefore, issuedAt, "jwtId", tree); } @SuppressWarnings("Convert2Diamond") @@ -70,7 +73,7 @@ public void shouldHaveUnmodifiableTree() throws Exception { @Test public void shouldGetIssuer() throws Exception { assertThat(payload, is(notNullValue())); - assertTrue(payload.getIssuer().contains("issuer")); + assertTrue(payload.getIssuer().contains(Constants.ISSUER)); } @Test @@ -83,7 +86,7 @@ public void shouldGetNullIssuerIfMissing() throws Exception { @Test public void shouldGetSubject() throws Exception { assertThat(payload, is(notNullValue())); - assertTrue(payload.getSubject().contains("subject")); + assertTrue(payload.getSubject().contains(Constants.SUBJECT)); } @Test @@ -98,7 +101,7 @@ public void shouldGetAudience() throws Exception { assertThat(payload, is(notNullValue())); assertThat(payload.getAudience(), is(IsCollectionWithSize.hasSize(1))); - assertThat(payload.getAudience(), is(IsCollectionContaining.hasItems("audience"))); + assertThat(payload.getAudience(), is(IsCollectionContaining.hasItems(Constants.AUDIENCE))); } @Test 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..15c91b4 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 { diff --git a/lib/src/test/java/com/auth0/jwt/verification/VerificationAndAssertionTest.java b/lib/src/test/java/com/auth0/jwt/verification/VerificationAndAssertionTest.java index cd611cd..af2ff26 100644 --- a/lib/src/test/java/com/auth0/jwt/verification/VerificationAndAssertionTest.java +++ b/lib/src/test/java/com/auth0/jwt/verification/VerificationAndAssertionTest.java @@ -19,16 +19,17 @@ package com.auth0.jwt.verification; +import static java.util.Arrays.asList; + import com.auth0.jwt.TimeUtil; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.creators.ImplicitJwtCreator; import com.auth0.jwt.exceptions.AlgorithmMismatchException; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; +import com.auth0.jwt.interfaces.constants.Constants; import com.auth0.jwt.jwts.ImplicitJWT; import com.auth0.jwt.jwts.JWT; -import com.auth0.jwt.verification.VerificationAndAssertion; -import static java.util.Arrays.asList; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -58,15 +59,15 @@ public void testAssertNullWithNullString() throws Exception { public void testVerifyAlgorithmWithMismatchingAlgorithms() throws Exception { thrown.expect(AlgorithmMismatchException.class); thrown.expectMessage("The provided Algorithm doesn't match the one defined in the JWT's Header."); - Algorithm algorithm = Algorithm.HMAC256("secret"); + Algorithm algorithm = Algorithm.HMAC256(Constants.SECRET); String token = ImplicitJwtCreator.build() .withIssuer("accounts.fake.com") - .withSubject("subject") - .withAudience("audience") + .withSubject(Constants.SUBJECT) + .withAudience(Constants.AUDIENCE) .withIat(TimeUtil.generateRandomIatDateInPast()) .sign(algorithm); Verification verification = ImplicitJWT.require(Algorithm.none()); - JWT verifier = verification.createVerifierForImplicit(asList("accounts.fake.com"), asList("audience"), 1).build(); + JWT verifier = verification.createVerifierForImplicit(asList("accounts.fake.com"), asList(Constants.AUDIENCE), 1).build(); DecodedJWT jwt = verifier.decode(token); }