AuthorizationCodeVerifier implements CodeVerifier { @Override public boolean verify(CodeChallenge codeChallenge, String providedCodeVerifier) { try { if (providedCodeVerifier.isEmpty() && !codeChallenge.isProvided()) { return true; } if (providedCodeVerifier.isEmpty() && codeChallenge.isProvided()) { return false; } if (!providedCodeVerifier.isEmpty() && !codeChallenge.isProvided()) { return false; } if (codeChallenge.method.equals("plain")) { return codeChallenge.transformedCodeChallenge.equals(providedCodeVerifier); } if (codeChallenge.method.equals("S256")) { byte[] hashed = MessageDigest.getInstance("SHA-256").digest(providedCodeVerifier.getBytes(StandardCharsets.UTF_8)); String transformedCodeVerifier = BaseEncoding.base64Url().encode(hashed); return transformedCodeVerifier.equals(codeChallenge.transformedCodeChallenge); } return false; } catch (NoSuchAlgorithmException e) { return false; } }  @Override boolean verify(CodeChallenge codeChallenge, String providedCodeVerifier);  }
@Test public void happyPath() throws Exception { String codeVerifierValue = "::code::"; byte[] hashedCodeChallenge = MessageDigest.getInstance("SHA-256").digest(codeVerifierValue.getBytes(StandardCharsets.UTF_8)); String transformedCodeChallenge = BaseEncoding.base64().encode(hashedCodeChallenge); CodeChallenge codeChallenge = new CodeChallenge(transformedCodeChallenge, "S256"); assertTrue(codeVerifier.verify(codeChallenge, codeVerifierValue)); }
@Test public void wrongCodeVerifierValue() throws Exception { String codeVerifierValue = "::code::"; byte[] hashedCodeChallenge = MessageDigest.getInstance("SHA-256").digest(codeVerifierValue.getBytes(StandardCharsets.UTF_8)); String transformedCodeChallenge = BaseEncoding.base64Url().encode(hashedCodeChallenge); CodeChallenge codeChallenge = new CodeChallenge(transformedCodeChallenge, "S256"); assertFalse(codeVerifier.verify(codeChallenge, "::codee::")); }
@Test public void usingPlainMethod() throws Exception { CodeChallenge codeChallenge = new CodeChallenge("::code::", "plain"); assertTrue(codeVerifier.verify(codeChallenge, "::code::")); }
@Test public void codeVerifierProvidedButNoCodeChallengeFound() throws Exception { assertFalse(codeVerifier.verify(new CodeChallenge("", ""), "::code::")); }
@Test public void codeChallengeProvidedButNoCodeVerifier() throws Exception { CodeChallenge codeChallenge = new CodeChallenge("::code::", "plain"); assertFalse(codeVerifier.verify(codeChallenge, "")); }