我在 Amazon Cognito 中设置了一个用户池以及一个随附的身份池。我可以根据用户池成功验证我的用户名/密码。下一步,我希望将收到的令牌交换为 Cognito 身份,从而获得访问 AWS 服务的临时凭证。我在 Android 应用程序中使用 Kotlin SDK,但很难找到任何代码示例以及相关的 API 文档。
到目前为止,我的登录方法有以下内容:
fun login(emailVal: String, passwordVal: String) {
val userPoolClient = CognitoIdentityProviderClient() { region = "eu-north-1" }
val identityPoolClient = CognitoIdentityClient() { region = "eu-north-1" }
val authParas = mutableMapOf<String, String>()
authParas["USERNAME"] = emailVal
authParas["PASSWORD"] = passwordVal
val loginRequest = InitiateAuthRequest {
clientId = cognitoClientId
authParameters = authParas
authFlow = AuthFlowType.UserPasswordAuth
}
var idToken = ""
viewModelScope.launch(Dispatchers.IO) {
userPoolClient.use { identityProviderClient ->
try {
val result = identityProviderClient.initiateAuth(loginRequest)
idToken = result.authenticationResult?.idToken ?: ""
} catch (e: Exception) {
_loginState.value = BooleanMessage(message = e.message.toString(), success = false)
}
}
//...And now what?
}
}
下一步是什么? authenticationResult 值同时具有 accessToken 和 idToken。 idToken 是来自 Cognito 身份池吗? API 是否为我解决了这个问题?如果没有,那又怎样?
弄清楚了:
val loginSettings: MutableMap<String, String> = HashMap()
loginSettings["cognito-idp.<REGION>.amazonaws.com/<USER_POOL_ID>"] = idToken
val identityRequest = GetIdRequest {
identityPoolId = "<REGION>:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
logins = loginSettings
}
var result: GetIdResponse
try {
result = identityPoolClient.getId(identityRequest)
} catch (e: Exception) {
_loginState.value = BooleanMessage(message = e.message.toString(), success = false)
}