I use retrofit2
in my android apps for any http/rest call. Now I need to call an api generated with Amazon AWS API Gateway.
The AWS documentation say I should generate the client code throw the API Gateway console and use the class ApiClientFactory
to build the request:
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);
Instead I would like to define the API like I would with retrofit
: with an interface I write, connect it to RxJava, OkHttp etc...
My question is: how can I sign the retrofit requests with Cognito Identity Provider?
Created an OkHttp interceptor based on @thanhbinh84 answer. Give it a try: https://github.com/Ghedeon/AwsInterceptor
The signature process is documented here: http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
But you could probably try to reuse some of the code from the core runtime package that the default API Gateway client depends on. There may be libraries out there already for signing requests of type RxJava or OkHttp since the signature process is well-known.
It took me several days to figure out how to make it work. Don't know why they don't point out the class instead of dozen of document pages. There are 4 steps in total, you must call in worker thread, I am using Rxjava but you can use AsyncTask instead:
The key here is the AWS4Signer class does 4 steps as documented here, you don't need to build one from scratch. In order to use AWS4Signer and AmazonWebServiceRequest, you need to import aws sdk in gradle: