@Override
public RegisteredClient load(ServerConfiguration serverConfig) throws Exception {
RestTemplate restTemplate = new RestTemplate(httpFactory);
RegisteredClient knownClient = registeredClientService.getByIssuer(serverConfig.getIssuer());
if (knownClient == null) {
// dynamically register this client
JsonObject jsonRequest = ClientDetailsEntityJsonProcessor.serialize(template);
String serializedClient = gson.toJson(jsonRequest);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(serializedClient, headers);
String registered = restTemplate.postForObject(serverConfig.getRegistrationEndpointUri(), entity, String.class);
// TODO: handle HTTP errors
RegisteredClient client = ClientDetailsEntityJsonProcessor.parseRegistered(registered);
// save this client for later
registeredClientService.save(serverConfig.getIssuer(), client);
return client;
} else {
if (knownClient.getClientId() == null) {
// load this client's information from the server
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, knownClient.getRegistrationAccessToken()));
headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
String registered = restTemplate.exchange(knownClient.getRegistrationClientUri(), HttpMethod.GET, entity, String.class).getBody();
// TODO: handle HTTP errors
RegisteredClient client = ClientDetailsEntityJsonProcessor.parseRegistered(registered);
return client;
} else {
// it's got a client ID from the store, don't bother trying to load it
return knownClient;