2016-08-03 1 views
5

모든 http/rest 호출에 대해 안드로이드 앱에 retrofit2을 사용합니다. 이제 Amazon AWS API Gateway으로 생성 된 API를 호출해야합니다.안드로이드에서 retrofit2를 통해 Cognito 자격 증명으로 API 게이트웨이를 호출하는 방법은 무엇입니까?

나는 클라이언트 코드는 API 게이트웨이 콘솔을 던져 요청 구축하기 위해 클래스를 ApiClientFactory을 사용하여 생성해야하는 AWS 문서 say : 나는 retrofit 때와 같은 API를 정의하고 싶습니다 대신

ApiClientFactory factory = new ApiClientFactory(); 

// Use CognitoCachingCredentialsProvider to provide AWS credentials 
// for the ApiClientFactory 
AWSCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
     context,   // activity context 
     "identityPoolId", // Cognito identity pool id 
     Regions.US_EAST_1 // region of Cognito identity pool 
}; 

factory.credentialsProvider(credentialsProvider); 

// Create an instance of your SDK (this should come from the generated code). 
final MyApiClient client = factory.build(MyApiClient.class); 

// Invoke a method (e.g., 'parentPath1Get(param1,body)') exposed by your SDK. 
// Here the method's return type is OriginalModel. 
OriginalModel output = client.parentPath1Get(param1,body); 

// You also have access to your API's models. 
OriginalModel myModel = new OriginalModel(); 
myModel.setStreetAddress(streetAddress); 
myModel.setCity(city); 
myModel.setState(state); 
myModel.setStreetNumber(streetNumber); 
myModel.setNested(nested); 
myModel.setPoBox(poBox); 

를 : 내가 작성한 인터페이스로 RxJava, OkHttp 등에 연결하십시오.

질문 : 어떻게 Cognito Identity Provider로 갱신 요청을 할 수 있습니까?

+0

AWS SDK를 직접 사용하고 Rx Observables에서 직접 처리했습니다. 잭 콘 (Jack Kohn)의 대답은 잘못이 아니지만 실제로는 답변이 아니며 스스로 구현하려는 경우 올바른 방향을 가리키고 있습니다. –

+0

그래서 나는 API 게이트웨이와 안드로이드를 연결하려고 노력하고있다. 그러나 어떻게 또는 어디서 얻었 는가/클래스'MyApiClient'를 만들었나? – TheQ

+0

이름은 서비스에 따라 다릅니다. theres 발전기/API 게이트웨이 웹 콘솔에서 내보낼 수 있습니다. 나는이 방법을 사용하지 않았다. 덕분에 –

답변

1

가 대답 thanhbinh84 @ 기반으로 OkHttp 인터셉터를 만들었습니다. 시도해보십시오. https://github.com/Ghedeon/AwsInterceptor

+0

현재로서는 더 이상 필요가 없기 때문에 실제로 테스트하지 않고 답변을 수락했습니다. 테스트 할 시간이 없습니다. 그것. 누군가가 그것을 시도하고 그것이 작동하지 않는 것을 찾으면 나는 받아 들인 대답을 취소 할 것이다/나는 그것이 일하는 것을 확인하는 사람들에게 감사 할 것이다! –

1

서명 과정은 여기에 설명되어 있습니다 : http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html

그러나 당신은 아마 기본 API 게이트웨이 클라이언트가 의존하는 핵심 런타임 패키지의 코드의 일부를 다시 시도 할 수 있습니다. 이미 서명 프로세스가 잘 알려져 있으므로 RxJava 또는 OkHttp 유형의 요청에 대해 이미 라이브러리가있을 수 있습니다.

+0

. 아마 다음 달에 이걸 필요할거야. 나는 누군가가 더 많은 세부 사항, 도서관 또는 그 사이에 무엇인가를 게시 할 것을 희망한다. 그렇지 않다면 내가 준 링크에서 시작해서 직접 할거야 –

3

작동 방식을 이해하는 데 며칠이 걸렸습니다. 그들이 왜 다스의 문서 페이지 대신에 수업을 지적하지 않는지 모르겠다. 총 4 단계가 있습니다, 당신은 내가 Rxjava 사용하고 작업자 스레드에서 호출해야하지만 대신 AsyncTask를 사용할 수 있습니다 :

