package com.napa.pulse.security; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.IdTokenCredentials; import com.google.auth.oauth2.IdTokenProvider; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.ResourceUtils; import java.io.ByteArrayInputStream; import java.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; @Service public class GCPAuthenticationService { @Value("${leadTime.targetAudience}") private String targetAudience; // @Value(("${leadTime.serviceAccount.key}")) @Value(("${leadTime.serviceAccount.key:classpath:gpc-key-dev.json}")) private String serviceAccountFilePath; public String getToken() throws IOException, ParseException { String serviceAccountKey; JSONParser parser = new JSONParser(); JSONObject jsonObject; if(serviceAccountFilePath.contains("classpath")){ jsonObject = (JSONObject) parser.parse(new FileReader(ResourceUtils.getFile(serviceAccountFilePath))); } else { jsonObject = (JSONObject) parser.parse(new FileReader(serviceAccountFilePath)); } serviceAccountKey = jsonObject.toString(); if (serviceAccountKey == null) { throw new IllegalStateException("Service account key is not set"); } final GoogleCredentials googleCredentials = GoogleCredentials .fromStream(new ByteArrayInputStream(serviceAccountKey.getBytes(StandardCharsets.UTF_8))); if (!(googleCredentials instanceof IdTokenProvider)) { throw new IllegalArgumentException("Credentials are not an instance of IdTokenProvider."); } final IdTokenCredentials tokenCredential = IdTokenCredentials.newBuilder() .setIdTokenProvider((IdTokenProvider) googleCredentials) .setTargetAudience(targetAudience) .build(); tokenCredential.refreshIfExpired(); return tokenCredential.getIdToken().getTokenValue(); } }