Search code examples
amazon-web-serviceskotlinamazon-cognito

How do I obtain credentials from the Cognito Identity pool using Kotlin SDK?


I setup a user pool in Amazon Cognito, and an accompanying identity pool. I can successfully authenticate my username/password against the user pool. As a next step, I wish to exchange the token I received for a Cognito Identity and thus obtain temporary credentials to access AWS services. I am using the Kotlin SDK in an Android app, and I'm having a hard time finding any code examples, as well as relevant API documentation.

So far I have the following in my login method:

    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?
        }

    }

What is the next step? The authenticationResult value has both accessToken and idToken. Is the idToken from the Cognito Identity pool? Did the API take care of this for me? If not, then what?


Solution

  • Figured it out:

    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)
    }