From 861c4dad316d202ae59b8f198466f644a00a30de Mon Sep 17 00:00:00 2001 From: Justin Dahmubed Date: Wed, 20 Dec 2017 15:45:22 -0800 Subject: [PATCH 1/7] Oicmsg --- .../DeserializationNotPossible.java | 10 + .../oicmsg_exceptions/HeaderError.java | 7 + .../oicmsg_exceptions/ImportException.java | 7 + .../oicmsg_exceptions/JWKException.java | 11 + .../oicmsg_exceptions/KeyUsage.java | 4 + .../SerializationNotPossible.java | 4 + .../oicmsg_exceptions/TypeError.java | 4 + .../oicmsg_exceptions/UnknownKeyType.java | 7 + .../oicmsg_exceptions/UpdateFailed.java | 7 + .../oicmsg_exceptions/ValueError.java | 4 + .../main/java/com/auth0/jwt/oicmsg/ECKey.java | 195 +++++++ .../main/java/com/auth0/jwt/oicmsg/Key.java | 236 ++++++++ .../java/com/auth0/jwt/oicmsg/KeyBundle.java | 519 ++++++++++++++++++ .../java/com/auth0/jwt/oicmsg/KeyJar.java | 378 +++++++++++++ .../java/com/auth0/jwt/oicmsg/RSAKey.java | 199 +++++++ .../java/com/auth0/jwt/oicmsg/SYMKey.java | 67 +++ 16 files changed, 1659 insertions(+) create mode 100644 lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/DeserializationNotPossible.java create mode 100644 lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/HeaderError.java create mode 100644 lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/ImportException.java create mode 100644 lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/JWKException.java create mode 100644 lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/KeyUsage.java create mode 100644 lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/SerializationNotPossible.java create mode 100644 lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/TypeError.java create mode 100644 lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/UnknownKeyType.java create mode 100644 lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/UpdateFailed.java create mode 100644 lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/ValueError.java create mode 100644 lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java create mode 100644 lib/src/main/java/com/auth0/jwt/oicmsg/Key.java create mode 100644 lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java create mode 100644 lib/src/main/java/com/auth0/jwt/oicmsg/KeyJar.java create mode 100644 lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java create mode 100644 lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java 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..210bcf4 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/DeserializationNotPossible.java @@ -0,0 +1,10 @@ +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..55f2708 --- /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..1b983b1 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/JWKException.java @@ -0,0 +1,11 @@ +package com.auth0.jwt.exceptions.oicmsg_exceptions; + +public class JWKException extends Exception{ + public JWKException(String message) { + + } + + public JWKException() { + + } +} \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/KeyUsage.java b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/KeyUsage.java new file mode 100644 index 0000000..7692a1d --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/KeyUsage.java @@ -0,0 +1,4 @@ +package com.auth0.jwt.exceptions.oicmsg_exceptions; + +public enum KeyUsage { +} \ 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..c54d6c6 --- /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..d9d025c --- /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..2d13263 --- /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/oicmsg/ECKey.java b/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java new file mode 100644 index 0000000..4b745c5 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java @@ -0,0 +1,195 @@ +package com.auth0.jwt.oicmsg; + +import com.auth0.jwt.exceptions.oicmsg_exceptions.HeaderError; +import com.auth0.jwt.exceptions.oicmsg_exceptions.SerializationNotPossible; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.security.spec.EllipticCurve; +import java.text.ParseException; +import java.util.*; + +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); + 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); + } + + 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 new ArrayList<>(Arrays.asList(this.d)); + } else { + return new ArrayList<>(Arrays.asList(this.x, this.y)); + } + } + + 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; + } + + 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) { + 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 Logger getLogger() { + return logger; + } + + 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 Set getPublicMembers() { + return publicMembers; + } + + 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..1de97f7 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java @@ -0,0 +1,236 @@ +package com.auth0.jwt.oicmsg; + +import com.auth0.jwt.exceptions.oicmsg_exceptions.HeaderError; +import com.google.common.primitives.Bytes; +import com.nimbusds.jose.util.Base64; +import org.junit.Assert; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.nio.charset.Charset; +import java.util.*; + +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 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 Set required = new HashSet<>(Arrays.asList("kty")); + + 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 void setInactiveSince(long now) { + this.inactiveSince = now; + } + + public long getInactiveSince() { + return inactiveSince; + } + + public Map toDict() { + Map hmap = serialize(); + for (String key : args.keySet()) { + hmap.put(key, args.get(key)); + } + return hmap; + } + + public List serialize() { + Map hmap = common(); + this.key. + //TODO + } + + public Map common() { + Map args = new HashMap<>(); + args.put("kty", this.kty); + if (this.use != null && !this.use.isEmpty()) { + args.put("use", this.use); + } + if (this.kid != null && !this.kid.isEmpty()) { + args.put("kid", this.kid); + } + if (this.alg != null && !this.alg.isEmpty()) { + args.put("alg", this.alg); + } + return args; + } + + public String toString() { + return this.toDict().toString(); + } + + public Key getKey() { + return this.key; + } + + 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; + } finally { + for(String sign : new ArrayList<>(Arrays.asList("+", "/", "="))) { + if(((String) item).contains(sign)) { + return false; + } + } + } + + if (this.kid != null && !this.kid.isEmpty()) { + 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) { + + } + + 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; + } finally { + return true; + } + } + + public List getKeys() { + return new ArrayList<>(this.toDict().keySet()); + } + + public byte[] thumbprint(String hashFunction, List members); //TODO + + public byte[] thumbprint(String hashFunction) { + thumbprint(hashFunction, null); + } + + public void addKid() { + this.kid = Base64.encode(this.thumbprint("SHA-256")).decodeToString(); + } + + + protected static void deser(Object item) { + 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..b42a638 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java @@ -0,0 +1,519 @@ +package com.auth0.jwt.oicmsg; + +import com.auth0.jwt.exceptions.oicmsg_exceptions.*; +import com.google.common.collect.ImmutableMap; +import com.google.gson.Gson; +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 com.auth0.jwt.oicmsg.*; +import sun.reflect.generics.reflectiveObjects.NotImplementedException; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.security.KeyException; +import java.util.*; + +public class KeyBundle { + + final private static Logger logger = LoggerFactory.getLogger(KeyBundle.class); + private static final Map K2C = + ImmutableMap.of("RSA", new RSAKey(), + "EC", new ECKey(), + "oct", new SYMKey() + ); + private static final Map map = + ImmutableMap.of("dec", "enc", + "enc", "enc", + "ver", "sig", + "sig", "sig" + ); + private 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 long lastUpdated; + + 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 (source.startsWith("file://")) { + this.source = source.substring(7); + } else if (source.startsWith("http://") || source.startsWith("https://")) { + this.source = source; + this.remote = true; + } else if (source.isEmpty()) { + this.source = null; + } else { + if (new HashSet(Arrays.asList("rsa", "der", "jwks")).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.fileFormat.equals("jwks") || this.fileFormat.equals("jwk")) { + 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 String getSource() { + return source; + } + + public KeyBundle() throws ImportException { + this(null, "", 300, true, "jwk", "RSA", 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", null); + } + + public KeyBundle(String source, String fileFormat, List usage) throws ImportException { + this(null, source, 300, true, fileFormat, "RSA", usage); + } + + public void doKeys(List keys) { + for (Key keyIndex : keys) { + final String kty = keyIndex.getKty(); + List usage = harmonizeUsage(keyIndex.getUse()); + keys.remove("use"); + boolean flag = false; + for (String use : usage) { + List types = new ArrayList() {{ + add(kty); + add(kty.toLowerCase()); + add(kty.toUpperCase()); + }}; + boolean isSuccess = true; + Key key; + for (String typeIndex : types) { + try { + switch(typeIndex) { + case "RSA": + key = new RSAKey("use"); + break; + case "EC": + key = new ECKey("use"); + break; + case "SYMKey": + key = new SYMKey("use"); + break; + default: + throw new IllegalArgumentException("Encryption type: " + typeIndex + " isn't supported"); + } + } catch (JWKException exception) { + logger.warn("While loading keys: " + exception); + isSuccess = false; + } + + if (isSuccess) { + this.keys.add(key); + flag = true; + break; + } + } + } + + 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); + } + + 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(); + while (iterator.hasNext()) { + keysList.add(new 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(); + } + } + + public void doLocalDer(String fileName, String keyType, List keyUsage) throws NotImplementedException { + RSAKey rsaKey = rsaLoad(fileName); + + if (!keyType.equalsIgnoreCase("rsa")) { + 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(); + } + + 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; + } + + 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) { + if (System.currentTimeMillis() > this.timeOut) { + if (update()) { + result = true; + } + } + } + } else if (this.remote) { + if (update()) { + result = true; + } + } + + return result; + } + + 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; + } + + long now = System.currentTimeMillis(); + for (Key key : keys) { + if (!keys.contains(key)) { + key.setInactiveSince(); + } else { + key.setInactiveSince(now); + } + this.keys.add(key); + } + } + return result; + } + + 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; + } + } + + public List getKeys() { + this.upToDate(); + return this.keys; + } + + public List getActiveKeys() { + List activeKeys = new ArrayList<>(); + for (Key key : this.keys) { + if (key.getInactiveSince() == 0) { + activeKeys.add(key); + } + } + + return activeKeys; + } + + 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); + } + } + } + + public String toString() { + return this.jwks(); + } + + public String jwks() { + return jwks(false); + } + + 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 void append(Key key) { + this.keys.add(key); + } + + public void remove(Key key) { + this.keys.remove(key); + } + + public int getLength() { + return this.keys.size(); + } + + public Key getKeyWithKid(String kid) { + for (Key key : this.keys) { + if (key.getKid().equals(kid)) { + return key; + } + } + + update(); + + for (Key key : this.keys) { + if (key.getKid().equals(kid)) { + return key; + } + } + + return null; + } + + public List getKids() { + this.upToDate(); + List kids = new ArrayList<>(); + for (Key key : this.keys) { + if (!key.getKid().isEmpty()) { + kids.add(key.getKid()); + } + } + + return kids; + } + + public void markAsInactive(String kid) { + Key key = getKeyWithKid(kid); + key.setInactiveSince(System.currentTimeMillis()); + } + + 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; + } + + + //----Not part of KeyBundle class, but I thought I should include these methods + public KeyBundle keyBundleFromLocalFile(String filename, String type, List usage) throws ImportException, UnknownKeyType { + usage = harmonizeUsage(usage); + KeyBundle keyBundle; + type = type.toLowerCase(); + if (type.equals("jwks")) { + keyBundle = new KeyBundle(filename, "jwks", usage); + } else if (type.equals("der")) { + keyBundle = new KeyBundle(filename, "der", usage); + } else { + throw new UnknownKeyType("Unsupported key type"); + } + + return keyBundle; + } + + 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..1154835 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyJar.java @@ -0,0 +1,378 @@ +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 org.junit.Assert; +import org.slf4j.LoggerFactory; + +import java.security.KeyException; +import java.util.*; +import java.util.logging.Logger; + +public class KeyJar { + + private boolean verifySSL; + private KeyBundle keyBundle; + private float removeAfter; + private Map> issuerKeys; + final private static org.slf4j.Logger logger = LoggerFactory.getLogger(KeyJar.class); + + 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; + } + + public KeyBundle addUrl(String owner, String url, Map args) throws KeyException, ImportException { + if(url == null || url.isEmpty()) { + 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; + } + + 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 = new ArrayList<>(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 = new ArrayList<>(Arrays.asList(key)); + usageList.add(use); + kb = new KeyBundle(keyList, "oct", usageList); + kbList.add(kb); + issuerKeys.put(owner, kbList); + } + } + } + + public void addKeyBundle(String owner, KeyBundle keyBundle) { + List kbList; + if(issuerKeys.get(owner) == null) { + kbList = new ArrayList<>(Arrays.asList(keyBundle)); + issuerKeys.put(owner, kbList); + } else { + kbList = issuerKeys.get(owner); + kbList.add(keyBundle); + issuerKeys.put(owner, kbList); + } + } + + public Collection> getItems() { + return this.issuerKeys.values(); + } + + 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(owner != null && !owner.isEmpty()) { + 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(keyType != null && !keyType.isEmpty()) { + keyList = keyBundle.get(keyType); + } else { + keyList = keyBundle.getKeys(); + } + + for(Key key : keyList) { + if(key.getInactiveSince() == 0 && !keyUse.equals("sig")) { + 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(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; + } + + if(use.equals("enc") && keyType.equals("oct") && owner != null && !owner.isEmpty()) { + for(KeyBundle keyBundle : this.issuerKeys.get("")) { + for(Key key : keyBundle.get(keyType)) { + if(key.getUse() == null || key.getUse() == 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.toLowerCase().equals("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)); + } + + 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")); ?? + } + + public KeyBundle find(String source, String issuer) { + for(KeyBundle keyBundle : this.issuerKeys.get(issuer)) { + if(keyBundle.getSource().equals(source)) { + return keyBundle; + } + } + + return null; + } + + 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); + } + + public void importJwks(Map jwks, String issuer) throws ImportException { + String keys = jwks.get("keys"); + List keyBundleList = this.issuerKeys.get("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(); + } + + 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; + } + + 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..847a72e --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java @@ -0,0 +1,199 @@ +package com.auth0.jwt.oicmsg; + +import com.auth0.jwt.exceptions.oicmsg_exceptions.DeserializationNotPossible; +import com.auth0.jwt.exceptions.oicmsg_exceptions.SerializationNotPossible; +import org.bouncycastle.util.encoders.Base64; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.*; + +public class RSAKey extends Key { + + final private static Logger logger = LoggerFactory.getLogger(RSAKey.class); + 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 String 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); + members.addAll(Arrays.asList("n", "e", "d", "p", "q")); + 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.length() > 0 && 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); + } + + public void deserialize() throws DeserializationNotPossible { + if (this.n != null && this.e != null) { + Object item = null; + 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 = new ArrayList<>(Arrays.asList(this.n, this.e)); + if(this.d != null && !this.d.isEmpty()) { + list.add(this.d); + } + if(this.p != null && !this.p.isEmpty()) { + list.add(this.p); + if(this.q != null && !this.q.isEmpty()) { + 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]); + + if(this.x5t != null) { + if(Base64.decode() != ) + + } + + this.key =; + this.split(); + if(this.x5c.length() > 1) { + + } + } else { + throw new DeserializationNotPossible(); + } + } + + 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 && new ArrayList<>(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; + + try { + this.d = this.key.d; + } catch (AttributeError e) { + + } finally { + Object item = null; + for(String param : new ArrayList<>(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 + } + } + } + } + } + + public RSAKey loadKey(Key key) { + this.key = key; + this.split(); + return key; + } + + public Key encryptionKey() { + if(this.key == null) { + deserialize(); + } + + return this.key; + } + + private String longToBase64(Object item) { + } + + public Map serialize() { + return serialize(false); + } + + private void split() { + + } + +} 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..39ffe14 --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java @@ -0,0 +1,67 @@ +package com.auth0.jwt.oicmsg; + +import com.auth0.jwt.exceptions.oicmsg_exceptions.JWKException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.*; + +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(); + args.put("k", b64e(this.k.getBytes()).asUnicode()); + return args; + } + + 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; + } +} From cea9297b6f1c29a220b8d631519eef3519243b91 Mon Sep 17 00:00:00 2001 From: Justin Dahmubed Date: Wed, 27 Dec 2017 11:30:19 -0800 Subject: [PATCH 2/7] Oicmsg --- lib/build.gradle | 2 + .../main/java/com/auth0/jwt/oicmsg/Key.java | 57 +++++++++++++++-- .../java/com/auth0/jwt/oicmsg/KeyBundle.java | 2 +- .../java/com/auth0/jwt/oicmsg/KeyJar.java | 1 - .../java/com/auth0/jwt/oicmsg/RSAKey.java | 64 ++++++++----------- .../java/com/auth0/jwt/oicmsg/SYMKey.java | 6 +- .../main/java/com/auth0/jwt/oicmsg/Utils.java | 34 ++++++++++ 7 files changed, 121 insertions(+), 45 deletions(-) create mode 100644 lib/src/main/java/com/auth0/jwt/oicmsg/Utils.java 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/oicmsg/Key.java b/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java index 1de97f7..27c965c 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java @@ -2,7 +2,9 @@ import com.auth0.jwt.exceptions.oicmsg_exceptions.HeaderError; import com.google.common.primitives.Bytes; +import com.google.gson.Gson; import com.nimbusds.jose.util.Base64; +import org.bouncycastle.util.encoders.Base64; import org.junit.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -26,7 +28,7 @@ public class Key { 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 Set required = new HashSet<>(Arrays.asList("kty")); + protected static List required = new ArrayList<>(Arrays.asList("kty")); public Key(String kty, String alg, String use, String kid, String x5c, String x5t, String x5u, Key key, Map args) { this.kty = kty; @@ -121,7 +123,7 @@ public Map toDict() { return hmap; } - public List serialize() { + public Key serialize() { Map hmap = common(); this.key. //TODO @@ -164,6 +166,7 @@ public boolean verify() throws HeaderError { } if (item instanceof Bytes) { + //item = item.decode('utf-8') ??? //TODO } @@ -219,18 +222,60 @@ public List getKeys() { return new ArrayList<>(this.toDict().keySet()); } - public byte[] thumbprint(String hashFunction, List members); //TODO + public byte[] thumbprint(String hashFunction, List members) { + 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) { + try { + value = key.getClass().getField(member).toString(); + } catch (NoSuchFieldException e) { + logger.error(e.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); } public void addKid() { - this.kid = Base64.encode(this.thumbprint("SHA-256")).decodeToString(); + this.kid = new String(Base64.encode(this.thumbprint("SHA-256"))); } - protected static void deser(Object item) { + //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 index b42a638..6d82bf0 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java @@ -130,7 +130,7 @@ public KeyBundle(String source, String fileFormat, List usage) throws Im public void doKeys(List keys) { for (Key keyIndex : keys) { final String kty = keyIndex.getKty(); - List usage = harmonizeUsage(keyIndex.getUse()); + List usage = harmonizeUsage(Arrays.asList(keyIndex.getUse())); keys.remove("use"); boolean flag = false; for (String use : usage) { diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/KeyJar.java b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyJar.java index 1154835..f4789ae 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/KeyJar.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyJar.java @@ -4,7 +4,6 @@ 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 org.junit.Assert; import org.slf4j.LoggerFactory; diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java b/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java index 847a72e..5fc5df5 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java @@ -21,7 +21,7 @@ public class RSAKey extends Key { private String dq; private String di; private String qi; - private String key; + 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) { @@ -76,12 +76,12 @@ public void deserialize() throws DeserializationNotPossible { } List list = new ArrayList<>(Arrays.asList(this.n, this.e)); - if(this.d != null && !this.d.isEmpty()) { + if (this.d != null && !this.d.isEmpty()) { list.add(this.d); } - if(this.p != null && !this.p.isEmpty()) { + if (this.p != null && !this.p.isEmpty()) { list.add(this.p); - if(this.q != null && !this.q.isEmpty()) { + if (this.q != null && !this.q.isEmpty()) { list.add(this.q); } this.key = RSA.construct(tuple(list)); //TODO @@ -91,14 +91,14 @@ public void deserialize() throws DeserializationNotPossible { } else if (this.x5c != null) { Base64.decode((int) this.x5c.getBytes()[0]); - if(this.x5t != null) { - if(Base64.decode() != ) + if (this.x5t != null) { + if (Base64.decode() !=) } this.key =; this.split(); - if(this.x5c.length() > 1) { + if (this.x5c.length() > 1) { } } else { @@ -106,8 +106,8 @@ public void deserialize() throws DeserializationNotPossible { } } - public Map serialize(boolean isPrivate) throws SerializationNotPossible { - if(this.key == null) { + public Map serialize(boolean isPrivate) throws SerializationNotPossible { + if (this.key == null) { throw new SerializationNotPossible(); } @@ -115,10 +115,10 @@ public Map serialize(boolean isPrivate) throws SerializationNotPo publicMembers.addAll(longs); List publicLongs = new ArrayList<>(publicMembers); - for(String param : publicLongs) { + for (String param : publicLongs) { try { Object item = this.getClass().getField(param).get(this); - if(item != null) { + if (item != null) { args.put(param, longToBase64(item)); } } catch (Exception e1) { @@ -126,9 +126,9 @@ public Map serialize(boolean isPrivate) throws SerializationNotPo } } - if(isPrivate) { - for(String param : longs) { - if(!isPrivate && new ArrayList<>(Arrays.asList("d", "p", "q", "dp", "dq", "di", + if (isPrivate) { + for (String param : longs) { + if (!isPrivate && new ArrayList<>(Arrays.asList("d", "p", "q", "dp", "dq", "di", "qi")).contains(param)) { continue; } @@ -151,34 +151,31 @@ private void split() { this.n = this.key.n; this.e = this.key.e; - try { - this.d = this.key.d; - } catch (AttributeError e) { - - } finally { - Object item = null; - for(String param : new ArrayList<>(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 - } + this.d = this.key.d; + Object item = null; + for (String param : new ArrayList<>(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 } } } } - public RSAKey loadKey(Key key) { +} + + public RSAKey loadKey(RSAKey key) { this.key = key; this.split(); return key; } public Key encryptionKey() { - if(this.key == null) { + if (this.key == null) { deserialize(); } @@ -191,9 +188,4 @@ private String longToBase64(Object item) { public Map serialize() { return serialize(false); } - - private void split() { - - } - } diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java b/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java index 39ffe14..f788944 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java @@ -1,9 +1,12 @@ package com.auth0.jwt.oicmsg; import com.auth0.jwt.exceptions.oicmsg_exceptions.JWKException; +import org.apache.commons.codec.Charsets; +import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.charset.StandardCharsets; import java.util.*; public class SYMKey extends Key{ @@ -38,7 +41,8 @@ public void deserialize() { public Map serialize(boolean isPrivate) { Map args = common(); - args.put("k", b64e(this.k.getBytes()).asUnicode()); + String k = Utils.urlSafeEncode(this.k); + args.put("k", k); return args; } 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..873cc9f --- /dev/null +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/Utils.java @@ -0,0 +1,34 @@ +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(); + } +} From 50378171be4fcb446388da3f983e234470da2ea4 Mon Sep 17 00:00:00 2001 From: Justin Dahmubed Date: Wed, 24 Jan 2018 11:38:13 -0800 Subject: [PATCH 3/7] Code style changes --- .../main/java/com/auth0/jwt/JWTDecoder.java | 3 - .../com/auth0/jwt/algorithms/Algorithm.java | 16 +- .../auth0/jwt/algorithms/CryptoHelper.java | 9 +- .../auth0/jwt/algorithms/ECDSAAlgorithm.java | 1 - .../auth0/jwt/algorithms/HMACAlgorithm.java | 3 - .../auth0/jwt/creators/AccessJwtCreator.java | 16 +- .../jwt/creators/ExtendedJwtCreator.java | 18 +- .../com/auth0/jwt/creators/FbJwtCreator.java | 16 +- .../auth0/jwt/creators/GoogleJwtCreator.java | 16 +- .../jwt/creators/ImplicitJwtCreator.java | 16 +- .../com/auth0/jwt/creators/JWTCreator.java | 13 +- .../java/com/auth0/jwt/creators/Message.java | 7 +- .../auth0/jwt/creators/RiscJwtCreator.java | 17 +- .../auth0/jwt/creators/ScopedJwtCreator.java | 18 +- .../DeserializationNotPossible.java | 3 +- .../oicmsg_exceptions/HeaderError.java | 2 +- .../oicmsg_exceptions/JWKException.java | 7 +- .../oicmsg_exceptions/KeyUsage.java | 4 - .../SerializationNotPossible.java | 2 +- .../oicmsg_exceptions/UnknownKeyType.java | 2 +- .../oicmsg_exceptions/UpdateFailed.java | 2 +- .../java/com/auth0/jwt/impl/BasicHeader.java | 4 +- .../com/auth0/jwt/impl/JsonNodeClaim.java | 8 +- .../auth0/jwt/impl/PayloadDeserializer.java | 10 +- .../java/com/auth0/jwt/impl/PayloadImpl.java | 10 +- .../jwt/interfaces/GoogleVerification.java | 3 +- .../java/com/auth0/jwt/jwts/AccessJWT.java | 3 + .../java/com/auth0/jwt/jwts/ExtendedJWT.java | 5 +- .../main/java/com/auth0/jwt/jwts/FbJWT.java | 7 +- .../java/com/auth0/jwt/jwts/GoogleJWT.java | 5 +- .../java/com/auth0/jwt/jwts/ImplicitJWT.java | 9 +- lib/src/main/java/com/auth0/jwt/jwts/JWT.java | 16 +- .../main/java/com/auth0/jwt/jwts/RiscJWT.java | 9 +- .../java/com/auth0/jwt/jwts/ScopedJWT.java | 7 +- .../main/java/com/auth0/jwt/oicmsg/ECKey.java | 35 ++-- .../main/java/com/auth0/jwt/oicmsg/Key.java | 23 ++- .../java/com/auth0/jwt/oicmsg/KeyBundle.java | 60 ++++--- .../java/com/auth0/jwt/oicmsg/KeyJar.java | 157 +++++++++--------- .../java/com/auth0/jwt/oicmsg/RSAKey.java | 10 +- .../java/com/auth0/jwt/oicmsg/SYMKey.java | 31 ++-- .../main/java/com/auth0/jwt/oicmsg/Utils.java | 12 +- .../java/oiccli/client_auth/BearerHeader.java | 51 ++++++ .../java/com/auth0/jwt/ClockImplTest.java | 10 +- .../com/auth0/jwt/ConcurrentVerifyTest.java | 10 +- .../java/com/auth0/jwt/JWTDecoderTest.java | 17 +- lib/src/test/java/com/auth0/jwt/JWTTest.java | 15 +- .../test/java/com/auth0/jwt/JsonMatcher.java | 4 +- .../com/auth0/jwt/MainTestSignatures.java | 13 +- lib/src/test/java/com/auth0/jwt/TimeUtil.java | 2 +- .../java/com/auth0/jwt/TokenUtilsTest.java | 9 +- lib/src/test/java/com/auth0/jwt/UserPojo.java | 8 +- .../auth0/jwt/algorithms/AlgorithmTest.java | 19 ++- .../jwt/algorithms/ECDSAAlgorithmTest.java | 137 ++++++++------- .../ECDSABouncyCastleProviderTests.java | 51 ++++-- .../jwt/algorithms/HMACAlgorithmTest.java | 19 ++- .../jwt/algorithms/NoneAlgorithmTest.java | 8 +- .../jwt/algorithms/RSAAlgorithmTest.java | 29 ++-- .../jwt/creators/AccessJwtCreatorTest.java | 12 +- .../jwt/creators/ExtendedJwtCreatorTest.java | 12 +- .../auth0/jwt/creators/FbJwtCreatorTest.java | 10 +- .../jwt/creators/GoogleJwtCreatorTest.java | 26 +-- .../jwt/creators/ImplicitJwtCreatorTest.java | 12 +- .../auth0/jwt/creators/JWTCreatorTest.java | 13 +- .../jwt/creators/RiscJwtCreatorTest.java | 10 +- .../jwt/creators/ScopedJwtCreatorTest.java | 11 +- .../com/auth0/jwt/impl/BasicHeaderTest.java | 9 +- .../com/auth0/jwt/impl/ClaimsHolderTest.java | 8 +- .../jwt/impl/HeaderDeserializerTest.java | 16 +- .../com/auth0/jwt/impl/JWTParserTest.java | 17 +- .../com/auth0/jwt/impl/JsonNodeClaimTest.java | 30 +++- .../com/auth0/jwt/impl/NullClaimTest.java | 6 +- .../jwt/impl/PayloadDeserializerTest.java | 31 ++-- .../com/auth0/jwt/impl/PayloadImplTest.java | 11 +- .../auth0/jwt/impl/PayloadSerializerTest.java | 8 +- .../VerificationAndAssertionTest.java | 4 +- 75 files changed, 765 insertions(+), 498 deletions(-) delete mode 100644 lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/KeyUsage.java create mode 100644 lib/src/main/java/oiccli/client_auth/BearerHeader.java diff --git a/lib/src/main/java/com/auth0/jwt/JWTDecoder.java b/lib/src/main/java/com/auth0/jwt/JWTDecoder.java index 7a967fb..b275fed 100644 --- a/lib/src/main/java/com/auth0/jwt/JWTDecoder.java +++ b/lib/src/main/java/com/auth0/jwt/JWTDecoder.java @@ -20,8 +20,6 @@ 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; @@ -33,7 +31,6 @@ 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; 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..9b64c6b 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/Algorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/Algorithm.java @@ -27,7 +27,12 @@ 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 +401,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..80767ac 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/CryptoHelper.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/CryptoHelper.java @@ -21,7 +21,14 @@ import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; -import java.security.*; + +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; 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..b7f294a 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java @@ -27,7 +27,6 @@ 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; 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..05fe0fa 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/HMACAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/HMACAlgorithm.java @@ -20,7 +20,6 @@ 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; @@ -28,11 +27,9 @@ 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; 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..274b7ab 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java @@ -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..624439d 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ExtendedJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ExtendedJwtCreator.java @@ -27,7 +27,7 @@ /** * 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 +53,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 +72,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 +91,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 +103,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..ce3f546 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/FbJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/FbJwtCreator.java @@ -186,8 +186,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 +214,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 +232,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 +250,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 +260,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..70c1747 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/GoogleJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/GoogleJwtCreator.java @@ -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..91cd16f 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ImplicitJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ImplicitJwtCreator.java @@ -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..93da9e8 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java @@ -29,14 +29,11 @@ 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; @@ -346,14 +343,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 +360,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 +419,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..9ffa7c2 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/Message.java +++ b/lib/src/main/java/com/auth0/jwt/creators/Message.java @@ -40,12 +40,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..2de8dd2 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/RiscJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/RiscJwtCreator.java @@ -22,7 +22,6 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; import com.auth0.jwt.impl.PublicClaims; -import com.auth0.jwt.interfaces.Verification; import com.auth0.jwt.jwts.JWT; import java.util.Date; @@ -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..6ae9e37 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ScopedJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ScopedJwtCreator.java @@ -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; @@ -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 index 210bcf4..66bfeba 100644 --- 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 @@ -1,9 +1,10 @@ package com.auth0.jwt.exceptions.oicmsg_exceptions; -public class DeserializationNotPossible extends JWKException{ +public class DeserializationNotPossible extends JWKException { public DeserializationNotPossible(String message) { super(message); } + public DeserializationNotPossible() { super(); } 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 index 55f2708..4fe7a97 100644 --- 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 @@ -1,6 +1,6 @@ package com.auth0.jwt.exceptions.oicmsg_exceptions; -public class HeaderError extends Exception{ +public class HeaderError extends Exception { public HeaderError(String message) { super(message); } 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 index 1b983b1..8cba426 100644 --- 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 @@ -1,11 +1,12 @@ package com.auth0.jwt.exceptions.oicmsg_exceptions; -public class JWKException extends Exception{ - public JWKException(String message) { +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/KeyUsage.java b/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/KeyUsage.java deleted file mode 100644 index 7692a1d..0000000 --- a/lib/src/main/java/com/auth0/jwt/exceptions/oicmsg_exceptions/KeyUsage.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.auth0.jwt.exceptions.oicmsg_exceptions; - -public enum KeyUsage { -} \ 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 index c54d6c6..676da1f 100644 --- 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 @@ -1,4 +1,4 @@ package com.auth0.jwt.exceptions.oicmsg_exceptions; -public class SerializationNotPossible extends Throwable{ +public class SerializationNotPossible extends Throwable { } \ 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 index d9d025c..1d9c714 100644 --- 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 @@ -1,6 +1,6 @@ package com.auth0.jwt.exceptions.oicmsg_exceptions; -public class UnknownKeyType extends Exception{ +public class UnknownKeyType extends Exception { public UnknownKeyType(String message) { super(message); } 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 index 2d13263..9d1fa27 100644 --- 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 @@ -1,6 +1,6 @@ package com.auth0.jwt.exceptions.oicmsg_exceptions; -public class UpdateFailed extends Exception{ +public class UpdateFailed extends Exception { public UpdateFailed(String message) { super(message); } 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..398bae6 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/BasicHeader.java +++ b/lib/src/main/java/com/auth0/jwt/impl/BasicHeader.java @@ -19,6 +19,8 @@ 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; @@ -27,8 +29,6 @@ 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/JsonNodeClaim.java b/lib/src/main/java/com/auth0/jwt/impl/JsonNodeClaim.java index 9b41403..e5d2515 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/JsonNodeClaim.java +++ b/lib/src/main/java/com/auth0/jwt/impl/JsonNodeClaim.java @@ -87,7 +87,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 +106,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/PayloadDeserializer.java b/lib/src/main/java/com/auth0/jwt/impl/PayloadDeserializer.java index babc935..e3c7e84 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/PayloadDeserializer.java +++ b/lib/src/main/java/com/auth0/jwt/impl/PayloadDeserializer.java @@ -30,7 +30,11 @@ 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..ef01cb7 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,17 @@ package com.auth0.jwt.impl; +import static com.auth0.jwt.impl.JsonNodeClaim.extractClaim; + import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.Payload; import com.fasterxml.jackson.databind.JsonNode; -import java.util.*; - -import static com.auth0.jwt.impl.JsonNodeClaim.extractClaim; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * The PayloadImpl class implements the Payload interface. diff --git a/lib/src/main/java/com/auth0/jwt/interfaces/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/jwts/AccessJWT.java b/lib/src/main/java/com/auth0/jwt/jwts/AccessJWT.java index aa58cee..046f328 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/AccessJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/AccessJWT.java @@ -34,12 +34,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 +87,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..d918715 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/ExtendedJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/ExtendedJWT.java @@ -25,15 +25,16 @@ 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..2e71be4 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java @@ -27,7 +27,7 @@ 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()])) @@ -128,6 +130,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/ImplicitJWT.java b/lib/src/main/java/com/auth0/jwt/jwts/ImplicitJWT.java index 91eb070..708e240 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/ImplicitJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/ImplicitJWT.java @@ -26,7 +26,7 @@ import java.util.List; -public class ImplicitJWT extends JWT.BaseVerification implements Verification{ +public class ImplicitJWT extends JWT.BaseVerification implements Verification { ImplicitJWT(Algorithm algorithm) throws IllegalArgumentException { super(algorithm); @@ -34,13 +34,15 @@ public class ImplicitJWT extends JWT.BaseVerification implements Verification{ /** * Create Verification object for verification purposes - * @issuer scope + * * @param issuer * @param audience * @return + * @issuer scope */ + @Override public Verification createVerifierForImplicit(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 +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/JWT.java b/lib/src/main/java/com/auth0/jwt/jwts/JWT.java index 4557a67..0c61895 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,26 @@ 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.creators.EncodeType; +import com.auth0.jwt.creators.JWTCreator; +import com.auth0.jwt.exceptions.AlgorithmMismatchException; +import com.auth0.jwt.exceptions.InvalidClaimException; +import com.auth0.jwt.exceptions.SignatureVerificationException; +import com.auth0.jwt.exceptions.TokenExpiredException; import com.auth0.jwt.impl.PublicClaims; import com.auth0.jwt.interfaces.Clock; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; import com.auth0.jwt.verification.VerificationAndAssertion; -import java.util.*; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @SuppressWarnings("WeakerAccess") public class JWT { 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..915182e 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/RiscJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/RiscJWT.java @@ -34,6 +34,7 @@ public class RiscJWT extends JWT.BaseVerification implements Verification { /** * Create Verification object for verification purposes + * * @param jti * @param issuer * @param audience @@ -41,19 +42,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 +101,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..9622272 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/ScopedJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/ScopedJWT.java @@ -26,7 +26,7 @@ import java.util.List; -public class ScopedJWT extends JWT.BaseVerification implements Verification{ +public class ScopedJWT extends JWT.BaseVerification 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()])) @@ -95,6 +97,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/oicmsg/ECKey.java b/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java index 4b745c5..c5d9ce8 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java @@ -7,9 +7,14 @@ import java.security.spec.EllipticCurve; import java.text.ParseException; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; -public class ECKey extends Key{ +public class ECKey extends Key { private String crv; private Object x; @@ -24,7 +29,7 @@ public class ECKey extends Key{ 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) { + Object curve, Map args) { super(kty, alg, use, kid, "", "", "", key, args); this.crv = crv; this.x = x; @@ -32,14 +37,14 @@ public ECKey(String kty, String alg, String use, String kid, Key key, String crv this.d = d; this.curve = curve; - if(this.crv != null && this.curve == null) { + 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)) { + } else if (this.getKey() != null && (this.crv == null && this.curve == null)) { this.loadKey(key); } } @@ -50,10 +55,10 @@ public ECKey() { public void deserialize() { try { - if(!(this.x instanceof Number)) { + if (!(this.x instanceof Number)) { this.x = deser(this.x); } - if(!(this.y instanceof Number)) { + if (!(this.y instanceof Number)) { this.y = deser(this.y); } } catch (ParseException e) { @@ -61,25 +66,25 @@ public void deserialize() { } this.curve = byName(this.crv); - if(this.d != null) { - if(this.d instanceof String) { + if (this.d != null) { + if (this.d instanceof String) { this.d = deser(this.d); } } } private EllipticCurve byName(String name) { - if(name.equals("P-256")) { + if (name.equals("P-256")) { return EllipticCurve(); - } else if(name.equals("P-384")) { + } else if (name.equals("P-384")) { return EllipticCurve(); - } else if(name.equals("P-521")) { + } else if (name.equals("P-521")) { return EllipticCurve(); } } public List getKey(boolean isPrivate) { - if(isPrivate) { + if (isPrivate) { return new ArrayList<>(Arrays.asList(this.d)); } else { return new ArrayList<>(Arrays.asList(this.x, this.y)); @@ -87,7 +92,7 @@ public List getKey(boolean isPrivate) { } public Object serialize(boolean isPrivate) throws SerializationNotPossible { - if(this.crv == null && this.curve == null) { + if (this.crv == null && this.curve == null) { throw new SerializationNotPossible(); } @@ -96,7 +101,7 @@ public Object serialize(boolean isPrivate) throws SerializationNotPossible { args.put("x", longToBase64(this.x)); args.put("y", longToBase64(this.y)); - if(isPrivate && this.d != null) { + if (isPrivate && this.d != null) { args.put("d", longToBase64(this.d)); } diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java b/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java index 27c965c..7e78c00 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java @@ -3,14 +3,19 @@ import com.auth0.jwt.exceptions.oicmsg_exceptions.HeaderError; import com.google.common.primitives.Bytes; import com.google.gson.Gson; -import com.nimbusds.jose.util.Base64; import org.bouncycastle.util.encoders.Base64; import org.junit.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.nio.charset.Charset; -import java.util.*; +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; public class Key { @@ -144,6 +149,7 @@ public Map common() { return args; } + @Override public String toString() { return this.toDict().toString(); } @@ -176,8 +182,8 @@ public boolean verify() throws HeaderError { } catch (Exception e) { return false; } finally { - for(String sign : new ArrayList<>(Arrays.asList("+", "/", "="))) { - if(((String) item).contains(sign)) { + for (String sign : new ArrayList<>(Arrays.asList("+", "/", "="))) { + if (((String) item).contains(sign)) { return false; } } @@ -199,6 +205,7 @@ private void base64URLToLong(Object item) { } + @Override public boolean equals(Object other) { try { Assert.assertTrue(other instanceof Key); @@ -223,15 +230,15 @@ public List getKeys() { } public byte[] thumbprint(String hashFunction, List members) { - if(members == null || members.isEmpty()) { + 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) { + Map hmap = new HashMap<>(); + for (String member : members) { try { value = key.getClass().getField(member).toString(); } catch (NoSuchFieldException e) { diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java index 6d82bf0..9577bf1 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java @@ -1,6 +1,11 @@ package com.auth0.jwt.oicmsg; -import com.auth0.jwt.exceptions.oicmsg_exceptions.*; +import com.auth0.jwt.exceptions.oicmsg_exceptions.ImportException; +import com.auth0.jwt.exceptions.oicmsg_exceptions.JWKException; +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 org.apache.http.Header; @@ -15,14 +20,19 @@ import org.json.simple.parser.ParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.auth0.jwt.oicmsg.*; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.security.KeyException; -import java.util.*; +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; public class KeyBundle { @@ -38,8 +48,9 @@ public class KeyBundle { "ver", "sig", "sig", "sig" ); - private List keys; - private Map> impJwks; + 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; @@ -49,6 +60,9 @@ public class KeyBundle { 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 long lastUpdated; public KeyBundle(List keys, String source, long cacheTime, boolean verifySSL, @@ -69,15 +83,15 @@ public KeyBundle(List keys, String source, long cacheTime, boolean verifySS this.source = null; //doKeys(this.keys); why is this here? } else { - if (source.startsWith("file://")) { + if ("file://".startsWith(source)) { this.source = source.substring(7); - } else if (source.startsWith("http://") || source.startsWith("https://")) { + } else if ("http://".startsWith(source) || "https://".startsWith(source)) { this.source = source; this.remote = true; - } else if (source.isEmpty()) { + } else if (!Strings.isNullOrEmpty(source)) { this.source = null; } else { - if (new HashSet(Arrays.asList("rsa", "der", "jwks")).contains(fileFormat.toLowerCase())) { + if (fileTypes.contains(fileFormat.toLowerCase())) { File file = new File(source); if (file.exists() && file.isFile()) { this.source = source; @@ -90,7 +104,7 @@ public KeyBundle(List keys, String source, long cacheTime, boolean verifySS } if (!this.remote) { - if (this.fileFormat.equals("jwks") || this.fileFormat.equals("jwk")) { + if (this.JWKS.equals(fileFormat) || this.JWK.equals(fileFormat)) { try { this.doLocalJwk(this.source); } catch (UpdateFailed updateFailed) { @@ -143,7 +157,7 @@ public void doKeys(List keys) { Key key; for (String typeIndex : types) { try { - switch(typeIndex) { + switch (typeIndex) { case "RSA": key = new RSAKey("use"); break; @@ -156,15 +170,11 @@ public void doKeys(List keys) { default: throw new IllegalArgumentException("Encryption type: " + typeIndex + " isn't supported"); } - } catch (JWKException exception) { - logger.warn("While loading keys: " + exception); - isSuccess = false; - } - - if (isSuccess) { this.keys.add(key); flag = true; break; + } catch (JWKException exception) { + logger.warn("While loading keys: " + exception); } } } @@ -195,8 +205,9 @@ public void doLocalJwk(String fileName) throws UpdateFailed { JSONArray keys = (JSONArray) jsonObject.get("keys"); Iterator iterator = keys.iterator(); List keysList = new ArrayList(); + Gson gson = new Gson(); while (iterator.hasNext()) { - keysList.add(new Gson().fromJson(iterator.next(), Key.class)); + keysList.add(gson.fromJson(iterator.next(), Key.class)); } doKeys(keysList); } catch (Exception e) { @@ -353,9 +364,9 @@ public boolean update() { long now = System.currentTimeMillis(); for (Key key : keys) { if (!keys.contains(key)) { - key.setInactiveSince(); - } else { - key.setInactiveSince(now); + if (key.getInactiveSince() == Long.MIN_VALUE) { + key.setInactiveSince(now); + } } this.keys.add(key); } @@ -407,6 +418,7 @@ public void removeKeysByType(String typ) { } } + @Override public String toString() { return this.jwks(); } @@ -500,9 +512,9 @@ public KeyBundle keyBundleFromLocalFile(String filename, String type, List> issuerKeys; + private Map> issuerKeys; final private static org.slf4j.Logger logger = LoggerFactory.getLogger(KeyJar.class); public KeyJar(boolean verifySSL, KeyBundle keyBundle, int removeAfter) { @@ -31,13 +36,13 @@ public KeyJar() throws ImportException { this.removeAfter = 3600; } - public KeyBundle addUrl(String owner, String url, Map args) throws KeyException, ImportException { - if(url == null || url.isEmpty()) { + 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/")) { + if (url.contains("/localhost:") || url.contains("/localhost/")) { keyBundle = new KeyBundle(url, false); } else { keyBundle = new KeyBundle(url, verifySSL); @@ -49,12 +54,12 @@ public KeyBundle addUrl(String owner, String url, Map args) throw } public void addSymmetricKey(String owner, Key key, List usage) throws ImportException { - if(!issuerKeys.containsKey(owner)) { + if (!issuerKeys.containsKey(owner)) { issuerKeys.put(owner, new ArrayList()); } Key key = b64e(key.toString().getBytes()); - if(usage == null || usage.isEmpty()) { + if (usage == null || usage.isEmpty()) { List kbList = new ArrayList<>(); List keyList = new ArrayList<>(Arrays.asList(key)); KeyBundle kb = new KeyBundle(keyList, "oct"); @@ -65,7 +70,7 @@ public void addSymmetricKey(String owner, Key key, List usage) throws Im List keyList; KeyBundle kb; List usageList = new ArrayList<>(); - for(String use : usage) { + for (String use : usage) { kbList = issuerKeys.get(owner); keyList = new ArrayList<>(Arrays.asList(key)); usageList.add(use); @@ -78,7 +83,7 @@ public void addSymmetricKey(String owner, Key key, List usage) throws Im public void addKeyBundle(String owner, KeyBundle keyBundle) { List kbList; - if(issuerKeys.get(owner) == null) { + if (issuerKeys.get(owner) == null) { kbList = new ArrayList<>(Arrays.asList(keyBundle)); issuerKeys.put(owner, kbList); } else { @@ -92,49 +97,49 @@ public Collection> getItems() { return this.issuerKeys.values(); } - public List getKeys(String keyUse, String keyType, String owner, String kid, Map args) { + public List getKeys(String keyUse, String keyType, String owner, String kid, Map args) { String use; - if(keyUse.equals("dec") || keyUse.equals("enc")) { + if (keyUse.equals("dec") || keyUse.equals("enc")) { use = "enc"; } else { use = "sig"; } List keyBundleList = null; - if(owner != null && !owner.isEmpty()) { + 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)); + if (keyBundleList == null) { + if (owner.endsWith("/")) { + keyBundleList = this.issuerKeys.get(owner.substring(0, owner.length() - 1)); } else { - keyBundleList = this.issuerKeys.get(owner+"/"); + keyBundleList = this.issuerKeys.get(owner + "/"); } } } else { keyBundleList = this.issuerKeys.get(owner); } - if(keyBundleList == null) { + if (keyBundleList == null) { return new ArrayList<>(); } List keyListReturned = new ArrayList<>(); List keyList = new ArrayList<>(); - for(KeyBundle keyBundle : keyBundleList) { - if(keyType != null && !keyType.isEmpty()) { + for (KeyBundle keyBundle : keyBundleList) { + if (!Strings.isNullOrEmpty(keyType)) { keyList = keyBundle.get(keyType); } else { keyList = keyBundle.getKeys(); } - for(Key key : keyList) { - if(key.getInactiveSince() == 0 && !keyUse.equals("sig")) { + for (Key key : keyList) { + if (key.getInactiveSince() == 0 && !"sig".equals(keyUse)) { continue; } - if(key.getUse() != null || use.equals(key.getUse())) { - if(kid != null) { - if(key.getKid().equals(kid)) { + if (key.getUse() != null || use.equals(key.getUse())) { + if (kid != null) { + if (key.getKid().equals(kid)) { keyListReturned.add(key); break; } @@ -146,10 +151,10 @@ public List getKeys(String keyUse, String keyType, String owner, String kid } String name; - if(keyType.equals("EC") && args.containsKey("alg")) { + if (keyType.equals("EC") && args.containsKey("alg")) { name = "P-{}" + args.get("alg").substring(2); List tempKeyList = new ArrayList<>(); - for(Key key : keyList) { + for (Key key : keyList) { try { Assert.assertTrue(name.equals(((ECKey) key).getCrv())); } catch (AssertionError error) { @@ -161,10 +166,10 @@ public List getKeys(String keyUse, String keyType, String owner, String kid keyList = tempKeyList; } - if(use.equals("enc") && keyType.equals("oct") && owner != null && !owner.isEmpty()) { - for(KeyBundle keyBundle : this.issuerKeys.get("")) { - for(Key key : keyBundle.get(keyType)) { - if(key.getUse() == null || key.getUse() == use) { + 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); } } @@ -174,25 +179,25 @@ public List getKeys(String keyUse, String keyType, String owner, String kid return keyList; } - public List getSigningKey(String keyType, String owner, String kid, Map args) { + 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) { + 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) { + 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) { + 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")) { + if (usage.equals("sig") || usage.equals("ver")) { keyType = algorithmToKeytypeForJWS(algorithm); } else { keyType = algorithmToKeytypeForJWE(algorithm); @@ -203,20 +208,20 @@ public List keysByAlgAndUsage(String issuer, String algorithm, String usage public List getIssuerKeys(String issuer) { List keyList = new ArrayList<>(); - for(KeyBundle keyBundle : this.issuerKeys.get(issuer)) { + for (KeyBundle keyBundle : this.issuerKeys.get(issuer)) { keyList.addAll(keyBundle.getKeys()); } return keyList; } private String algorithmToKeytypeForJWS(String algorithm) { - if(algorithm == null || algorithm.toLowerCase().equals("none")) { + if (algorithm == null || algorithm.equalsIgnoreCase("none")) { return "none"; - } else if(algorithm.startsWith("RS") || algorithm.startsWith("PS")) { + } else if (algorithm.startsWith("RS") || algorithm.startsWith("PS")) { return "RSA"; - } else if(algorithm.startsWith("HS") || algorithm.startsWith("A")) { + } else if (algorithm.startsWith("HS") || algorithm.startsWith("A")) { return "oct"; - } else if(algorithm.startsWith("ES") || algorithm.startsWith("ECDH-ES")) { + } else if (algorithm.startsWith("ES") || algorithm.startsWith("ECDH-ES")) { return "EC"; } else { return null; @@ -224,11 +229,11 @@ private String algorithmToKeytypeForJWS(String algorithm) { } private String algorithmToKeytypeForJWE(String algorithm) { - if(algorithm.startsWith("RSA")) { + if (algorithm.startsWith("RSA")) { return "RSA"; - } else if(algorithm.startsWith("A")) { + } else if (algorithm.startsWith("A")) { return "oct"; - } else if(algorithm.startsWith("ECDH")) { + } else if (algorithm.startsWith("ECDH")) { return "EC"; } else { return null; @@ -236,8 +241,8 @@ private String algorithmToKeytypeForJWE(String algorithm) { } public String matchOwner(String url) throws KeyException { - for(String key : this.issuerKeys.keySet()) { - if(url.startsWith(key)) { + for (String key : this.issuerKeys.keySet()) { + if (url.startsWith(key)) { return key; } } @@ -245,10 +250,10 @@ public String matchOwner(String url) throws KeyException { throw new KeyException(String.format("No keys for %s", url)); } - public void loadKeys(Map pcr, String issuer, boolean shouldReplace) { + public void loadKeys(Map pcr, String issuer, boolean shouldReplace) { logger.debug("loading keys for issuer: " + issuer); - if(shouldReplace || !this.issuerKeys.keySet().contains(issuer)) { + if (shouldReplace || !this.issuerKeys.keySet().contains(issuer)) { this.issuerKeys.put(issuer, new ArrayList()); } @@ -256,8 +261,8 @@ public void loadKeys(Map pcr, String issuer, boolean shouldReplac } public KeyBundle find(String source, String issuer) { - for(KeyBundle keyBundle : this.issuerKeys.get(issuer)) { - if(keyBundle.getSource().equals(source)) { + for (KeyBundle keyBundle : this.issuerKeys.get(issuer)) { + if (keyBundle.getSource().equals(source)) { return keyBundle; } } @@ -265,29 +270,29 @@ public KeyBundle find(String source, String issuer) { return null; } - public Map> exportsJwks(boolean isPrivate, String issuer) { + 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) { + for (KeyBundle keyBundle : this.issuerKeys.get(issuer)) { + for (Key key : keyBundle.getKeys()) { + if (key.getInactiveSince() == 0) { keys.addAll(key.serialize()); } } } - Map> keysMap = new HashMap<>(); + Map> keysMap = new HashMap<>(); keysMap.put("keys", keys); return keysMap; } - public Map> exportJwksAsJson(boolean isPrivate, String issuer) { + public Map> exportJwksAsJson(boolean isPrivate, String issuer) { return this.exportsJwks(isPrivate, issuer); } - public void importJwks(Map jwks, String issuer) throws ImportException { + public void importJwks(Map jwks, String issuer) throws ImportException { String keys = jwks.get("keys"); List keyBundleList = this.issuerKeys.get("issuer"); - if(keyBundleList == null) { + if (keyBundleList == null) { keyBundleList = new ArrayList<>(); } @@ -301,16 +306,16 @@ public void importJwksAsJson(String js, String issuer) { public void removeOutdated(int when) throws TypeError { List keyBundleList; - for(String owner : this.issuerKeys.keySet()) { + for (String owner : this.issuerKeys.keySet()) { keyBundleList = new ArrayList<>(); - for(KeyBundle keyBundle : this.issuerKeys.get(owner)) { + for (KeyBundle keyBundle : this.issuerKeys.get(owner)) { keyBundle.removeOutdated(this.removeAfter, when); - if(keyBundle.getLength() > 0) { + if (keyBundle.getLength() > 0) { keyBundleList.add(keyBundle); } } - if(keyBundleList.size() > 0) { + if (keyBundleList.size() > 0) { this.issuerKeys.put(owner, keyBundleList); } else { this.issuerKeys.remove(owner); @@ -319,34 +324,34 @@ public void removeOutdated(int when) throws TypeError { } public List addKey(List keys, String owner, String use, String keyType, String kid, - Map> noKidIssuer) { - if(!this.issuerKeys.keySet().contains(owner)) { + 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)) { + 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) { + if (keyList.size() == 0) { return keys; - } else if(keyList.size() == 1) { - if(!keys.contains(keyList.get(0))) { + } else if (keyList.size() == 1) { + if (!keys.contains(keyList.get(0))) { keys.add(keyList.get(0)); } - } else if(noKidIssuer != null) { + } else if (noKidIssuer != null) { List allowedKids = noKidIssuer.get(owner); - if(allowedKids != null) { - for(Key key : keyList) { - if(allowedKids.contains(key.getKid())) { + if (allowedKids != null) { + for (Key key : keyList) { + if (allowedKids.contains(key.getKid())) { keys.add(key); } } @@ -358,7 +363,7 @@ public List addKey(List keys, String owner, String use, String keyType return keys; } - public void getJwtVerifyKeys(JWT jwt, Map args) { + public void getJwtVerifyKeys(JWT jwt, Map args) { List keyList = new ArrayList<>(); JWTParser converter = new JWTParser(); String keyType = algorithmToKeytypeForJWS(converter.parseHeader(jwttoString().getHeader().getAlgorithm().getName()); @@ -369,7 +374,7 @@ public void getJwtVerifyKeys(JWT jwt, Map args) { public KeyJar copy() throws ImportException { KeyJar keyJar = new KeyJar(); - for(String owner : this.issuerKeys.keySet()) { + 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 index 5fc5df5..e456613 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java @@ -6,7 +6,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; public class RSAKey extends Key { @@ -39,7 +44,7 @@ public RSAKey(String kty, String alg, String use, String kid, String x5c, String this.di = di; this.qi = qi; - boolean hasPublicKeyParts = this.n.length() > 0 && this.n.length() == this.e.length(); + boolean hasPublicKeyParts = !this.n.isEmpty() && this.n.length() == this.e.length(); boolean hasX509CertChain = this.getX5c().length() > 0; if (this.getKey() == null && (hasPublicKeyParts || hasX509CertChain)) { @@ -185,6 +190,7 @@ public Key encryptionKey() { 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 index f788944..f1cb4a0 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java @@ -1,22 +1,23 @@ package com.auth0.jwt.oicmsg; import com.auth0.jwt.exceptions.oicmsg_exceptions.JWKException; -import org.apache.commons.codec.Charsets; -import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; -public class SYMKey extends Key{ +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(){{ + private static Map alg2Keylen = new HashMap() {{ put("A128KW", 16); put("A192KW", 24); put("A256KW", 32); @@ -26,11 +27,11 @@ public class SYMKey extends Key{ }}; public SYMKey(String kty, String alg, String use, String kid, Key key, String x5c, - String x5t, String x5u, String k, Map args) { + 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) { + if (this.key == null) { this.key = b64d(this.k.getBytes()); } } @@ -39,27 +40,27 @@ public void deserialize() { this.key = b64d(this.k.getBytes()); } - public Map serialize(boolean isPrivate) { - Map args = common(); + public Map serialize(boolean isPrivate) { + Map args = common(); String k = Utils.urlSafeEncode(this.k); args.put("k", k); return args; } public String encryptionKey(String alg) throws JWKException { - if(this.key == null) { + if (this.key == null) { deserialize(); } int size = alg2Keylen.get(alg); String encryptedKey; - if(size <= 32) { - encryptedKey = sha256_digest(this.key).substring(0,size); + if (size <= 32) { + encryptedKey = sha256_digest(this.key).substring(0, size); } else if (size <= 48) { - encryptedKey = sha384_digest(this.key).substring(0,size); + encryptedKey = sha384_digest(this.key).substring(0, size); } else if (size <= 64) { - encryptedKey = sha512_digest(this.key).substring(0,size); + encryptedKey = sha512_digest(this.key).substring(0, size); } else { throw new JWKException("No support for symmetric keys > 512 bits"); } diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/Utils.java b/lib/src/main/java/com/auth0/jwt/oicmsg/Utils.java index 873cc9f..aa1e92f 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/Utils.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/Utils.java @@ -7,8 +7,10 @@ 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) == '=') { + for (int i = sb.length() - 1; + i >= 0; + i--) { + if (sb.charAt(i) == '=') { sb.deleteCharAt(i); } else { break; @@ -21,8 +23,10 @@ public static String urlSafeEncode(String value) { 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) == '=') { + for (int i = sb.length() - 1; + i >= 0; + i--) { + if (sb.charAt(i) == '=') { sb.deleteCharAt(i); } else { break; diff --git a/lib/src/main/java/oiccli/client_auth/BearerHeader.java b/lib/src/main/java/oiccli/client_auth/BearerHeader.java new file mode 100644 index 0000000..fa84c1d --- /dev/null +++ b/lib/src/main/java/oiccli/client_auth/BearerHeader.java @@ -0,0 +1,51 @@ +package oiccli.client_auth; + +import oiccli.client_info.ClientInfo; + +import java.util.HashMap; +import java.util.Map; + +public class BearerHeader { + + public Map> construct(Map cis, ClientInfo clientInfo, Map requestArgs, Map> httpArgs, + Map args) { + String accessToken; + if (cis != null) { + if (cis.containsKey("accessToken")) { + accessToken = cis.get("accessToken"); + cis.remove(accessToken); + //cis.c_param["access_token"] = SINGLE_OPTIONAL_STRING + } else { + accessToken = requestArgs.get("accessToken"); + requestArgs.remove(accessToken); + + if (accessToken != null) { + accessToken = args.get("accessToken"); + if (accessToken == null) { + accessToken = clientInfo.getStateDb().getTokenInfo(args).get("accessToken"); + } + } + } + } else { + accessToken = args.get("accessToken"); + if (accessToken == null) { + } + } + + String bearer = "Bearer " + accessToken; + if (httpArgs == null) { + Map hMap = new HashMap<>(); + hMap.put("Authorization", bearer); + httpArgs.put("headers", hMap); + } else { + Map hMap = httpArgs.get("headers"); + if (hMap == null) { + hMap = new HashMap<>(); + } + hMap.put("Authorization", bearer); + httpArgs.put("headers", hMap); + } + + return httpArgs; + } +} diff --git a/lib/src/test/java/com/auth0/jwt/ClockImplTest.java b/lib/src/test/java/com/auth0/jwt/ClockImplTest.java index 6fdb01b..d6f39f1 100644 --- a/lib/src/test/java/com/auth0/jwt/ClockImplTest.java +++ b/lib/src/test/java/com/auth0/jwt/ClockImplTest.java @@ -19,19 +19,19 @@ package com.auth0.jwt; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + 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.*; - 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..380cfdc 100644 --- a/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java +++ b/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java @@ -19,6 +19,8 @@ package com.auth0.jwt; +import static com.auth0.jwt.PemUtils.readPublicKeyFromFile; + import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.jwts.JWT; @@ -33,9 +35,11 @@ import java.security.interfaces.RSAKey; import java.util.Collections; import java.util.List; -import java.util.concurrent.*; - -import static com.auth0.jwt.PemUtils.readPublicKeyFromFile; +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; //@Ignore("Skipping concurrency tests") public class ConcurrentVerifyTest { diff --git a/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java b/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java index 8ff3844..4e740b9 100644 --- a/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java +++ b/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java @@ -19,6 +19,15 @@ 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; @@ -28,7 +37,6 @@ 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; @@ -37,9 +45,6 @@ import java.util.Date; import java.util.Map; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; - public class JWTDecoderTest { @Rule @@ -340,7 +345,7 @@ public void shouldGetAvailableClaims() throws Exception { JWT jwt = JWT.require(Algorithm.HMAC256("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,7 +360,7 @@ 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(); diff --git a/lib/src/test/java/com/auth0/jwt/JWTTest.java b/lib/src/test/java/com/auth0/jwt/JWTTest.java index b368d43..d057b5a 100644 --- a/lib/src/test/java/com/auth0/jwt/JWTTest.java +++ b/lib/src/test/java/com/auth0/jwt/JWTTest.java @@ -20,26 +20,13 @@ 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 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 +57,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..c322da4 100644 --- a/lib/src/test/java/com/auth0/jwt/JsonMatcher.java +++ b/lib/src/test/java/com/auth0/jwt/JsonMatcher.java @@ -112,7 +112,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..567673f 100644 --- a/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java +++ b/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java @@ -21,6 +21,9 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static java.util.Arrays.asList; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.creators.GoogleJwtCreator; import com.auth0.jwt.creators.GoogleJwtCreatorTest; @@ -31,8 +34,6 @@ import com.auth0.jwt.interfaces.GoogleVerification; import com.auth0.jwt.jwts.GoogleJWT; import com.auth0.jwt.jwts.JWT; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertTrue; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -58,7 +59,7 @@ public void testComplainOnNone() throws Exception { .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(); + GoogleJwtCreatorTest.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -79,8 +80,8 @@ public void testVerifyingWithEmptyKey() throws Exception { .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(GoogleJwtCreatorTest.PICTURE, GoogleJwtCreatorTest.EMAIL, asList("accounts.fake.com"), asList("audience"), + GoogleJwtCreatorTest.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -101,7 +102,7 @@ public void testConfigurableToMultipleKeys() throws Exception { JWT verifier = verification.createVerifierForGoogle(GoogleJwtCreatorTest.PICTURE, GoogleJwtCreatorTest.EMAIL, asList("issuer", "issuer2"), asList("audience", "audience2"), GoogleJwtCreatorTest.NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); - Map claims = jwt.getClaims(); + Map claims = jwt.getClaims(); assertTrue(claims.get(GoogleJwtCreatorTest.PICTURE).asString().equals(GoogleJwtCreatorTest.PICTURE)); assertTrue(claims.get(GoogleJwtCreatorTest.EMAIL).asString().equals(GoogleJwtCreatorTest.EMAIL)); List issuers = claims.get(PublicClaims.ISSUER).asList(String.class); 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..e5a4bab 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/AlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/AlgorithmTest.java @@ -19,6 +19,13 @@ 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 org.junit.Rule; @@ -26,12 +33,12 @@ 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; +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; public class AlgorithmTest { 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..52ee0da 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; @@ -35,23 +48,17 @@ 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.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 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 +112,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 +126,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 +138,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 +153,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 +164,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 +177,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 +194,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 +209,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 +225,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 +234,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 +249,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 +259,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 +273,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 +285,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 +300,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 +311,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 +324,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 +339,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 +354,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 +370,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 +379,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 +394,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 +404,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 +418,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 +430,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 +445,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 +456,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 +469,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 +484,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 +499,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 +515,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 +532,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 +556,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 +575,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 +594,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 +614,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 +629,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 +649,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 +689,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 +704,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 +724,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 +764,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 +779,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 +800,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 +965,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 +983,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 +1001,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..79a2dc9 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; @@ -35,23 +53,18 @@ 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.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 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 +988,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 +1006,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 +1024,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..f00e0c4 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java @@ -19,6 +19,17 @@ 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; @@ -35,14 +46,6 @@ 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; - public class HMACAlgorithmTest { @Rule 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..c6c7a4b 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; @@ -32,21 +45,15 @@ 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; - @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..41f8fb9 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java @@ -21,6 +21,9 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static java.util.Arrays.asList; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; @@ -28,16 +31,15 @@ import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; -import com.auth0.jwt.jwts.JWT; import com.auth0.jwt.jwts.AccessJWT; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertTrue; +import com.auth0.jwt.jwts.JWT; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.Date; +import java.util.Map; public class AccessJwtCreatorTest { @@ -342,7 +344,7 @@ public void testAccessJwtCreatorExpTimeHasPassed() throws Exception { verifyClaims(claims, exp); } - private static void verifyClaims(Map claims, Date 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")); 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..3967ed8 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ExtendedJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ExtendedJwtCreatorTest.java @@ -19,22 +19,22 @@ 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.EMAIL; +import static com.auth0.jwt.creators.GoogleJwtCreatorTest.NAME; +import static com.auth0.jwt.creators.GoogleJwtCreatorTest.PICTURE; +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.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; 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..0f87c59 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/FbJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/FbJwtCreatorTest.java @@ -21,8 +21,9 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.creators.FbJwtCreator; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; import com.auth0.jwt.impl.PublicClaims; @@ -31,13 +32,13 @@ import com.auth0.jwt.interfaces.Verification; import com.auth0.jwt.jwts.FbJWT; import com.auth0.jwt.jwts.JWT; -import static org.junit.Assert.assertTrue; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.Date; +import java.util.Map; public class FbJwtCreatorTest { @@ -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); @@ -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..c975048 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java @@ -21,8 +21,10 @@ 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; @@ -31,15 +33,13 @@ import com.auth0.jwt.interfaces.GoogleVerification; import com.auth0.jwt.jwts.GoogleJWT; import com.auth0.jwt.jwts.JWT; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertTrue; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; - import java.text.SimpleDateFormat; -import java.util.*; +import java.util.Date; +import java.util.Map; public class GoogleJwtCreatorTest { @@ -133,7 +133,7 @@ public void testGoogleJwtCreatorWhenCertainRequiredClaimIsntProvided() throws Ex GoogleVerification verification = GoogleJWT.require(algorithm); JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -157,7 +157,7 @@ public void testGoogleJwtCreatorNoneAlgorithmNotAllowed() throws Exception { GoogleVerification verification = GoogleJWT.require(algorithm); JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -180,7 +180,7 @@ public void testGoogleJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() th GoogleVerification verification = GoogleJWT.require(algorithm); JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -201,7 +201,7 @@ public void testGoogleJwtCreatorNoneAlgorithmAllowed() throws Exception { GoogleVerification verification = GoogleJWT.require(algorithm); JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -251,7 +251,7 @@ public void testGoogleJwtCreatorInvalidIssuer() throws Exception { GoogleVerification verification = GoogleJWT.require(algorithm); JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -363,7 +363,7 @@ public void testGoogleJwtCreatorNonStandardClaimString() throws Exception { .sign(algorithm); GoogleVerification verification = GoogleJWT.require(algorithm); JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"), - NAME, 1, 1).build(); + NAME, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -536,14 +536,14 @@ public void testGoogleJwtCreatorTokenCantBeUsedBefore() throws Exception { } @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")); verification.createVerifierForExtended(null, null, null, null, null, 1L, 1L, 1L); } - protected static void verifyClaims(Map claims, Date exp) { + 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")); 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..d58087d 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java @@ -19,8 +19,11 @@ 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; @@ -29,13 +32,12 @@ import com.auth0.jwt.interfaces.Verification; import com.auth0.jwt.jwts.ImplicitJWT; import com.auth0.jwt.jwts.JWT; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertTrue; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.util.*; +import java.util.Date; +import java.util.Map; public class ImplicitJwtCreatorTest { @@ -317,7 +319,7 @@ public void testImplicitJwtCreatorNonStandardClaimDateValue() throws Exception { verifyClaims(claims); } - private static void verifyClaims(Map 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")); 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..b7c95d3 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java @@ -19,11 +19,16 @@ 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; @@ -38,12 +43,6 @@ 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; - public class JWTCreatorTest { private static final String PRIVATE_KEY_FILE_RSA = "src/test/resources/rsa-private.pem"; 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..d84a3f6 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/RiscJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/RiscJwtCreatorTest.java @@ -21,6 +21,9 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; +import static java.util.Arrays.asList; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; @@ -30,14 +33,13 @@ import com.auth0.jwt.interfaces.Verification; import com.auth0.jwt.jwts.JWT; import com.auth0.jwt.jwts.RiscJWT; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertTrue; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.Date; +import java.util.Map; public class RiscJwtCreatorTest { @@ -404,7 +406,7 @@ public void testRiscJwtCreatorExpTimeHasPassed() throws Exception { verifyClaims(claims, exp); } - private static void verifyClaims(Map claims, Date 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")); 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..4fc371f 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java @@ -21,8 +21,10 @@ 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; @@ -31,14 +33,13 @@ import com.auth0.jwt.interfaces.Verification; import com.auth0.jwt.jwts.JWT; import com.auth0.jwt.jwts.ScopedJWT; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertTrue; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.Date; +import java.util.Map; public class ScopedJwtCreatorTest { @@ -396,7 +397,7 @@ public void testScopedJwtCreatorExpTimeHasPassed() throws Exception { verifyClaims(claims, expDate); } - private static void verifyClaims(Map claims, Date 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")); 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..94d84dc 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/BasicHeaderTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/BasicHeaderTest.java @@ -19,6 +19,12 @@ 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; @@ -30,9 +36,6 @@ 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..8abfc81 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/ClaimsHolderTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/ClaimsHolderTest.java @@ -19,15 +19,17 @@ package com.auth0.jwt.impl; +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 org.hamcrest.collection.IsMapContaining; import org.junit.Test; import java.util.HashMap; import java.util.Map; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; - public class ClaimsHolderTest { @SuppressWarnings("RedundantCast") 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..c8c782f 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; @@ -40,13 +49,6 @@ 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..f3e0779 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; @@ -38,15 +53,12 @@ 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.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; public class JsonNodeClaimTest { 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..114ccc0 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,25 +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 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; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class PayloadDeserializerTest { 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..4802df2 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/PayloadImplTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/PayloadImplTest.java @@ -19,12 +19,18 @@ package com.auth0.jwt.impl; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertTrue; + import com.auth0.jwt.interfaces.Claim; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; import 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; @@ -36,9 +42,6 @@ import java.util.HashMap; import java.util.Map; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; - public class PayloadImplTest { @Rule diff --git a/lib/src/test/java/com/auth0/jwt/impl/PayloadSerializerTest.java b/lib/src/test/java/com/auth0/jwt/impl/PayloadSerializerTest.java index c7e9873..3275517 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/PayloadSerializerTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/PayloadSerializerTest.java @@ -19,6 +19,11 @@ 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; @@ -33,9 +38,6 @@ import java.util.HashMap; import java.util.Map; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; - public class PayloadSerializerTest { private StringWriter writer; 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..d105ebb 100644 --- a/lib/src/test/java/com/auth0/jwt/verification/VerificationAndAssertionTest.java +++ b/lib/src/test/java/com/auth0/jwt/verification/VerificationAndAssertionTest.java @@ -19,6 +19,8 @@ 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; @@ -27,8 +29,6 @@ import com.auth0.jwt.interfaces.Verification; 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; From a5a4c6389a2487e8bb8bdb137c313f642b18fa35 Mon Sep 17 00:00:00 2001 From: Justin Dahmubed Date: Thu, 25 Jan 2018 13:44:56 -0800 Subject: [PATCH 4/7] Code style changes --- .../auth0/jwt/creators/AccessJwtCreator.java | 10 +- .../com/auth0/jwt/creators/FbJwtCreator.java | 2 +- .../auth0/jwt/creators/GoogleJwtCreator.java | 27 +- .../jwt/creators/ImplicitJwtCreator.java | 10 +- .../com/auth0/jwt/creators/JWTCreator.java | 2 +- .../auth0/jwt/creators/RiscJwtCreator.java | 11 +- .../auth0/jwt/creators/ScopedJwtCreator.java | 17 +- .../auth0/jwt/impl/HeaderDeserializer.java | 1 + .../auth0/jwt/impl/PayloadDeserializer.java | 1 + .../com/auth0/jwt/impl/PayloadSerializer.java | 1 + .../jwt/interfaces/ExtendedVerification.java | 23 -- .../jwt/interfaces/constants/Constants.java | 18 + .../constants}/PublicClaims.java | 2 +- .../java/com/auth0/jwt/jwts/GoogleJWT.java | 4 +- lib/src/main/java/com/auth0/jwt/jwts/JWT.java | 2 +- .../java/com/auth0/jwt/jwts/ScopedJWT.java | 4 +- .../main/java/com/auth0/jwt/oicmsg/ECKey.java | 13 +- .../main/java/com/auth0/jwt/oicmsg/Key.java | 49 +-- .../java/com/auth0/jwt/oicmsg/KeyBundle.java | 87 ++-- .../java/com/auth0/jwt/oicmsg/KeyJar.java | 55 +-- .../java/com/auth0/jwt/oicmsg/RSAKey.java | 15 +- .../VerificationAndAssertion.java | 2 +- .../com/auth0/jwt/ConcurrentVerifyTest.java | 7 +- .../java/com/auth0/jwt/JWTDecoderTest.java | 59 +-- .../com/auth0/jwt/MainTestSignatures.java | 96 ++--- .../auth0/jwt/algorithms/AlgorithmTest.java | 12 +- .../jwt/algorithms/HMACAlgorithmTest.java | 32 +- .../jwt/creators/AccessJwtCreatorTest.java | 159 ++++---- .../jwt/creators/ExtendedJwtCreatorTest.java | 241 ++++++----- .../auth0/jwt/creators/FbJwtCreatorTest.java | 31 +- .../jwt/creators/GoogleJwtCreatorTest.java | 376 +++++++++--------- .../jwt/creators/ImplicitJwtCreatorTest.java | 157 ++++---- .../auth0/jwt/creators/JWTCreatorTest.java | 45 ++- .../jwt/creators/RiscJwtCreatorTest.java | 179 ++++----- .../jwt/creators/ScopedJwtCreatorTest.java | 211 +++++----- .../com/auth0/jwt/impl/PayloadImplTest.java | 9 +- .../VerificationAndAssertionTest.java | 8 +- 37 files changed, 977 insertions(+), 1001 deletions(-) delete mode 100644 lib/src/main/java/com/auth0/jwt/interfaces/ExtendedVerification.java create mode 100644 lib/src/main/java/com/auth0/jwt/interfaces/constants/Constants.java rename lib/src/main/java/com/auth0/jwt/{impl => interfaces/constants}/PublicClaims.java (97%) 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 274b7ab..ee61bbb 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java @@ -21,7 +21,7 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.JWT; import java.util.Date; @@ -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; } 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 ce3f546..f003a08 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/FbJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/FbJwtCreator.java @@ -21,7 +21,7 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.JWT; import java.util.Date; 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 70c1747..4c46cc1 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/GoogleJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/GoogleJwtCreator.java @@ -21,7 +21,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.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.JWT; import java.util.Date; @@ -41,11 +42,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 +69,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 +80,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 +92,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 +106,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 +119,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; } 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 91cd16f..0cca245 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ImplicitJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ImplicitJwtCreator.java @@ -21,7 +21,7 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.JWT; import java.util.Date; @@ -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; } 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 93da9e8..120da9f 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java @@ -24,7 +24,7 @@ import com.auth0.jwt.exceptions.SignatureGenerationException; import com.auth0.jwt.impl.ClaimsHolder; import com.auth0.jwt.impl.PayloadSerializer; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; 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 2de8dd2..b3e114a 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/RiscJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/RiscJwtCreator.java @@ -21,7 +21,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.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.JWT; import java.util.Date; @@ -42,8 +43,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() {{ @@ -78,7 +79,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; } @@ -91,7 +92,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; } 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 6ae9e37..db9d8c5 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ScopedJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ScopedJwtCreator.java @@ -21,7 +21,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.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.JWT; import java.util.Date; @@ -41,9 +42,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 +66,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 +80,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 +93,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; } 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..ee4729a 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/HeaderDeserializer.java +++ b/lib/src/main/java/com/auth0/jwt/impl/HeaderDeserializer.java @@ -20,6 +20,7 @@ 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; 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 e3c7e84..71034cf 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; 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..4e5d2bc 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/PayloadSerializer.java +++ b/lib/src/main/java/com/auth0/jwt/impl/PayloadSerializer.java @@ -19,6 +19,7 @@ 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; 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/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/GoogleJWT.java b/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java index 2e71be4..da888a7 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java @@ -58,7 +58,7 @@ public Verification createVerifierForGoogle(String picture, String email, List issuer, * @return this same Verification instance. */ public Verification withScope(String scope) { - requireClaim("scope", scope); + requireClaim(Constants.SCOPE, scope); return this; } @@ -92,7 +93,6 @@ 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. diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java b/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java index c5d9ce8..8660505 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java @@ -23,7 +23,6 @@ public class ECKey extends Key { private Object curve; final private static Logger logger = LoggerFactory.getLogger(ECKey.class); 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")); @@ -85,9 +84,9 @@ private EllipticCurve byName(String name) { public List getKey(boolean isPrivate) { if (isPrivate) { - return new ArrayList<>(Arrays.asList(this.d)); + return Arrays.asList(this.d); } else { - return new ArrayList<>(Arrays.asList(this.x, this.y)); + return Arrays.asList(this.x, this.y); } } @@ -162,10 +161,6 @@ public void setCurve(Object curve) { this.curve = curve; } - public static Logger getLogger() { - return logger; - } - public static Set getLongs() { return longs; } @@ -182,10 +177,6 @@ public static void setMembers(Set members) { ECKey.members = members; } - public static Set getPublicMembers() { - return publicMembers; - } - public static void setPublicMembers(Set publicMembers) { ECKey.publicMembers = publicMembers; } diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java b/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java index 7e78c00..75ca00c 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java @@ -1,6 +1,7 @@ package com.auth0.jwt.oicmsg; import com.auth0.jwt.exceptions.oicmsg_exceptions.HeaderError; +import com.google.common.base.Strings; import com.google.common.primitives.Bytes; import com.google.gson.Gson; import org.bouncycastle.util.encoders.Base64; @@ -30,10 +31,14 @@ public class Key { 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 = new ArrayList<>(Arrays.asList("kty")); + 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; @@ -112,10 +117,6 @@ public void setInactiveSince() { this.inactiveSince = System.currentTimeMillis(); } - public void setInactiveSince(long now) { - this.inactiveSince = now; - } - public long getInactiveSince() { return inactiveSince; } @@ -137,13 +138,13 @@ public Key serialize() { public Map common() { Map args = new HashMap<>(); args.put("kty", this.kty); - if (this.use != null && !this.use.isEmpty()) { + if (!Strings.isNullOrEmpty(this.use)) { args.put("use", this.use); } - if (this.kid != null && !this.kid.isEmpty()) { + if (!Strings.isNullOrEmpty(this.kid)) { args.put("kid", this.kid); } - if (this.alg != null && !this.alg.isEmpty()) { + if (!Strings.isNullOrEmpty(this.alg)) { args.put("alg", this.alg); } return args; @@ -154,10 +155,6 @@ public String toString() { return this.toDict().toString(); } - public Key getKey() { - return this.key; - } - public boolean verify() throws HeaderError { Object item = null; for (String key : longs.keySet()) { @@ -181,15 +178,14 @@ public boolean verify() throws HeaderError { base64URLToLong(item); } catch (Exception e) { return false; - } finally { - for (String sign : new ArrayList<>(Arrays.asList("+", "/", "="))) { - if (((String) item).contains(sign)) { - return false; - } + } + for (String sign : signs){ + if (((String) item).contains(sign)) { + return false; } } - if (this.kid != null && !this.kid.isEmpty()) { + if (!Strings.isNullOrEmpty(this.kid)) { try { Assert.assertTrue(this.kid instanceof String); } catch (AssertionError error) { @@ -220,16 +216,15 @@ public boolean equals(Object other) { Assert.assertEquals(this.getX5u(), otherKey.x5u); } catch (AssertionError error) { return false; - } finally { - return true; } + return true; } public List getKeys() { return new ArrayList<>(this.toDict().keySet()); } - public byte[] thumbprint(String hashFunction, List members) { + public byte[] thumbprint(String hashFunction, List members) throws NoSuchFieldException { if (members == null || members.isEmpty()) { members = required; } @@ -239,24 +234,20 @@ public byte[] thumbprint(String hashFunction, List members) { String value = null; Map hmap = new HashMap<>(); for (String member : members) { - try { - value = key.getClass().getField(member).toString(); - } catch (NoSuchFieldException e) { - logger.error(e.toString()); - } + value = key.getClass().getField(member).toString(); hmap.put(member, value); } String json = new Gson().toJson(hmap); byte[] byteArr = null; switch (hashFunction) { - case "SHA-256": + case SHA_256: byteArr = sha256_digest(json); break; - case "SHA-384": + case SHA_384: byteArr = sha384_digest(json); break; - case "SHA-512": + case SHA_512: byteArr = sha512_digest(json); break; default: diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java index 9577bf1..6209bba 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java @@ -1,7 +1,6 @@ package com.auth0.jwt.oicmsg; import com.auth0.jwt.exceptions.oicmsg_exceptions.ImportException; -import com.auth0.jwt.exceptions.oicmsg_exceptions.JWKException; import com.auth0.jwt.exceptions.oicmsg_exceptions.TypeError; import com.auth0.jwt.exceptions.oicmsg_exceptions.UnknownKeyType; import com.auth0.jwt.exceptions.oicmsg_exceptions.UpdateFailed; @@ -38,7 +37,7 @@ public class KeyBundle { final private static Logger logger = LoggerFactory.getLogger(KeyBundle.class); private static final Map K2C = - ImmutableMap.of("RSA", new RSAKey(), + ImmutableMap.of(RSA_KEY, new RSAKey(), "EC", new ECKey(), "oct", new SYMKey() ); @@ -48,7 +47,7 @@ public class KeyBundle { "ver", "sig", "sig", "sig" ); - private static final Set fileTypes = new HashSet(Arrays.asList("rsa", "der", "jwks")); + private static final Set fileTypes = new HashSet(Arrays.asList("rsa", DER, JWKS)); private java.util.List keys; private Map> impJwks; private String source; @@ -63,6 +62,9 @@ public class KeyBundle { 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; public KeyBundle(List keys, String source, long cacheTime, boolean verifySSL, @@ -110,35 +112,31 @@ public KeyBundle(List keys, String source, long cacheTime, boolean verifySS } catch (UpdateFailed updateFailed) { logger.error("Local key updated from " + this.source + " failed."); } - } else if (this.fileFormat.equals("der")) { + } else if (this.fileFormat.equals(DER)) { doLocalDer(this.source, this.keyType, this.keyUsage); } } } } - public String getSource() { - return source; - } - public KeyBundle() throws ImportException { - this(null, "", 300, true, "jwk", "RSA", null); + this(null, "", 300, true, JWK, RSA_KEY, null); } public KeyBundle(List keyList, String keyType) throws ImportException { - this(keyList, "", 300, true, "jwk", keyType, null); + this(keyList, "", 300, true, JWK, keyType, null); } public KeyBundle(List keyList, String keyType, List usage) throws ImportException { - this(keyList, "", 300, true, "jwk", keyType, usage); + this(keyList, "", 300, true, JWK, keyType, usage); } public KeyBundle(String source, boolean verifySSL) throws ImportException { - this(null, source, 300, verifySSL, "jwk", "RSA", null); + 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", usage); + this(null, source, 300, true, fileFormat, RSA_KEY, usage); } public void doKeys(List keys) { @@ -148,35 +146,17 @@ public void doKeys(List keys) { keys.remove("use"); boolean flag = false; for (String use : usage) { - List types = new ArrayList() {{ - add(kty); - add(kty.toLowerCase()); - add(kty.toUpperCase()); - }}; - boolean isSuccess = true; - Key key; - for (String typeIndex : types) { - try { - switch (typeIndex) { - case "RSA": - key = new RSAKey("use"); - break; - case "EC": - key = new ECKey("use"); - break; - case "SYMKey": - key = new SYMKey("use"); - break; - default: - throw new IllegalArgumentException("Encryption type: " + typeIndex + " isn't supported"); - } - this.keys.add(key); - flag = true; - break; - } catch (JWKException exception) { - logger.warn("While loading keys: " + exception); - } + 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) { @@ -221,7 +201,7 @@ public void doLocalJwk(String fileName) throws UpdateFailed { public void doLocalDer(String fileName, String keyType, List keyUsage) throws NotImplementedException { RSAKey rsaKey = rsaLoad(fileName); - if (!keyType.equalsIgnoreCase("rsa")) { + if (!keyType.equalsIgnoreCase(RSA_KEY)) { throw new NotImplementedException(); } @@ -324,12 +304,8 @@ private boolean upToDate() { boolean result = false; if (!this.keys.isEmpty()) { - if (this.remote) { - if (System.currentTimeMillis() > this.timeOut) { - if (update()) { - result = true; - } - } + if (this.remote && System.currentTimeMillis() > this.timeOut && update()) { + result = true; } } else if (this.remote) { if (update()) { @@ -347,9 +323,9 @@ public boolean update() { this.keys = new ArrayList(); try { if (!this.remote) { - if (this.fileFormat.equals("jwks")) { + if (this.fileFormat.equals(JWKS)) { this.doLocalJwk(this.source); - } else if (this.fileFormat.equals("der")) { + } else if (this.fileFormat.equals(DER)) { doLocalDer(source, keyType, keyUsage); } } else { @@ -361,11 +337,10 @@ public boolean update() { return false; } - long now = System.currentTimeMillis(); for (Key key : keys) { if (!keys.contains(key)) { if (key.getInactiveSince() == Long.MIN_VALUE) { - key.setInactiveSince(now); + key.setInactiveSince(); } } this.keys.add(key); @@ -397,6 +372,10 @@ public List getKeys() { return this.keys; } + public String getSource() { + return source; + } + public List getActiveKeys() { List activeKeys = new ArrayList<>(); for (Key key : this.keys) { @@ -485,7 +464,7 @@ public List getKids() { public void markAsInactive(String kid) { Key key = getKeyWithKid(kid); - key.setInactiveSince(System.currentTimeMillis()); + key.setInactiveSince(); } public void removeOutdated(float after, int when) throws TypeError { @@ -515,7 +494,7 @@ public KeyBundle keyBundleFromLocalFile(String filename, String type, List> 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); public KeyJar(boolean verifySSL, KeyBundle keyBundle, int removeAfter) { @@ -61,8 +68,8 @@ public void addSymmetricKey(String owner, Key key, List usage) throws Im Key key = b64e(key.toString().getBytes()); if (usage == null || usage.isEmpty()) { List kbList = new ArrayList<>(); - List keyList = new ArrayList<>(Arrays.asList(key)); - KeyBundle kb = new KeyBundle(keyList, "oct"); + List keyList = Arrays.asList(key); + KeyBundle kb = new KeyBundle(keyList, OCT); kbList.add(kb); issuerKeys.put(owner, kbList); } else { @@ -72,9 +79,9 @@ public void addSymmetricKey(String owner, Key key, List usage) throws Im List usageList = new ArrayList<>(); for (String use : usage) { kbList = issuerKeys.get(owner); - keyList = new ArrayList<>(Arrays.asList(key)); + keyList = Arrays.asList(key); usageList.add(use); - kb = new KeyBundle(keyList, "oct", usageList); + kb = new KeyBundle(keyList, OCT, usageList); kbList.add(kb); issuerKeys.put(owner, kbList); } @@ -84,7 +91,7 @@ public void addSymmetricKey(String owner, Key key, List usage) throws Im public void addKeyBundle(String owner, KeyBundle keyBundle) { List kbList; if (issuerKeys.get(owner) == null) { - kbList = new ArrayList<>(Arrays.asList(keyBundle)); + kbList = Arrays.asList(keyBundle); issuerKeys.put(owner, kbList); } else { kbList = issuerKeys.get(owner); @@ -99,10 +106,10 @@ public Collection> getItems() { public List getKeys(String keyUse, String keyType, String owner, String kid, Map args) { String use; - if (keyUse.equals("dec") || keyUse.equals("enc")) { - use = "enc"; + if (keyUse.equals(DEC) || keyUse.equals(ENC)) { + use = ENC; } else { - use = "sig"; + use = SIG; } List keyBundleList = null; @@ -134,7 +141,7 @@ public List getKeys(String keyUse, String keyType, String owner, String kid } for (Key key : keyList) { - if (key.getInactiveSince() == 0 && !"sig".equals(keyUse)) { + if (key.getInactiveSince() == 0 && !SIG.equals(keyUse)) { continue; } if (key.getUse() != null || use.equals(key.getUse())) { @@ -151,8 +158,8 @@ public List getKeys(String keyUse, String keyType, String owner, String kid } String name; - if (keyType.equals("EC") && args.containsKey("alg")) { - name = "P-{}" + args.get("alg").substring(2); + if (keyType.equals(EC) && args.containsKey(ALG)) { + name = "P-{}" + args.get(ALG).substring(2); List tempKeyList = new ArrayList<>(); for (Key key : keyList) { try { @@ -166,7 +173,7 @@ public List getKeys(String keyUse, String keyType, String owner, String kid keyList = tempKeyList; } - if (use.equals("enc") && keyType.equals("oct") && !Strings.isNullOrEmpty(owner)) { + 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)) { @@ -180,7 +187,7 @@ public List getKeys(String keyUse, String keyType, String owner, String kid } public List getSigningKey(String keyType, String owner, String kid, Map args) { - return getKeys("sig", keyType, owner, kid, args); + return getKeys(SIG, keyType, owner, kid, args); } public List getVerifyKey(String keyType, String owner, String kid, Map args) { @@ -188,16 +195,16 @@ public List getVerifyKey(String keyType, String owner, String kid, Map getEncryptKey(String keyType, String owner, String kid, Map args) { - return getKeys("enc", keyType, owner, kid, 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); + 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")) { + if (usage.equals(SIG) || usage.equals("ver")) { keyType = algorithmToKeytypeForJWS(algorithm); } else { keyType = algorithmToKeytypeForJWE(algorithm); @@ -218,23 +225,23 @@ private String algorithmToKeytypeForJWS(String algorithm) { if (algorithm == null || algorithm.equalsIgnoreCase("none")) { return "none"; } else if (algorithm.startsWith("RS") || algorithm.startsWith("PS")) { - return "RSA"; + return RSA; } else if (algorithm.startsWith("HS") || algorithm.startsWith("A")) { - return "oct"; + return OCT; } else if (algorithm.startsWith("ES") || algorithm.startsWith("ECDH-ES")) { - return "EC"; + return EC; } else { return null; } } private String algorithmToKeytypeForJWE(String algorithm) { - if (algorithm.startsWith("RSA")) { - return "RSA"; + if (algorithm.startsWith(RSA)) { + return RSA; } else if (algorithm.startsWith("A")) { - return "oct"; + return OCT; } else if (algorithm.startsWith("ECDH")) { - return "EC"; + return EC; } else { return null; } @@ -291,7 +298,7 @@ public Map> exportJwksAsJson(boolean isPrivate, String issuer) public void importJwks(Map jwks, String issuer) throws ImportException { String keys = jwks.get("keys"); - List keyBundleList = this.issuerKeys.get("issuer"); + List keyBundleList = this.issuerKeys.get(Constants.ISSUER); if (keyBundleList == null) { keyBundleList = new ArrayList<>(); } diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java b/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java index e456613..1040b2e 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java @@ -2,6 +2,7 @@ import com.auth0.jwt.exceptions.oicmsg_exceptions.DeserializationNotPossible; import com.auth0.jwt.exceptions.oicmsg_exceptions.SerializationNotPossible; +import com.google.common.base.Strings; import org.bouncycastle.util.encoders.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -80,13 +81,13 @@ public void deserialize() throws DeserializationNotPossible { } } - List list = new ArrayList<>(Arrays.asList(this.n, this.e)); - if (this.d != null && !this.d.isEmpty()) { + List list = Arrays.asList(this.n, this.e); + if (!Strings.isNullOrEmpty(this.d)) { list.add(this.d); } - if (this.p != null && !this.p.isEmpty()) { + if (!Strings.isNullOrEmpty(this.p)) { list.add(this.p); - if (this.q != null && !this.q.isEmpty()) { + if (!Strings.isNullOrEmpty(this.q)) { list.add(this.q); } this.key = RSA.construct(tuple(list)); //TODO @@ -133,8 +134,8 @@ public Map serialize(boolean isPrivate) throws SerializationNotP if (isPrivate) { for (String param : longs) { - if (!isPrivate && new ArrayList<>(Arrays.asList("d", "p", "q", "dp", "dq", "di", - "qi")).contains(param)) { + if (!isPrivate && Arrays.asList("d", "p", "q", "dp", "dq", "di", + "qi").contains(param)) { continue; } try { @@ -158,7 +159,7 @@ private void split() { this.d = this.key.d; Object item = null; - for (String param : new ArrayList<>(Arrays.asList("p", "q"))) { + for (String param : Arrays.asList("p", "q")) { try { item = this.getClass().getField(param).get(this); } catch (Exception e1) { 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..2965799 100644 --- a/lib/src/main/java/com/auth0/jwt/verification/VerificationAndAssertion.java +++ b/lib/src/main/java/com/auth0/jwt/verification/VerificationAndAssertion.java @@ -23,7 +23,7 @@ import com.auth0.jwt.exceptions.AlgorithmMismatchException; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.impl.PublicClaims; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.Clock; import com.auth0.jwt.interfaces.DecodedJWT; diff --git a/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java b/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java index 380cfdc..45b6f7b 100644 --- a/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java +++ b/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java @@ -23,6 +23,7 @@ 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 net.jodah.concurrentunit.Waiter; import org.junit.AfterClass; @@ -102,7 +103,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"; @@ -112,7 +113,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); @@ -121,7 +122,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 4e740b9..4315f68 100644 --- a/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java +++ b/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java @@ -32,6 +32,7 @@ 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 org.apache.commons.codec.binary.Base64; import org.hamcrest.collection.IsCollectionWithSize; @@ -53,7 +54,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")); @@ -64,7 +65,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"); } @@ -72,7 +73,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"); } @@ -99,7 +100,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())); @@ -109,7 +110,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")); @@ -118,7 +119,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")); @@ -127,7 +128,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")); @@ -138,7 +139,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")); @@ -147,7 +148,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")); @@ -156,7 +157,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))); @@ -166,7 +167,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))); @@ -176,7 +177,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))); @@ -189,7 +190,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))); @@ -202,7 +203,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))); @@ -215,7 +216,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")); @@ -224,7 +225,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")); @@ -233,7 +234,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")); @@ -242,7 +243,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")); @@ -254,7 +255,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())); @@ -265,7 +266,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())); @@ -275,7 +276,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)); @@ -284,7 +285,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)); @@ -293,7 +294,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)); @@ -302,7 +303,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())); @@ -312,7 +313,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")); @@ -321,7 +322,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)); @@ -330,7 +331,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(); @@ -342,7 +343,7 @@ 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(); @@ -363,7 +364,7 @@ public void shouldGetAvailableClaims() 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/MainTestSignatures.java b/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java index 567673f..febcf59 100644 --- a/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java +++ b/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java @@ -26,12 +26,12 @@ 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 org.junit.Rule; @@ -54,12 +54,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); } @@ -69,53 +69,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)); + 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 @@ -123,21 +123,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); } @@ -146,21 +146,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/algorithms/AlgorithmTest.java b/lib/src/test/java/com/auth0/jwt/algorithms/AlgorithmTest.java index e5a4bab..eb26e63 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/AlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/AlgorithmTest.java @@ -234,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))); @@ -244,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))); @@ -254,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))); @@ -264,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))); @@ -274,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))); @@ -284,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/HMACAlgorithmTest.java b/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java index f00e0c4..a6af171 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java @@ -63,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); @@ -96,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); @@ -129,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); @@ -169,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); @@ -185,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); @@ -203,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); @@ -221,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); @@ -239,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); @@ -257,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); @@ -275,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); @@ -301,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]); } @@ -315,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/creators/AccessJwtCreatorTest.java b/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java index 41f8fb9..0f342fd 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java @@ -27,7 +27,8 @@ 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.constants.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; @@ -51,16 +52,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); @@ -68,16 +69,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); @@ -85,16 +86,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); @@ -104,16 +105,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); } @@ -121,16 +122,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); } @@ -141,16 +142,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); } @@ -161,15 +162,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); } @@ -177,15 +178,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); @@ -193,17 +194,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); @@ -211,17 +212,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); @@ -229,17 +230,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); @@ -247,17 +248,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); @@ -265,17 +266,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); @@ -283,17 +284,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); @@ -301,17 +302,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); @@ -328,26 +329,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")); + 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 3967ed8..d770b1e 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ExtendedJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ExtendedJwtCreatorTest.java @@ -21,15 +21,14 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; -import static com.auth0.jwt.creators.GoogleJwtCreatorTest.EMAIL; import static com.auth0.jwt.creators.GoogleJwtCreatorTest.NAME; -import static com.auth0.jwt.creators.GoogleJwtCreatorTest.PICTURE; 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.interfaces.constants.Constants; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.GoogleVerification; @@ -53,20 +52,20 @@ 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) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); @@ -75,20 +74,20 @@ 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) .signBase16Encoding(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode16Bytes(token); Map claims = jwt.getClaims(); @@ -97,20 +96,20 @@ 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) .signBase32Encoding(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode32Bytes(token); Map claims = jwt.getClaims(); @@ -121,20 +120,20 @@ 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) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -143,20 +142,20 @@ 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) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -165,20 +164,20 @@ 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) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); @@ -189,20 +188,20 @@ 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) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); @@ -213,20 +212,20 @@ 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"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); @@ -241,11 +240,11 @@ 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) @@ -253,7 +252,7 @@ public void testExtendedJwtCreatorNoneAlgorithmNotAllowed() throws Exception { .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -266,11 +265,11 @@ 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) @@ -278,7 +277,7 @@ public void testExtendedJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -288,11 +287,11 @@ 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) @@ -300,7 +299,7 @@ public void testExtendedJwtCreatorNoneAlgorithmAllowed() throws Exception { .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); @@ -309,14 +308,14 @@ 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) @@ -324,21 +323,21 @@ public void testExtendedJwtCreatorNonStandardClaimStringValue() throws Exception .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 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) @@ -346,21 +345,21 @@ public void testExtendedJwtCreatorNonStandardClaimIntegerValue() throws Exceptio .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 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) @@ -368,21 +367,21 @@ public void testExtendedJwtCreatorNonStandardClaimLongValue() throws Exception { .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 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) @@ -390,21 +389,21 @@ public void testExtendedJwtCreatorNonStandardClaimDoubleValue() throws Exception .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 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) @@ -412,21 +411,21 @@ public void testExtendedJwtCreatorNonStandardClaimBooleanValue() throws Exceptio .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 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) @@ -434,7 +433,7 @@ public void testExtendedJwtCreatorNonStandardClaimDateValue() throws Exception { .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -450,14 +449,14 @@ 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) @@ -465,7 +464,7 @@ public void testExtendedJwtCreatorExpTimeHasPassed() throws Exception { .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); - JWT verifier = verification.createVerifierForExtended(PICTURE, EMAIL, asList("issuer"), asList("audience"), + JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), 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 0f87c59..51f1627 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/FbJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/FbJwtCreatorTest.java @@ -21,15 +21,16 @@ 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.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 org.junit.Rule; @@ -51,7 +52,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) @@ -67,7 +68,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) @@ -83,7 +84,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) @@ -101,7 +102,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) @@ -117,7 +118,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) @@ -133,7 +134,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) @@ -198,7 +199,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) @@ -216,7 +217,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) @@ -234,7 +235,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) @@ -252,7 +253,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) @@ -270,7 +271,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) @@ -288,7 +289,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) @@ -306,7 +307,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) @@ -333,7 +334,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) 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 c975048..448967b 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java @@ -27,10 +27,11 @@ 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.constants.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.GoogleJWT; import com.auth0.jwt.jwts.JWT; import org.junit.Rule; @@ -47,27 +48,24 @@ public class GoogleJwtCreatorTest { public ExpectedException thrown = ExpectedException.none(); private static final Date exp = generateRandomExpDateInFuture(); private static final Date iat = generateRandomIatDateInPast(); - public static final String PICTURE = "picture"; - public static final String EMAIL = "email"; - public static final String NAME = "name"; @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 +73,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 +94,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 +118,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 +142,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 +166,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 +186,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 +209,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 +236,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 +258,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 +281,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 +304,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 +327,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 +369,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 +391,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 +413,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 +435,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 +457,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 +488,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,20 +516,20 @@ 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); } @@ -539,17 +537,17 @@ public void testGoogleJwtCreatorTokenCantBeUsedBefore() 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")); + 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 d58087d..f4538af 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java @@ -26,7 +26,8 @@ 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.constants.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; @@ -48,15 +49,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); @@ -64,15 +65,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); @@ -80,15 +81,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); @@ -98,15 +99,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); @@ -116,15 +117,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); @@ -134,14 +135,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); @@ -154,15 +155,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); } @@ -173,13 +174,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); } @@ -187,14 +188,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); @@ -202,16 +203,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); @@ -219,16 +220,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); @@ -236,16 +237,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); @@ -253,16 +254,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); @@ -270,16 +271,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); @@ -287,16 +288,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); @@ -304,24 +305,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")); + 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 b7c95d3..4d7862c 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java @@ -31,6 +31,7 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.ECDSAKeyProvider; import com.auth0.jwt.interfaces.RSAKeyProvider; +import com.auth0.jwt.interfaces.constants.Constants; import org.apache.commons.codec.binary.Base64; import org.junit.Rule; import org.junit.Test; @@ -67,7 +68,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("\\."); @@ -79,7 +80,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("\\."); @@ -157,7 +158,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")); @@ -167,7 +168,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")); @@ -177,7 +178,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")); @@ -185,7 +186,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")); @@ -195,7 +196,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")); @@ -205,7 +206,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")); @@ -215,7 +216,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")); @@ -225,7 +226,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")); @@ -236,7 +237,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")); @@ -245,7 +246,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("\\."); @@ -256,7 +257,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("\\."); @@ -284,7 +285,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("\\."); @@ -295,7 +296,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("\\."); @@ -306,7 +307,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("\\."); @@ -317,7 +318,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("\\."); @@ -328,7 +329,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("\\."); @@ -340,7 +341,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("\\."); @@ -351,7 +352,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("\\."); @@ -362,7 +363,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("\\."); @@ -373,7 +374,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 d84a3f6..b5ba508 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/RiscJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/RiscJwtCreatorTest.java @@ -27,7 +27,8 @@ 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.constants.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; @@ -52,18 +53,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); @@ -71,18 +72,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); @@ -90,18 +91,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); @@ -112,17 +113,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); @@ -133,16 +134,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); @@ -152,18 +153,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); } @@ -171,18 +172,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); } @@ -195,15 +196,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); } @@ -216,14 +217,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); } @@ -233,32 +234,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); @@ -266,18 +267,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); @@ -285,18 +286,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); @@ -304,18 +305,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); @@ -323,18 +324,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); @@ -342,18 +343,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); @@ -361,18 +362,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); @@ -389,27 +390,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")); + 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 4fc371f..79b3110 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java @@ -27,7 +27,8 @@ 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.constants.Constants; +import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; @@ -51,17 +52,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); @@ -69,17 +70,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); @@ -87,17 +88,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); @@ -107,17 +108,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); } @@ -125,17 +126,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); } @@ -143,17 +144,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); } @@ -161,16 +162,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); @@ -183,17 +184,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); } @@ -204,16 +205,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); } @@ -221,16 +222,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); @@ -238,18 +239,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); @@ -257,18 +258,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); @@ -276,18 +277,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); @@ -295,18 +296,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); @@ -314,18 +315,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); @@ -333,18 +334,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); @@ -352,18 +353,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); @@ -380,27 +381,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")); + 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/PayloadImplTest.java b/lib/src/test/java/com/auth0/jwt/impl/PayloadImplTest.java index 4802df2..bae5bcc 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/PayloadImplTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/PayloadImplTest.java @@ -27,6 +27,7 @@ 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 org.hamcrest.collection.IsCollectionWithSize; @@ -59,7 +60,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") @@ -73,7 +74,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 @@ -86,7 +87,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 @@ -101,7 +102,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/verification/VerificationAndAssertionTest.java b/lib/src/test/java/com/auth0/jwt/verification/VerificationAndAssertionTest.java index d105ebb..deeea6a 100644 --- a/lib/src/test/java/com/auth0/jwt/verification/VerificationAndAssertionTest.java +++ b/lib/src/test/java/com/auth0/jwt/verification/VerificationAndAssertionTest.java @@ -58,15 +58,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); } From e5fdab4dd0e18f1da10cd2f2813ae71f7ecd2e9a Mon Sep 17 00:00:00 2001 From: Justin Dahmubed Date: Thu, 25 Jan 2018 15:09:28 -0800 Subject: [PATCH 5/7] Import reorder --- .../main/java/com/auth0/jwt/ClockImpl.java | 1 - .../main/java/com/auth0/jwt/JWTDecoder.java | 9 ++-- .../com/auth0/jwt/algorithms/Algorithm.java | 1 - .../auth0/jwt/algorithms/CryptoHelper.java | 5 +- .../auth0/jwt/algorithms/ECDSAAlgorithm.java | 7 ++- .../auth0/jwt/algorithms/HMACAlgorithm.java | 9 ++-- .../auth0/jwt/algorithms/NoneAlgorithm.java | 3 +- .../auth0/jwt/algorithms/RSAAlgorithm.java | 7 ++- .../auth0/jwt/creators/AccessJwtCreator.java | 1 - .../jwt/creators/ExtendedJwtCreator.java | 1 - .../com/auth0/jwt/creators/FbJwtCreator.java | 1 - .../auth0/jwt/creators/GoogleJwtCreator.java | 1 - .../jwt/creators/ImplicitJwtCreator.java | 1 - .../com/auth0/jwt/creators/JWTCreator.java | 7 ++- .../java/com/auth0/jwt/creators/Message.java | 1 - .../auth0/jwt/creators/RiscJwtCreator.java | 1 - .../auth0/jwt/creators/ScopedJwtCreator.java | 1 - .../java/com/auth0/jwt/impl/BasicHeader.java | 1 - .../auth0/jwt/impl/HeaderDeserializer.java | 1 - .../java/com/auth0/jwt/impl/JWTParser.java | 1 - .../com/auth0/jwt/impl/JsonNodeClaim.java | 1 - .../java/com/auth0/jwt/impl/NullClaim.java | 1 - .../auth0/jwt/impl/PayloadDeserializer.java | 1 - .../java/com/auth0/jwt/impl/PayloadImpl.java | 1 - .../com/auth0/jwt/impl/PayloadSerializer.java | 1 - .../java/com/auth0/jwt/interfaces/Claim.java | 1 - .../auth0/jwt/interfaces/Verification.java | 1 - .../java/com/auth0/jwt/jwts/AccessJWT.java | 1 - .../java/com/auth0/jwt/jwts/ExtendedJWT.java | 1 - .../java/com/auth0/jwt/jwts/GoogleJWT.java | 1 - .../java/com/auth0/jwt/jwts/ImplicitJWT.java | 1 - lib/src/main/java/com/auth0/jwt/jwts/JWT.java | 3 +- .../main/java/com/auth0/jwt/jwts/RiscJWT.java | 1 - .../java/com/auth0/jwt/jwts/ScopedJWT.java | 1 - .../main/java/com/auth0/jwt/oicmsg/ECKey.java | 6 +-- .../main/java/com/auth0/jwt/oicmsg/Key.java | 11 ++-- .../java/com/auth0/jwt/oicmsg/KeyBundle.java | 23 ++++----- .../java/com/auth0/jwt/oicmsg/KeyJar.java | 5 +- .../java/com/auth0/jwt/oicmsg/RSAKey.java | 7 ++- .../java/com/auth0/jwt/oicmsg/SYMKey.java | 5 +- .../VerificationAndAssertion.java | 3 +- .../java/oiccli/client_auth/BearerHeader.java | 51 ------------------- .../java/com/auth0/jwt/ClockImplTest.java | 3 +- .../com/auth0/jwt/ConcurrentVerifyTest.java | 13 +++-- .../java/com/auth0/jwt/JWTDecoderTest.java | 7 ++- lib/src/test/java/com/auth0/jwt/JWTTest.java | 3 +- .../test/java/com/auth0/jwt/JsonMatcher.java | 7 ++- .../com/auth0/jwt/MainTestSignatures.java | 7 ++- lib/src/test/java/com/auth0/jwt/PemUtils.java | 5 +- .../auth0/jwt/algorithms/AlgorithmTest.java | 7 ++- .../jwt/algorithms/ECDSAAlgorithmTest.java | 15 +++--- .../ECDSABouncyCastleProviderTests.java | 15 +++--- .../jwt/algorithms/HMACAlgorithmTest.java | 9 ++-- .../jwt/algorithms/RSAAlgorithmTest.java | 9 ++-- .../jwt/creators/AccessJwtCreatorTest.java | 11 ++-- .../jwt/creators/ExtendedJwtCreatorTest.java | 9 ++-- .../auth0/jwt/creators/FbJwtCreatorTest.java | 7 ++- .../jwt/creators/GoogleJwtCreatorTest.java | 7 ++- .../jwt/creators/ImplicitJwtCreatorTest.java | 9 ++-- .../auth0/jwt/creators/JWTCreatorTest.java | 9 ++-- .../jwt/creators/RiscJwtCreatorTest.java | 11 ++-- .../jwt/creators/ScopedJwtCreatorTest.java | 11 ++-- .../com/auth0/jwt/impl/BasicHeaderTest.java | 5 +- .../com/auth0/jwt/impl/ClaimsHolderTest.java | 5 +- .../jwt/impl/HeaderDeserializerTest.java | 7 ++- .../com/auth0/jwt/impl/JsonNodeClaimTest.java | 13 +++-- .../jwt/impl/PayloadDeserializerTest.java | 13 +++-- .../com/auth0/jwt/impl/PayloadImplTest.java | 9 ++-- .../auth0/jwt/impl/PayloadSerializerTest.java | 5 +- 69 files changed, 149 insertions(+), 269 deletions(-) delete mode 100644 lib/src/main/java/oiccli/client_auth/BearerHeader.java 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 b275fed..92ba0cd 100644 --- a/lib/src/main/java/com/auth0/jwt/JWTDecoder.java +++ b/lib/src/main/java/com/auth0/jwt/JWTDecoder.java @@ -25,15 +25,14 @@ 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.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 9b64c6b..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,7 +25,6 @@ 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.ECKey; import java.security.interfaces.ECPrivateKey; 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 80767ac..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,6 @@ package com.auth0.jwt.algorithms; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -29,6 +26,8 @@ import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; 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 b7f294a..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,10 +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 java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; @@ -35,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 05fe0fa..98f3655 100644 --- a/lib/src/main/java/com/auth0/jwt/algorithms/HMACAlgorithm.java +++ b/lib/src/main/java/com/auth0/jwt/algorithms/HMACAlgorithm.java @@ -23,16 +23,15 @@ 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 java.io.UnsupportedEncodingException; import java.net.URLDecoder; 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 ee61bbb..a6b6aaa 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/AccessJwtCreator.java @@ -23,7 +23,6 @@ import com.auth0.jwt.exceptions.JWTCreationException; 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; 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 624439d..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,7 +21,6 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; - import java.util.Date; /** 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 f003a08..eb68296 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/FbJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/FbJwtCreator.java @@ -23,7 +23,6 @@ import com.auth0.jwt.exceptions.JWTCreationException; 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; 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 4c46cc1..8f3b706 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/GoogleJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/GoogleJwtCreator.java @@ -24,7 +24,6 @@ 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; 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 0cca245..9e66d66 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ImplicitJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ImplicitJwtCreator.java @@ -23,7 +23,6 @@ import com.auth0.jwt.exceptions.JWTCreationException; 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; 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 120da9f..5c2cfa9 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/JWTCreator.java @@ -29,16 +29,15 @@ import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; -import org.apache.commons.codec.binary.Base32; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.binary.Hex; - import java.io.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. 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 9ffa7c2..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; 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 b3e114a..8cc362a 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/RiscJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/RiscJwtCreator.java @@ -24,7 +24,6 @@ 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; 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 db9d8c5..e601d41 100644 --- a/lib/src/main/java/com/auth0/jwt/creators/ScopedJwtCreator.java +++ b/lib/src/main/java/com/auth0/jwt/creators/ScopedJwtCreator.java @@ -24,7 +24,6 @@ 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; 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 398bae6..e5efbc0 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/BasicHeader.java +++ b/lib/src/main/java/com/auth0/jwt/impl/BasicHeader.java @@ -24,7 +24,6 @@ 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; 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 ee4729a..21a3d29 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/HeaderDeserializer.java +++ b/lib/src/main/java/com/auth0/jwt/impl/HeaderDeserializer.java @@ -26,7 +26,6 @@ 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 e5d2515..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; 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 71034cf..bbb6568 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/PayloadDeserializer.java +++ b/lib/src/main/java/com/auth0/jwt/impl/PayloadDeserializer.java @@ -29,7 +29,6 @@ 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.ArrayList; import java.util.Collections; 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 ef01cb7..5800585 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/PayloadImpl.java +++ b/lib/src/main/java/com/auth0/jwt/impl/PayloadImpl.java @@ -24,7 +24,6 @@ import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.Payload; import com.fasterxml.jackson.databind.JsonNode; - import java.util.Collections; import java.util.Date; import java.util.HashMap; 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 4e5d2bc..4a53aee 100644 --- a/lib/src/main/java/com/auth0/jwt/impl/PayloadSerializer.java +++ b/lib/src/main/java/com/auth0/jwt/impl/PayloadSerializer.java @@ -23,7 +23,6 @@ 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/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/jwts/AccessJWT.java b/lib/src/main/java/com/auth0/jwt/jwts/AccessJWT.java index 046f328..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 { 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 d918715..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,7 +22,6 @@ 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 { 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 da888a7..64e3698 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/GoogleJWT.java @@ -24,7 +24,6 @@ import com.auth0.jwt.interfaces.Clock; import com.auth0.jwt.interfaces.GoogleVerification; import com.auth0.jwt.interfaces.Verification; - import java.util.List; public class GoogleJWT extends JWT.BaseVerification implements GoogleVerification { diff --git a/lib/src/main/java/com/auth0/jwt/jwts/ImplicitJWT.java b/lib/src/main/java/com/auth0/jwt/jwts/ImplicitJWT.java index 708e240..64e031c 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/ImplicitJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/ImplicitJWT.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 ImplicitJWT extends JWT.BaseVerification implements Verification { 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 196981e..dc20a52 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/JWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/JWT.java @@ -28,12 +28,11 @@ import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.interfaces.constants.PublicClaims; 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.Arrays; import java.util.Collections; import java.util.Date; 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 915182e..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 { 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 f03113c..9a2c2ef 100644 --- a/lib/src/main/java/com/auth0/jwt/jwts/ScopedJWT.java +++ b/lib/src/main/java/com/auth0/jwt/jwts/ScopedJWT.java @@ -24,7 +24,6 @@ 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 { diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java b/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java index 8660505..39e4007 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java @@ -2,17 +2,15 @@ import com.auth0.jwt.exceptions.oicmsg_exceptions.HeaderError; import com.auth0.jwt.exceptions.oicmsg_exceptions.SerializationNotPossible; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.security.spec.EllipticCurve; import java.text.ParseException; -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.slf4j.Logger; +import org.slf4j.LoggerFactory; public class ECKey extends Key { diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java b/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java index 75ca00c..57fcd6d 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java @@ -4,11 +4,6 @@ import com.google.common.base.Strings; import com.google.common.primitives.Bytes; import com.google.gson.Gson; -import org.bouncycastle.util.encoders.Base64; -import org.junit.Assert; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -17,6 +12,10 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.bouncycastle.util.encoders.Base64; +import org.junit.Assert; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class Key { @@ -179,7 +178,7 @@ public boolean verify() throws HeaderError { } catch (Exception e) { return false; } - for (String sign : signs){ + for (String sign : signs) { if (((String) item).contains(sign)) { return false; } diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java index 6209bba..c502ced 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java @@ -7,6 +7,17 @@ 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; @@ -21,18 +32,6 @@ import org.slf4j.LoggerFactory; import sun.reflect.generics.reflectiveObjects.NotImplementedException; -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; - public class KeyBundle { final private static Logger logger = LoggerFactory.getLogger(KeyBundle.class); diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/KeyJar.java b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyJar.java index a4cd8f2..59e62a5 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/KeyJar.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyJar.java @@ -5,9 +5,6 @@ import com.auth0.jwt.impl.JWTParser; import com.auth0.jwt.jwts.JWT; import com.google.common.base.Strings; -import org.junit.Assert; -import org.slf4j.LoggerFactory; - import java.security.KeyException; import java.util.ArrayList; import java.util.Arrays; @@ -15,6 +12,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.Assert; +import org.slf4j.LoggerFactory; public class 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 index 1040b2e..8c032a9 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java @@ -3,16 +3,15 @@ import com.auth0.jwt.exceptions.oicmsg_exceptions.DeserializationNotPossible; import com.auth0.jwt.exceptions.oicmsg_exceptions.SerializationNotPossible; import com.google.common.base.Strings; -import org.bouncycastle.util.encoders.Base64; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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; public class RSAKey extends Key { diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java b/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java index f1cb4a0..30b02e6 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java @@ -1,14 +1,13 @@ package com.auth0.jwt.oicmsg; import com.auth0.jwt.exceptions.oicmsg_exceptions.JWKException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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; public class SYMKey extends Key { 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 2965799..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.interfaces.constants.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/main/java/oiccli/client_auth/BearerHeader.java b/lib/src/main/java/oiccli/client_auth/BearerHeader.java deleted file mode 100644 index fa84c1d..0000000 --- a/lib/src/main/java/oiccli/client_auth/BearerHeader.java +++ /dev/null @@ -1,51 +0,0 @@ -package oiccli.client_auth; - -import oiccli.client_info.ClientInfo; - -import java.util.HashMap; -import java.util.Map; - -public class BearerHeader { - - public Map> construct(Map cis, ClientInfo clientInfo, Map requestArgs, Map> httpArgs, - Map args) { - String accessToken; - if (cis != null) { - if (cis.containsKey("accessToken")) { - accessToken = cis.get("accessToken"); - cis.remove(accessToken); - //cis.c_param["access_token"] = SINGLE_OPTIONAL_STRING - } else { - accessToken = requestArgs.get("accessToken"); - requestArgs.remove(accessToken); - - if (accessToken != null) { - accessToken = args.get("accessToken"); - if (accessToken == null) { - accessToken = clientInfo.getStateDb().getTokenInfo(args).get("accessToken"); - } - } - } - } else { - accessToken = args.get("accessToken"); - if (accessToken == null) { - } - } - - String bearer = "Bearer " + accessToken; - if (httpArgs == null) { - Map hMap = new HashMap<>(); - hMap.put("Authorization", bearer); - httpArgs.put("headers", hMap); - } else { - Map hMap = httpArgs.get("headers"); - if (hMap == null) { - hMap = new HashMap<>(); - } - hMap.put("Authorization", bearer); - httpArgs.put("headers", hMap); - } - - return httpArgs; - } -} diff --git a/lib/src/test/java/com/auth0/jwt/ClockImplTest.java b/lib/src/test/java/com/auth0/jwt/ClockImplTest.java index d6f39f1..19c610f 100644 --- a/lib/src/test/java/com/auth0/jwt/ClockImplTest.java +++ b/lib/src/test/java/com/auth0/jwt/ClockImplTest.java @@ -24,9 +24,8 @@ import static org.junit.Assert.assertThat; import com.auth0.jwt.interfaces.Clock; -import org.junit.Test; - import java.util.Date; +import org.junit.Test; public class ClockImplTest { diff --git a/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java b/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java index 45b6f7b..cc93bb8 100644 --- a/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java +++ b/lib/src/test/java/com/auth0/jwt/ConcurrentVerifyTest.java @@ -25,13 +25,6 @@ import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.constants.Constants; import com.auth0.jwt.jwts.JWT; -import net.jodah.concurrentunit.Waiter; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - import java.security.interfaces.ECKey; import java.security.interfaces.RSAKey; import java.util.Collections; @@ -41,6 +34,12 @@ 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; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; //@Ignore("Skipping concurrency tests") public class ConcurrentVerifyTest { diff --git a/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java b/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java index 4315f68..0511c70 100644 --- a/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java +++ b/lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java @@ -34,6 +34,9 @@ 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; @@ -42,10 +45,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import java.nio.charset.StandardCharsets; -import java.util.Date; -import java.util.Map; - public class JWTDecoderTest { @Rule diff --git a/lib/src/test/java/com/auth0/jwt/JWTTest.java b/lib/src/test/java/com/auth0/jwt/JWTTest.java index d057b5a..238e1de 100644 --- a/lib/src/test/java/com/auth0/jwt/JWTTest.java +++ b/lib/src/test/java/com/auth0/jwt/JWTTest.java @@ -21,12 +21,11 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.jwts.JWT; +import java.util.Date; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.util.Date; - public class JWTTest { @Rule diff --git a/lib/src/test/java/com/auth0/jwt/JsonMatcher.java b/lib/src/test/java/com/auth0/jwt/JsonMatcher.java index c322da4..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 { diff --git a/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java b/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java index febcf59..f26196b 100644 --- a/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java +++ b/lib/src/test/java/com/auth0/jwt/MainTestSignatures.java @@ -34,13 +34,12 @@ import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.GoogleJWT; import com.auth0.jwt.jwts.JWT; -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 { 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/algorithms/AlgorithmTest.java b/lib/src/test/java/com/auth0/jwt/algorithms/AlgorithmTest.java index eb26e63..3020751 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/AlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/AlgorithmTest.java @@ -28,10 +28,6 @@ import com.auth0.jwt.interfaces.ECDSAKeyProvider; import com.auth0.jwt.interfaces.RSAKeyProvider; -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.ECPrivateKey; @@ -39,6 +35,9 @@ 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; public class AlgorithmTest { 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 52ee0da..fa4b0af 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/ECDSAAlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/ECDSAAlgorithmTest.java @@ -39,14 +39,6 @@ import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.ECDSAKeyProvider; import com.auth0.jwt.jwts.JWT; -import org.apache.commons.codec.binary.Base64; -import org.hamcrest.Matchers; -import org.hamcrest.collection.IsIn; -import org.junit.Assert; -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; @@ -58,6 +50,13 @@ 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; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; @SuppressWarnings("deprecation") public class ECDSAAlgorithmTest { diff --git a/lib/src/test/java/com/auth0/jwt/algorithms/ECDSABouncyCastleProviderTests.java b/lib/src/test/java/com/auth0/jwt/algorithms/ECDSABouncyCastleProviderTests.java index 79a2dc9..4e7348d 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/ECDSABouncyCastleProviderTests.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/ECDSABouncyCastleProviderTests.java @@ -44,14 +44,6 @@ import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.ECDSAKeyProvider; import com.auth0.jwt.jwts.JWT; -import org.apache.commons.codec.binary.Base64; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.junit.AfterClass; -import org.junit.BeforeClass; -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; @@ -64,6 +56,13 @@ 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; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; public class ECDSABouncyCastleProviderTests { diff --git a/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java b/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java index a6af171..503d540 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java @@ -36,15 +36,14 @@ import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.jwts.JWT; -import org.apache.commons.codec.binary.Base64; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; +import org.apache.commons.codec.binary.Base64; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; public class HMACAlgorithmTest { 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 c6c7a4b..8178b9b 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/RSAAlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/RSAAlgorithmTest.java @@ -39,11 +39,6 @@ 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.InvalidKeyException; import java.security.NoSuchAlgorithmException; @@ -53,6 +48,10 @@ import java.security.interfaces.RSAKey; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; +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 0f342fd..fdc54ce 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/AccessJwtCreatorTest.java @@ -27,20 +27,19 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.interfaces.constants.Constants; -import com.auth0.jwt.interfaces.constants.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.AccessJWT; import com.auth0.jwt.jwts.JWT; -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 AccessJwtCreatorTest { 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 d770b1e..119fdd1 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ExtendedJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ExtendedJwtCreatorTest.java @@ -28,19 +28,18 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.interfaces.constants.Constants; 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.jwts.ExtendedJWT; import com.auth0.jwt.jwts.JWT; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; public class ExtendedJwtCreatorTest { diff --git a/lib/src/test/java/com/auth0/jwt/creators/FbJwtCreatorTest.java b/lib/src/test/java/com/auth0/jwt/creators/FbJwtCreatorTest.java index 51f1627..9926c8b 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/FbJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/FbJwtCreatorTest.java @@ -33,13 +33,12 @@ import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.FbJWT; import com.auth0.jwt.jwts.JWT; -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 FbJwtCreatorTest { 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 448967b..0cb98e0 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/GoogleJwtCreatorTest.java @@ -34,13 +34,12 @@ import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.GoogleJWT; import com.auth0.jwt.jwts.JWT; -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 GoogleJwtCreatorTest { 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 f4538af..f0b8592 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ImplicitJwtCreatorTest.java @@ -26,20 +26,19 @@ import com.auth0.jwt.TimeUtil; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; -import com.auth0.jwt.interfaces.constants.Constants; -import com.auth0.jwt.interfaces.constants.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 java.util.Date; +import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.util.Date; -import java.util.Map; - public class ImplicitJwtCreatorTest { @Rule 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 4d7862c..7d3aaf6 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/JWTCreatorTest.java @@ -32,17 +32,16 @@ import com.auth0.jwt.interfaces.ECDSAKeyProvider; import com.auth0.jwt.interfaces.RSAKeyProvider; import com.auth0.jwt.interfaces.constants.Constants; -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.interfaces.ECPrivateKey; import java.security.interfaces.RSAPrivateKey; import java.util.Date; import java.util.HashMap; import java.util.Map; +import org.apache.commons.codec.binary.Base64; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; public class JWTCreatorTest { 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 b5ba508..e52393f 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/RiscJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/RiscJwtCreatorTest.java @@ -27,20 +27,19 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.interfaces.constants.Constants; -import com.auth0.jwt.interfaces.constants.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 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 RiscJwtCreatorTest { 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 79b3110..d48ae2d 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ScopedJwtCreatorTest.java @@ -27,20 +27,19 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.TokenExpiredException; -import com.auth0.jwt.interfaces.constants.Constants; -import com.auth0.jwt.interfaces.constants.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 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 ScopedJwtCreatorTest { 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 94d84dc..5221c1b 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/BasicHeaderTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/BasicHeaderTest.java @@ -28,14 +28,13 @@ 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; - 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 8abfc81..7429937 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/ClaimsHolderTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/ClaimsHolderTest.java @@ -24,11 +24,10 @@ import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; -import org.hamcrest.collection.IsMapContaining; -import org.junit.Test; - import java.util.HashMap; import java.util.Map; +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 c8c782f..ddc009a 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/HeaderDeserializerTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/HeaderDeserializerTest.java @@ -40,15 +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; - public class HeaderDeserializerTest { @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 f3e0779..66f0deb 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/JsonNodeClaimTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/JsonNodeClaimTest.java @@ -45,13 +45,6 @@ import com.fasterxml.jackson.databind.node.MissingNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ObjectNode; -import org.hamcrest.collection.IsMapContaining; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.mockito.ArgumentMatchers; - import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -59,6 +52,12 @@ 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; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.ArgumentMatchers; public class JsonNodeClaimTest { 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 114ccc0..fb641b6 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/PayloadDeserializerTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/PayloadDeserializerTest.java @@ -44,6 +44,12 @@ 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; @@ -52,13 +58,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - 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 bae5bcc..ac054ad 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/PayloadImplTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/PayloadImplTest.java @@ -30,6 +30,10 @@ 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 org.junit.Before; @@ -38,11 +42,6 @@ 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; - public class PayloadImplTest { @Rule diff --git a/lib/src/test/java/com/auth0/jwt/impl/PayloadSerializerTest.java b/lib/src/test/java/com/auth0/jwt/impl/PayloadSerializerTest.java index 3275517..15c91b4 100644 --- a/lib/src/test/java/com/auth0/jwt/impl/PayloadSerializerTest.java +++ b/lib/src/test/java/com/auth0/jwt/impl/PayloadSerializerTest.java @@ -29,14 +29,13 @@ 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 org.junit.Before; +import org.junit.Test; public class PayloadSerializerTest { From 7418d98a8009691e898718a14c84357cf88426e8 Mon Sep 17 00:00:00 2001 From: Justin Dahmubed Date: Thu, 25 Jan 2018 16:28:26 -0800 Subject: [PATCH 6/7] Cleanup --- .../auth0/jwt/creators/AccessJwtCreator.java | 1 + .../jwt/creators/ImplicitJwtCreator.java | 1 + .../java/com/auth0/jwt/jwts/GoogleJWT.java | 1 + .../auth0/jwt/algorithms/AlgorithmTest.java | 1 + .../jwt/algorithms/HMACAlgorithmTest.java | 1 + .../jwt/creators/ExtendedJwtCreatorTest.java | 71 +++++++++---------- .../VerificationAndAssertionTest.java | 1 + 7 files changed, 41 insertions(+), 36 deletions(-) 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 a6b6aaa..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,6 +21,7 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; +import com.auth0.jwt.interfaces.constants.Constants; import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.JWT; import java.util.Date; 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 9e66d66..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,6 +21,7 @@ import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; +import com.auth0.jwt.interfaces.constants.Constants; import com.auth0.jwt.interfaces.constants.PublicClaims; import com.auth0.jwt.jwts.JWT; import java.util.Date; 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 64e3698..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,6 +24,7 @@ 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 { 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 3020751..aaa2e67 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/AlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/AlgorithmTest.java @@ -28,6 +28,7 @@ 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; 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 503d540..7346315 100644 --- a/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java +++ b/lib/src/test/java/com/auth0/jwt/algorithms/HMACAlgorithmTest.java @@ -35,6 +35,7 @@ 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 java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; 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 119fdd1..6c93219 100644 --- a/lib/src/test/java/com/auth0/jwt/creators/ExtendedJwtCreatorTest.java +++ b/lib/src/test/java/com/auth0/jwt/creators/ExtendedJwtCreatorTest.java @@ -21,7 +21,6 @@ import static com.auth0.jwt.TimeUtil.generateRandomExpDateInFuture; import static com.auth0.jwt.TimeUtil.generateRandomIatDateInPast; -import static com.auth0.jwt.creators.GoogleJwtCreatorTest.NAME; import static com.auth0.jwt.creators.GoogleJwtCreatorTest.verifyClaims; import static java.util.Arrays.asList; @@ -61,11 +60,11 @@ public void testExtendedJwtCreatorAllStandardClaimsMustBeRequired() throws Excep .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -83,11 +82,11 @@ public void testExtendedJwtCreatorBase16Encoding() throws Exception { .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .signBase16Encoding(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode16Bytes(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -105,11 +104,11 @@ public void testExtendedJwtCreatorBase32Encoding() throws Exception { .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .signBase32Encoding(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode32Bytes(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -129,11 +128,11 @@ public void testExtendedJwtCreatorInvalidIssuer() throws Exception { .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -151,11 +150,11 @@ public void testExtendedJwtCreatorInvalidPicture() throws Exception { .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -173,11 +172,11 @@ public void testExtendedJwtCreatorInvalidEmail() throws Exception { .withAudience(Constants.AUDIENCE) .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -197,11 +196,11 @@ public void testExtendedJwtCreatorInvalidAudience() throws Exception { .withAudience("invalid") .withExp(exp) .withIat(iat) - .withName(NAME) + .withName(Constants.NAME) .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -225,7 +224,7 @@ public void testExtendedJwtCreatorInvalidName() throws Exception { .sign(algorithm); GoogleVerification verification = ExtendedJWT.require(algorithm); JWT verifier = verification.createVerifierForExtended(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -246,13 +245,13 @@ public void testExtendedJwtCreatorNoneAlgorithmNotAllowed() throws Exception { .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(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -271,13 +270,13 @@ public void testExtendedJwtCreatorNoneAlgorithmNotSpecifiedButStillNotAllowed() .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(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -293,13 +292,13 @@ public void testExtendedJwtCreatorNoneAlgorithmAllowed() throws Exception { .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(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); Map claims = jwt.getClaims(); verifyClaims(claims, exp); @@ -317,13 +316,13 @@ public void testExtendedJwtCreatorNonStandardClaimStringValue() throws Exception .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(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -339,13 +338,13 @@ public void testExtendedJwtCreatorNonStandardClaimIntegerValue() throws Exceptio .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(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -361,13 +360,13 @@ public void testExtendedJwtCreatorNonStandardClaimLongValue() throws Exception { .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(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -383,13 +382,13 @@ public void testExtendedJwtCreatorNonStandardClaimDoubleValue() throws Exception .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(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -405,13 +404,13 @@ public void testExtendedJwtCreatorNonStandardClaimBooleanValue() throws Exceptio .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(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -427,13 +426,13 @@ public void testExtendedJwtCreatorNonStandardClaimDateValue() throws Exception { .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(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } @@ -458,13 +457,13 @@ public void testExtendedJwtCreatorExpTimeHasPassed() throws Exception { .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(Constants.PICTURE, Constants.EMAIL, asList(Constants.ISSUER), asList(Constants.AUDIENCE), - NAME, 1, 1, 1).build(); + Constants.NAME, 1, 1, 1).build(); DecodedJWT jwt = verifier.decode(token); } } 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 deeea6a..af2ff26 100644 --- a/lib/src/test/java/com/auth0/jwt/verification/VerificationAndAssertionTest.java +++ b/lib/src/test/java/com/auth0/jwt/verification/VerificationAndAssertionTest.java @@ -27,6 +27,7 @@ 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 org.junit.Rule; From eba52d964233c3311139ea98300dc71b24fe098c Mon Sep 17 00:00:00 2001 From: Justin Dahmubed Date: Wed, 7 Feb 2018 16:31:22 -0800 Subject: [PATCH 7/7] Added comments for javadocs --- .../main/java/com/auth0/jwt/oicmsg/ECKey.java | 49 +++++++ .../main/java/com/auth0/jwt/oicmsg/Key.java | 45 +++++- .../java/com/auth0/jwt/oicmsg/KeyBundle.java | 137 +++++++++++++++++- .../java/com/auth0/jwt/oicmsg/KeyJar.java | 91 ++++++++++++ .../java/com/auth0/jwt/oicmsg/RSAKey.java | 57 +++++++- .../java/com/auth0/jwt/oicmsg/SYMKey.java | 18 +++ 6 files changed, 387 insertions(+), 10 deletions(-) diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java b/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java index 39e4007..c504c0e 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/ECKey.java @@ -12,6 +12,19 @@ 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; @@ -20,6 +33,7 @@ public class ECKey extends Key { 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")); @@ -50,6 +64,27 @@ 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)) { @@ -88,6 +123,14 @@ public List getKey(boolean isPrivate) { } } + /** + * 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(); @@ -105,6 +148,11 @@ public Object serialize(boolean isPrivate) throws SerializationNotPossible { 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? @@ -116,6 +164,7 @@ public List getDecryptionKey() { } public List getEncryptionKey(boolean isPrivate) { + //both for encryption and decryption. return this.getKey(isPrivate); } diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java b/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java index 57fcd6d..5c708f3 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/Key.java @@ -1,8 +1,6 @@ package com.auth0.jwt.oicmsg; -import com.auth0.jwt.exceptions.oicmsg_exceptions.HeaderError; import com.google.common.base.Strings; -import com.google.common.primitives.Bytes; import com.google.gson.Gson; import java.util.ArrayList; import java.util.Arrays; @@ -12,11 +10,16 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.bouncycastle.util.encoders.Base64; 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); @@ -120,6 +123,12 @@ 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()) { @@ -134,6 +143,10 @@ public Key serialize() { //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); @@ -154,6 +167,13 @@ 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()) { @@ -200,6 +220,11 @@ 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 { @@ -223,6 +248,16 @@ 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; @@ -260,6 +295,10 @@ 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"))); } diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java index c502ced..5f0d861 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyBundle.java @@ -32,6 +32,14 @@ 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); @@ -66,6 +74,19 @@ public class KeyBundle { 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; @@ -138,6 +159,10 @@ public KeyBundle(String source, String fileFormat, List usage) throws Im 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(); @@ -175,6 +200,11 @@ private static List harmonizeUsage(List uses) { 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 { @@ -197,6 +227,13 @@ public void doLocalJwk(String fileName) throws UpdateFailed { } } + /** + * 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); @@ -221,6 +258,12 @@ public void doLocalDer(String fileName, String keyType, List keyUsage) t 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); @@ -289,6 +332,15 @@ public boolean doRemote() throws UpdateFailed, KeyException { 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"); @@ -315,6 +367,12 @@ private boolean upToDate() { 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()) { @@ -348,6 +406,12 @@ public boolean update() { 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(); @@ -366,6 +430,10 @@ public List get(String typ) { } } + /** + * Return all keys after having updated them + * @return List of all keys + */ public List getKeys() { this.upToDate(); return this.keys; @@ -386,6 +454,10 @@ public List getActiveKeys() { 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()); @@ -401,10 +473,11 @@ public String toString() { return this.jwks(); } - public String jwks() { - return jwks(false); - } - + /** + * 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<>(); @@ -419,18 +492,39 @@ public String jwks(boolean isPrivate) { } } + 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)) { @@ -438,6 +532,7 @@ public Key getKeyWithKid(String kid) { } } + //Try updating since there might have been an update to the key file update(); for (Key key : this.keys) { @@ -449,6 +544,11 @@ public Key getKeyWithKid(String kid) { 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<>(); @@ -461,11 +561,24 @@ public List getKids() { 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) { @@ -485,7 +598,15 @@ public void removeOutdated(float after, int when) throws TypeError { } - //----Not part of KeyBundle class, but I thought I should include these methods + /** + * 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; @@ -501,6 +622,12 @@ public KeyBundle keyBundleFromLocalFile(String filename, String type, 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 index 59e62a5..d543839 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/KeyJar.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/KeyJar.java @@ -15,6 +15,9 @@ import org.junit.Assert; import org.slf4j.LoggerFactory; +/** + * A keyjar contains a number of keybundles + */ public class KeyJar { private boolean verifySSL; @@ -30,6 +33,12 @@ public class KeyJar { 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; @@ -42,6 +51,16 @@ public KeyJar() throws ImportException { 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"); @@ -59,6 +78,16 @@ public KeyBundle addUrl(String owner, String url, Map args) thro 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()); @@ -87,6 +116,11 @@ public void addSymmetricKey(String owner, Key key, List usage) throws Im } } + /** + * 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) { @@ -99,10 +133,23 @@ public void addKeyBundle(String owner, KeyBundle keyBundle) { } } + /** + * 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)) { @@ -140,6 +187,7 @@ public List getKeys(String keyUse, String keyType, String owner, String kid } for (Key key : keyList) { + //Skip inactive keys unless for signature verification if (key.getInactiveSince() == 0 && !SIG.equals(keyUse)) { continue; } @@ -157,6 +205,7 @@ public List getKeys(String keyUse, String keyType, String owner, String kid } 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<>(); @@ -172,6 +221,7 @@ public List getKeys(String keyUse, String keyType, String owner, String kid 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)) { @@ -256,6 +306,14 @@ public String matchOwner(String url) throws KeyException { 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); @@ -266,6 +324,12 @@ public void loadKeys(Map pcr, String issuer, boolean shouldRepla //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)) { @@ -276,6 +340,13 @@ public KeyBundle find(String source, String issuer) { 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)) { @@ -295,6 +366,12 @@ 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); @@ -310,6 +387,14 @@ 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()) { @@ -369,6 +454,12 @@ public List addKey(List keys, String owner, String use, String keyType 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(); diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java b/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java index 8c032a9..3d90f92 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/RSAKey.java @@ -13,9 +13,33 @@ 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; @@ -31,7 +55,10 @@ public class RSAKey extends 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; @@ -58,9 +85,17 @@ 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); @@ -96,6 +131,7 @@ public void deserialize() throws DeserializationNotPossible { } else if (this.x5c != null) { Base64.decode((int) this.x5c.getBytes()[0]); + //verify the cert thumbprint if (this.x5t != null) { if (Base64.decode() !=) @@ -103,6 +139,7 @@ public void deserialize() throws DeserializationNotPossible { this.key =; this.split(); + //verify chain if (this.x5c.length() > 1) { } @@ -111,6 +148,13 @@ public void deserialize() throws 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(); @@ -171,14 +215,23 @@ private void split() { } } -} - + /** + * 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(); diff --git a/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java b/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java index 30b02e6..5b1f263 100644 --- a/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java +++ b/lib/src/main/java/com/auth0/jwt/oicmsg/SYMKey.java @@ -9,6 +9,16 @@ 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); @@ -46,6 +56,14 @@ public Map serialize(boolean isPrivate) { 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();