Amazon CognitoのGetOpenIdTokenForDeveloperIdentityとGetCredentialsForIdentityを使ってみる。

Amazon CognitoのGetOpenIdTokenForDeveloperIdentityとGetCredentialsForIdentityを使ってみたときのサンプルコードのメモ。
Amazon Cognito側でのIdentity Poolの作成は済んでいる前提。

getOpenIdTokenForDeveloperIdentity

AWSCredentials credentials = new BasicAWSCredentials("XXXX", "XXXXX");
AmazonCognitoIdentityClient client = new AmazonCognitoIdentityClient(credentials);
client.setEndpoint("cognito-identity.ap-northeast-1.amazonaws.com");
		
GetOpenIdTokenForDeveloperIdentityRequest getOpenIdTokenForDeveloperIdentityRequest = new GetOpenIdTokenForDeveloperIdentityRequest();
getOpenIdTokenForDeveloperIdentityRequest.setIdentityPoolId("ap-northeast-1:XXXX");
Map<String,String> logins = new HashMap<String,String>();
logins.put("login.mycompany.myapp","user1");
getOpenIdTokenForDeveloperIdentityRequest.setLogins(logins);
GetOpenIdTokenForDeveloperIdentityResult getOpenIdTokenForDeveloperIdentityResult = client.getOpenIdTokenForDeveloperIdentity(getOpenIdTokenForDeveloperIdentityRequest);

getCredentialsForIdentity

GetCredentialsForIdentityRequest getCredentialsForIdentityRequest = new GetCredentialsForIdentityRequest();
Map<String,String> map = new HashMap<String,String>();
map.put("cognito-identity.amazonaws.com", getOpenIdTokenForDeveloperIdentityResult.getToken());
getCredentialsForIdentityRequest.setLogins(map);
getCredentialsForIdentityRequest.setIdentityId(getOpenIdTokenForDeveloperIdentityResult.getIdentityId());
		
GetCredentialsForIdentityResult result = client.getCredentialsForIdentity(getCredentialsForIdentityRequest);
Credentials userCredentials = result.getCredentials();
System.out.println("AccessKey: " + userCredentials.getAccessKeyId());
System.out.println("SecretKey: " + userCredentials.getSecretKey());