@Override public Jwk get(final String keyId) throws JwkException { try { String cacheKey = keyId == null ? NULL_KID_KEY : keyId; return cache.get(cacheKey, new Callable<Jwk>() { @Override public Jwk call() throws Exception { return provider.get(keyId); } }); } catch (ExecutionException e) { throw new SigningKeyNotFoundException("Failed to get key with kid " + keyId, e); } }
private List<Jwk> getAll() throws SigningKeyNotFoundException { List<Jwk> jwks = Lists.newArrayList(); @SuppressWarnings("unchecked") final List<Map<String, Object>> keys = (List<Map<String, Object>>) getJwks().get("keys"); if (keys == null || keys.isEmpty()) { throw new SigningKeyNotFoundException("No keys found in " + url.toString(), null); } try { for (Map<String, Object> values : keys) { jwks.add(Jwk.fromValues(values)); } } catch (IllegalArgumentException e) { throw new SigningKeyNotFoundException("Failed to parse jwk from json", e); } return jwks; }
private Map<String, Object> getJwks() throws SigningKeyNotFoundException { try { final URLConnection c = this.url.openConnection(); if (connectTimeout != null) { c.setConnectTimeout(connectTimeout); } if (readTimeout != null) { c.setReadTimeout(readTimeout); } final InputStream inputStream = c.getInputStream(); final JsonFactory factory = new JsonFactory(); final JsonParser parser = factory.createParser(inputStream); final TypeReference<Map<String, Object>> typeReference = new TypeReference<Map<String, Object>>() { }; return new ObjectMapper().reader().readValue(parser, typeReference); } catch (IOException e) { throw new SigningKeyNotFoundException("Cannot obtain jwks from url " + url.toString(), e); } }
@Override public Jwk get(String keyId) throws JwkException { final List<Jwk> jwks = getAll(); if (keyId == null && jwks.size() == 1) { return jwks.get(0); } if (keyId != null) { for (Jwk jwk : jwks) { if (keyId.equals(jwk.getId())) { return jwk; } } } throw new SigningKeyNotFoundException("No key found in " + url.toString() + " with kid " + keyId, null); } }
@Test public void shouldFailToGetSingleWhenNotExists() throws Exception { expectedException.expect(SigningKeyNotFoundException.class); when(fallback.get(anyString())).thenThrow(new SigningKeyNotFoundException("TEST!", null)); provider.get(KID); }
@Test public void shouldUseCachedValue() throws Exception { when(fallback.get(eq(KID))).thenReturn(jwk).thenThrow(new SigningKeyNotFoundException("TEST!", null)); provider.get(KID); assertThat(provider.get(KID), equalTo(jwk)); verify(fallback, only()).get(KID); }