java/Google Cloud Flatform sdk 분석

JAVA 구글 GCP credential 가져오는 방법

JAVA천재 2017. 7. 28. 11:15
1. pom.xml 추가
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud</artifactId>
  <version>0.20.3-alpha</version>
</dependency>

2. source 코드
String token  = null;
        try {
            
            File file = new File(KEY_DIR + SEPARATOR + "your key file.json"); # 서비스 계정 Json 파일 명시
            InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
            GoogleCredential credential= GoogleCredential.fromStream(inputStream);

            List<String> COMPUTE_SCOPES =Collections.singletonList(ComputeScopes.COMPUTE);
            if (credential.createScopedRequired()) {
                credential = credential.createScoped(COMPUTE_SCOPES);
            }
            
            credential.refreshToken();
            token = credential.getAccessToken();
            Assert.assertNotNull(token);
                
        } catch (IOException e) {
            Assert.assertNotNull(token);
        }

실제 서비스 계정이 존재 하지 않는다면 token 값에 NULL이 떨어진다.