|
| 1 | +package cloud.stackit.sdk.core; |
| 2 | + |
| 3 | +import cloud.stackit.sdk.core.model.ServiceAccountCredentials; |
| 4 | +import cloud.stackit.sdk.core.model.ServiceAccountKey; |
| 5 | +import com.auth0.jwt.JWT; |
| 6 | +import com.auth0.jwt.algorithms.Algorithm; |
| 7 | +import com.google.gson.Gson; |
| 8 | +import com.google.gson.annotations.SerializedName; |
| 9 | +import okhttp3.*; |
| 10 | + |
| 11 | +import java.io.IOException; |
| 12 | +import java.io.InputStream; |
| 13 | +import java.io.InputStreamReader; |
| 14 | +import java.net.HttpURLConnection; |
| 15 | +import java.nio.charset.StandardCharsets; |
| 16 | +import java.security.interfaces.RSAPrivateKey; |
| 17 | +import java.security.interfaces.RSAPublicKey; |
| 18 | +import java.util.Date; |
| 19 | +import java.util.HashMap; |
| 20 | +import java.util.Map; |
| 21 | +import java.util.UUID; |
| 22 | +import java.util.concurrent.TimeUnit; |
| 23 | + |
| 24 | +public class KeyFlowAuthenticator { |
| 25 | + private final String REFRESH_TOKEN = "refresh_token"; |
| 26 | + private final String ASSERTION = "assertion"; |
| 27 | + |
| 28 | + private final OkHttpClient httpClient; |
| 29 | + private final ServiceAccountKey saKey; |
| 30 | + private KeyFlowTokenResponse token; |
| 31 | + private final Gson gson; |
| 32 | + private final String tokenUrl; |
| 33 | + |
| 34 | + private static class KeyFlowTokenResponse { |
| 35 | + @SerializedName("access_token") |
| 36 | + private String accessToken; |
| 37 | + @SerializedName("refresh_token") |
| 38 | + private String refreshToken; |
| 39 | + @SerializedName("expires_in") |
| 40 | + private long expiresIn; |
| 41 | + @SerializedName("scope") |
| 42 | + private String scope; |
| 43 | + @SerializedName("token_type") |
| 44 | + private String tokenType; |
| 45 | + |
| 46 | + public boolean isExpired() { |
| 47 | + return expiresIn < new Date().toInstant().minusSeconds(60).getEpochSecond(); |
| 48 | + } |
| 49 | + |
| 50 | + public String getAccessToken() { |
| 51 | + return accessToken; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + public KeyFlowAuthenticator(ServiceAccountKey saKey) { |
| 56 | + this.saKey = saKey; |
| 57 | + this.gson = new Gson(); |
| 58 | + this.httpClient = new OkHttpClient.Builder() |
| 59 | + .connectTimeout(10, TimeUnit.SECONDS) |
| 60 | + .writeTimeout(10, TimeUnit.SECONDS) |
| 61 | + .readTimeout(30, TimeUnit.SECONDS) |
| 62 | + .build(); |
| 63 | + this.tokenUrl = "https://service-account.api.stackit.cloud/token"; |
| 64 | + createAccessToken(); |
| 65 | + } |
| 66 | + |
| 67 | + |
| 68 | + public synchronized String getAccessToken() throws IOException { |
| 69 | + if (token == null || token.isExpired()) { |
| 70 | + createAccessTokenWithRefreshToken(); |
| 71 | + } |
| 72 | + return token.getAccessToken(); |
| 73 | + } |
| 74 | + |
| 75 | + private void createAccessToken() { |
| 76 | + String grant = "urn:ietf:params:oauth:grant-type:jwt-bearer"; |
| 77 | + String assertion = generateSelfSignedJWT(); |
| 78 | + try(Response response = requestToken(grant, assertion).execute()) { |
| 79 | + parseTokenResponse(response); |
| 80 | + } catch (IOException | ApiException e) { |
| 81 | + e.printStackTrace(); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + private synchronized void createAccessTokenWithRefreshToken() throws IOException { |
| 86 | + String refreshToken = token.refreshToken; |
| 87 | + try (Response response = requestToken(REFRESH_TOKEN, refreshToken).execute()) { |
| 88 | + parseTokenResponse(response); |
| 89 | + } catch (ApiException e) { |
| 90 | + e.printStackTrace(); |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + private synchronized void parseTokenResponse(Response response) throws ApiException { |
| 95 | + if (response.code() != HttpURLConnection.HTTP_OK) { |
| 96 | + String body = null; |
| 97 | + if (response.body() != null) { |
| 98 | + body = response.body().toString(); |
| 99 | + response.body().close(); |
| 100 | + } |
| 101 | + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), body); |
| 102 | + } |
| 103 | + if (response.body() == null) { |
| 104 | + throw new ApiException("body from token creation is null"); |
| 105 | + } |
| 106 | + |
| 107 | + token = gson.fromJson(new InputStreamReader(response.body().byteStream(), StandardCharsets.UTF_8), KeyFlowTokenResponse.class); |
| 108 | + token.expiresIn = JWT.decode(token.accessToken).getExpiresAt().toInstant().getEpochSecond(); |
| 109 | + response.body().close(); |
| 110 | + } |
| 111 | + |
| 112 | + private Call requestToken(String grant, String assertion) throws IOException { |
| 113 | + FormBody.Builder bodyBuilder = new FormBody.Builder(); |
| 114 | + bodyBuilder.addEncoded("grant_type", grant); |
| 115 | + if (grant.equals(REFRESH_TOKEN)) { |
| 116 | + bodyBuilder.addEncoded(REFRESH_TOKEN, assertion); |
| 117 | + } else { |
| 118 | + bodyBuilder.addEncoded(ASSERTION, assertion); |
| 119 | + } |
| 120 | + FormBody body = bodyBuilder.build(); |
| 121 | + |
| 122 | + Request request = new Request.Builder() |
| 123 | + .url(tokenUrl) |
| 124 | + .post(body) |
| 125 | + .addHeader("Content-Type", "application/x-www-form-urlencoded") |
| 126 | + .build(); |
| 127 | + return httpClient.newCall(request); |
| 128 | + } |
| 129 | + |
| 130 | + private String generateSelfSignedJWT() { |
| 131 | + RSAPrivateKey prvKey = saKey.getCredentials().getPrivateKeyParsed(); |
| 132 | + Algorithm algorithm = null; |
| 133 | + try { |
| 134 | + algorithm = Algorithm.RSA512(prvKey); |
| 135 | + } catch (Exception e) { |
| 136 | + e.printStackTrace(); |
| 137 | + } |
| 138 | + |
| 139 | + Map<String, Object> jwtHeader = new HashMap<>(); |
| 140 | + jwtHeader.put("kid", saKey.getCredentials().getKid()); |
| 141 | + |
| 142 | + return JWT.create() |
| 143 | + .withIssuer(saKey.getCredentials().getIss()) |
| 144 | + .withSubject(saKey.getCredentials().getSub().toString()) |
| 145 | + .withJWTId(UUID.randomUUID().toString()) |
| 146 | + .withAudience(saKey.getCredentials().getAud()) |
| 147 | + .withIssuedAt(new Date()) |
| 148 | + .withExpiresAt(new Date().toInstant().plusSeconds(10 * 60)) |
| 149 | + .withHeader(jwtHeader) |
| 150 | + .sign(algorithm); |
| 151 | + } |
| 152 | +} |
0 commit comments