JWKSetCacheService.java

  1. /*******************************************************************************
  2.  * Copyright 2017 The MIT Internet Trust Consortium
  3.  *
  4.  * Portions copyright 2011-2013 The MITRE Corporation
  5.  *
  6.  * Licensed under the Apache License, Version 2.0 (the "License");
  7.  * you may not use this file except in compliance with the License.
  8.  * You may obtain a copy of the License at
  9.  *
  10.  *   http://www.apache.org/licenses/LICENSE-2.0
  11.  *
  12.  * Unless required by applicable law or agreed to in writing, software
  13.  * distributed under the License is distributed on an "AS IS" BASIS,
  14.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15.  * See the License for the specific language governing permissions and
  16.  * limitations under the License.
  17.  *******************************************************************************/
  18. /**
  19.  *
  20.  */
  21. package org.mitre.jwt.signer.service.impl;

  22. import java.util.concurrent.ExecutionException;
  23. import java.util.concurrent.TimeUnit;

  24. import org.apache.http.client.HttpClient;
  25. import org.apache.http.impl.client.HttpClientBuilder;
  26. import org.mitre.jose.keystore.JWKSetKeyStore;
  27. import org.mitre.jwt.encryption.service.JWTEncryptionAndDecryptionService;
  28. import org.mitre.jwt.encryption.service.impl.DefaultJWTEncryptionAndDecryptionService;
  29. import org.mitre.jwt.signer.service.JWTSigningAndValidationService;
  30. import org.slf4j.Logger;
  31. import org.slf4j.LoggerFactory;
  32. import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
  33. import org.springframework.stereotype.Service;
  34. import org.springframework.web.client.RestClientException;
  35. import org.springframework.web.client.RestTemplate;

  36. import com.google.common.cache.CacheBuilder;
  37. import com.google.common.cache.CacheLoader;
  38. import com.google.common.cache.LoadingCache;
  39. import com.google.common.util.concurrent.UncheckedExecutionException;
  40. import com.google.gson.JsonParseException;
  41. import com.nimbusds.jose.jwk.JWKSet;

  42. /**
  43.  *
  44.  * Creates a caching map of JOSE signers/validators and encrypters/decryptors
  45.  * keyed on the JWK Set URI. Dynamically loads JWK Sets to create the services.
  46.  *
  47.  * @author jricher
  48.  *
  49.  */
  50. @Service
  51. public class JWKSetCacheService {

  52.     /**
  53.      * Logger for this class
  54.      */
  55.     private static final Logger logger = LoggerFactory.getLogger(JWKSetCacheService.class);

  56.     // map of jwk set uri -> signing/validation service built on the keys found in that jwk set
  57.     private LoadingCache<String, JWTSigningAndValidationService> validators;

  58.     // map of jwk set uri -> encryption/decryption service built on the keys found in that jwk set
  59.     private LoadingCache<String, JWTEncryptionAndDecryptionService> encrypters;

  60.     public JWKSetCacheService() {
  61.         this.validators = CacheBuilder.newBuilder()
  62.                 .expireAfterWrite(1, TimeUnit.HOURS) // expires 1 hour after fetch
  63.                 .maximumSize(100)
  64.                 .build(new JWKSetVerifierFetcher(HttpClientBuilder.create().useSystemProperties().build()));
  65.         this.encrypters = CacheBuilder.newBuilder()
  66.                 .expireAfterWrite(1, TimeUnit.HOURS) // expires 1 hour after fetch
  67.                 .maximumSize(100)
  68.                 .build(new JWKSetEncryptorFetcher(HttpClientBuilder.create().useSystemProperties().build()));
  69.     }

  70.     /**
  71.      * @param jwksUri
  72.      * @return
  73.      * @throws ExecutionException
  74.      * @see com.google.common.cache.Cache#get(java.lang.Object)
  75.      */
  76.     public JWTSigningAndValidationService getValidator(String jwksUri) {
  77.         try {
  78.             return validators.get(jwksUri);
  79.         } catch (UncheckedExecutionException | ExecutionException e) {
  80.             logger.warn("Couldn't load JWK Set from " + jwksUri + ": " + e.getMessage());
  81.             return null;
  82.         }
  83.     }

  84.     public JWTEncryptionAndDecryptionService getEncrypter(String jwksUri) {
  85.         try {
  86.             return encrypters.get(jwksUri);
  87.         } catch (UncheckedExecutionException | ExecutionException e) {
  88.             logger.warn("Couldn't load JWK Set from " + jwksUri + ": " + e.getMessage());
  89.             return null;
  90.         }
  91.     }

  92.     /**
  93.      * @author jricher
  94.      *
  95.      */
  96.     private class JWKSetVerifierFetcher extends CacheLoader<String, JWTSigningAndValidationService> {
  97.         private HttpComponentsClientHttpRequestFactory httpFactory;
  98.         private RestTemplate restTemplate;

  99.         JWKSetVerifierFetcher(HttpClient httpClient) {
  100.             this.httpFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
  101.             this.restTemplate = new RestTemplate(httpFactory);
  102.         }

  103.         /**
  104.          * Load the JWK Set and build the appropriate signing service.
  105.          */
  106.         @Override
  107.         public JWTSigningAndValidationService load(String key) throws Exception {
  108.             String jsonString = restTemplate.getForObject(key, String.class);
  109.             JWKSet jwkSet = JWKSet.parse(jsonString);

  110.             JWKSetKeyStore keyStore = new JWKSetKeyStore(jwkSet);

  111.             JWTSigningAndValidationService service = new DefaultJWTSigningAndValidationService(keyStore);

  112.             return service;
  113.         }

  114.     }

  115.     /**
  116.      * @author jricher
  117.      *
  118.      */
  119.     private class JWKSetEncryptorFetcher extends CacheLoader<String, JWTEncryptionAndDecryptionService> {
  120.         private HttpComponentsClientHttpRequestFactory httpFactory;
  121.         private RestTemplate restTemplate;

  122.         public JWKSetEncryptorFetcher(HttpClient httpClient) {
  123.             this.httpFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
  124.             this.restTemplate = new RestTemplate(httpFactory);
  125.         }

  126.         /* (non-Javadoc)
  127.          * @see com.google.common.cache.CacheLoader#load(java.lang.Object)
  128.          */
  129.         @Override
  130.         public JWTEncryptionAndDecryptionService load(String key) throws Exception {
  131.             try {
  132.                 String jsonString = restTemplate.getForObject(key, String.class);
  133.                 JWKSet jwkSet = JWKSet.parse(jsonString);

  134.                 JWKSetKeyStore keyStore = new JWKSetKeyStore(jwkSet);

  135.                 JWTEncryptionAndDecryptionService service = new DefaultJWTEncryptionAndDecryptionService(keyStore);

  136.                 return service;
  137.             } catch (JsonParseException | RestClientException e) {
  138.                 throw new IllegalArgumentException("Unable to load JWK Set");
  139.             }
  140.         }
  141.     }

  142. }