1 package com.atlassian.asap.core.client;
2
3 import com.atlassian.asap.api.Jwt;
4 import com.atlassian.asap.api.JwtBuilder;
5 import com.atlassian.asap.api.client.http.AuthorizationHeaderGenerator;
6 import com.atlassian.asap.api.exception.CannotRetrieveKeyException;
7 import com.atlassian.asap.api.exception.InvalidTokenException;
8 import com.atlassian.asap.core.client.http.AuthorizationHeaderGeneratorImpl;
9 import org.apache.commons.io.IOUtils;
10 import org.apache.http.client.methods.CloseableHttpResponse;
11 import org.apache.http.client.methods.HttpGet;
12 import org.apache.http.impl.client.CloseableHttpClient;
13 import org.apache.http.impl.client.HttpClientBuilder;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
16
17 import java.io.IOException;
18 import java.io.InputStreamReader;
19 import java.net.URI;
20 import java.nio.charset.StandardCharsets;
21
22
23
24
25 public class SimpleClient {
26 private static final Logger logger = LoggerFactory.getLogger(SimpleClient.class);
27
28 private final String issuer;
29 private final String keyId;
30 private final String audience;
31 private final AuthorizationHeaderGenerator authorizationHeaderGenerator;
32
33
34
35
36
37
38
39 public SimpleClient(String issuer, String keyId, String audience, URI privateKeyPath) {
40 this.issuer = issuer;
41 this.keyId = keyId;
42 this.audience = audience;
43 this.authorizationHeaderGenerator = AuthorizationHeaderGeneratorImpl.createDefault(privateKeyPath);
44 }
45
46
47
48
49
50
51
52
53 public void execute(URI resourceServerUrl) throws CannotRetrieveKeyException, InvalidTokenException {
54 Jwt jwt = JwtBuilder.newJwt()
55 .keyId(keyId)
56 .audience(audience)
57 .issuer(issuer)
58 .build();
59
60 logger.info("Making a GET request to {} using access token {}", resourceServerUrl, jwt);
61 HttpGet httpGet = new HttpGet(resourceServerUrl);
62 httpGet.setHeader("Authorization", authorizationHeaderGenerator.generateAuthorizationHeader(jwt));
63
64 try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();
65 CloseableHttpResponse response = httpClient.execute(httpGet);
66 InputStreamReader reader = new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8)) {
67 logger.info("Request completed status={} -- response body: {}",
68 response.getStatusLine().getStatusCode(), IOUtils.toString(reader));
69 } catch (IOException ex) {
70 logger.error("Error accessing resource server", ex);
71 }
72 }
73 }