2016-07-14 2 views
0

내 AngularJS 웹 응용 프로그램에서 Google 클라우드 저장소에 이미지를 업로드하려고하고 있으며 업로드를 요청하는 동안 Authorization 헤더에있는 액세스 코드가 필요합니다. 액세스 토큰을 얻으려면 JAVA로 개발 된 서버 측에 엔드 포인트를 도입했습니다. 액세스 토큰을 얻으려는 현재 코드는 다음과 같습니다.Google Cloud Storage에 대한 액세스 코드를 얻는 방법은 무엇인가요?

GoogleCredential credential = GoogleCredential.fromStream(new URL("HERE GOES URL OF MY SERVICE ACCOUNT JSON FILE").openStream()); 
if (credential.createScopedRequired()) { 
     Collection<String> scopes = StorageScopes.all(); 
     credential = credential.createScoped(scopes); 
    } 
String token = credential.getAccessToken(); 
log.log(Level.SEVERE, "5 "+token); 

그러나 로그에는 null이 표시됩니다.

URL에서 JSON 파일을 가져 오는 이유는 JSON 파일을 동일한 패키지에 넣었을 때 java.security.AccessControlException이 발생했기 때문입니다. 그래서, 내가 Google 드라이브에 파일을 배치하고 위의 코드에서 사용되는 직접 다운로드 링크를 생성하지 않도록하십시오.

액세스 코드를 원하면 웹 앱으로 보내어 업로드를 시작할 수 있습니다. 어떤 도움을 주시면 감사하겠습니다.

고맙습니다.

+0

에 완전한 답변을해야하는 경우? App Engine에서 GCS를 사용하는 대부분의 라이브러리는 자동으로 앱 엔진 서비스 계정으로 인증을 처리합니다. –

+0

@BrandonYarbrough 나는 angularJS에 내장 된 내 웹 앱을 사용하여 GCS에 이미지를 업로드하려고하고 있으며이를 달성하기 위해 인증 헤더에 액세스 토큰을 보내야합니다. –

+1

아, 그러면 클라이언트 측에 액세스 토큰을 보내고 클라이언트가 업로드를 수행하기 위해 토큰을 사용하도록 하시겠습니까? 그렇다면 서명 된 URL과 같은 다른 접근 방식을 사용하는 것이 좋습니다. 액세스 토큰은 서비스 계정이 해당 범위로 수행 할 수있는 모든 권한을 나타냅니다. 예를 들어, 악의적 인 클라이언트가 버킷 및 모든 내용을 삭제할 수 있습니다. –

답변

0

내가 사용하여 자격 증명을 얻을 수 오전 다음 수업.

package XXXXXXXXXXXX; 

import java.io.IOException; 
import java.net.URL; 
import java.security.GeneralSecurityException; 
import java.util.Collection; 

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; 
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; 
import com.google.api.client.http.HttpTransport; 
import com.google.api.client.json.JsonFactory; 
import com.google.api.client.json.jackson2.JacksonFactory; 
import com.google.api.services.storage.Storage; 
import com.google.api.services.storage.StorageScopes; 

//@author Umesh Chauhan 

public class StorageFactory 
{ 

    private static Storage instance = null; 

    public static synchronized Storage getService() throws IOException, GeneralSecurityException 
    { 
     if (instance == null) 
     { 
      instance = buildService(); 
     } 
     return instance; 
    } 

    private static Storage buildService() throws IOException, GeneralSecurityException 
    { 

     HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport(); 
     JsonFactory jsonFactory = new JacksonFactory(); 

     GoogleCredential credential = GoogleCredential.fromStream (
       new URL ("HERE GOES THE URL FOR YOUR SERVICE ACCOUNT JSON - I USED GOOGLE DRIVE DIRECT DOWNLOAD LINK TO MY JSON FILE") 
         .openStream()); 

     // Depending on the environment that provides the default credentials 
     // (for 
     // example: Compute Engine, App Engine), the credentials may require us 
     // to 
     // specify the scopes we need explicitly. Check for this case, and 
     // inject 
     // the Cloud Storage scope if required. 
     if (credential.createScopedRequired()) 
     { 
      Collection<String> scopes = StorageScopes.all(); 
      credential = credential.createScoped (scopes); 
     } 

     return new Storage.Builder (transport, jsonFactory, credential).setApplicationName ("YOUR PROJECT NAME").build(); 
    } 
} 

그리고 그 스토리지 개체를 사용하여 파일을 Google Cloud Storage에 업로드했습니다.

중 하나가 당신이 토큰을 직접 액세스 할 려 "How to upload file to Google Cloud Storage ?"

+0

이 패키지를 가져올 수 없습니다 .. 추가 할 라이브러리가 있습니까? import com.google.api.services.storage.Storage; import com.google.api.services.storage.StorageScopes; – Jana

+0

괜찮습니다. 컴파일 그룹을 추가했습니다 : 'com.google.apis ', 이름 :'google-api-services-storage ', 버전 : build.gradle의'v1beta1-rev21-1.14.1-beta '및 가져 오기가 작동합니다. – Jana

+0

하지만이 all() 메서드는 인식되지 않습니다 ... StorageScopes.all(); 내가 \t 을 사용하고 – Jana

0

사용중인 코드는 App Engine 인스턴스 용이 아닙니다. 당신이 어떤 정적 파일에서와 같이 당신은 /war/WEB_INF 폴더에 앱을 JSON 파일을 넣을 수 있지만, 더 나은 솔루션은 앱 엔진에 특별히 작동 코드를 사용하는 것입니다

private static final AppIdentityService identityService = AppIdentityServiceFactory.getAppIdentityService(); 

String token = identityService 
       .getAccessToken(Arrays.asList("https://www.googleapis.com/auth/devstorage.full_control")).getAccessToken(); 
+0

안녕하세요 @Andrei, 먼저 도움을 주셔서 감사합니다.하지만 invalidToken이 반환됩니다. 완전한 토큰 값은 다음과 같습니다 "InvalidToken : https : // www.googleapis.com/auth/devstorage.full_control:6058" –

+0

내 응용 프로그램에서이 코드를 아무런 문제없이 사용합니다 (FileMambo.com 중 하나임). 프로젝트에 올바른 Cloud Storage API를 사용 설정 했습니까? –

+0

내 Google 콘솔에서이 두 API를 사용 설정했습니다. Google Cloud Storage, Google Cloud Storage JSON API –

관련 문제