Observable.create((Observable.OnSubscribe<String>) subscriber -> { 
//Step 1: Get credential, ask server team for Identity pool id and regions    
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
       this, // Context 
       "Identity Pool ID", // Identity Pool ID 
       Regions.US_EAST_1 // Region 
      ); 

//Step 2: Get these 3 three keys, test with postman v4.9.3 to see if identity is correct 
      String identityId = credentialsProvider.getIdentityId(); 
      Log.show("identityId = " + identityId); 

      String AccessKey = credentialsProvider.getCredentials().getAWSAccessKeyId(); 
      String SecretKey = credentialsProvider.getCredentials().getAWSSecretKey(); 
      String SessionKey = credentialsProvider.getCredentials().getSessionToken(); 

      Log.show("AccessKey = " + AccessKey); 
      Log.show("SecretKey = " + SecretKey); 
      Log.show("SessionKey = " + SessionKey); 
//Step 3: Create an aws requets and sign by using AWS4Signer class 
      AmazonWebServiceRequest amazonWebServiceRequest = new AmazonWebServiceRequest() { 
      }; 

      ClientConfiguration clientConfiguration = new ClientConfiguration(); 

      String API_GATEWAY_SERVICE_NAME = "execute-api"; 

      Request request = new DefaultRequest(amazonWebServiceRequest,API_GATEWAY_SERVICE_NAME); 
      request.setEndpoint(URI.create("YOUR_URI")); 
      request.setHttpMethod(HttpMethodName.GET); 

      AWS4Signer signer = new AWS4Signer(); 
      signer.setServiceName(API_GATEWAY_SERVICE_NAME); 
      signer.setRegionName(Region.getRegion(Regions.US_EAST_1).getName()); 
      signer.sign(request, credentialsProvider.getCredentials()); 

      Log.show("Request header " + request.getHeaders().toString()); 
//Step 4: Create new request with authorization headers 

      OkHttpClient httpClient = new OkHttpClient(); 
      Map<String, String> headers = request.getHeaders(); 
      List<String> key = new ArrayList<String>(); 
      List<String> value = new ArrayList<String>(); 

      for (Map.Entry<String, String> entry : headers.entrySet()) 
      { 
       key.add(entry.getKey()); 
       value.add(entry.getValue()); 
      } 

      try { 
       okhttp3.Request request2 = new okhttp3.Request.Builder() 
         .url("Your_url") // remember to add/to the end of the url, otherwise the signature will be different 
         .addHeader(key.get(0), value.get(0)) 
         .addHeader(key.get(1), value.get(1)) 
         .addHeader(key.get(2), value.get(2)) 
         .addHeader(key.get(3), value.get(3)) 

         .addHeader("Content-Type", "application/x-www-form-urlencoded") 
         .build(); 
       Response response = null; 

       response = httpClient.newCall(request2).execute(); 
       String body = response.body().string(); 
       Log.show("response " + body); 
      } catch (Exception e) { 
       Log.show("error " + e); 
      } 

      subscriber.onNext(identityId); 

     }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() { 
      @Override 
      public void onCompleted() { 

      } 

      @Override 
      public void onError(Throwable e) { 
       Log.show("Throwable = " + e.getMessage()); 
      } 

      @Override 
      public void onNext(String s) { 

      } 
     }); 

여기서 핵심은 AWS4Signer 클래스는 here 설명 된대로 4 단계를 수행, 당신은하지 않습니다 처음부터 하나를 만들 필요가있다. AWS4Signer 및 AmazonWebServiceRequest를 사용하려면, 당신은 Gradle을에서 AWS SDK를 가져와야 :

compile 'com.amazonaws:aws-android-sdk-cognito:2.3.9' 
+1

지금은 테스트 할 기회가 없다.하지만 약간의 정리가 필요하다는 것 외에는 올바른 해결책 인 것 같다. 내가 할 수있을 때 다시 돌아올 것이다. , 감사. (한편으로는 개조하지 않고도 SDK를 사용했기 때문에 직접 사용했습니다. –

+0

@DanieleSegato, 나중에 AWS SDK로 전환 할 수 있습니다. 시간이 필요합니다. :) – thanhbinh84

+0

더 쉽고, 청소하기가 쉽지 않으며, 힘들이지 않고 개조해야합니다. (별명 = 더 많은 상용구) : –

관련 문제