Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Cognito identity pool with UnAuthenticatd users in Amplify for Android

I've been going through the AWS Amplify docs and tutorials for how to use Amplify and Cognito identity pools together with UNauthenticated users. The example given by the Amplify docs is:

Amplify.Auth.fetchAuthSession(
    result -> {
        AWSCognitoAuthSession cognitoAuthSession = (AWSCognitoAuthSession) result;
            switch(cognitoAuthSession.getIdentityId().getType()) {
                case SUCCESS:
                    Log.i("AuthQuickStart", "IdentityId: " + cognitoAuthSession.getIdentityId().getValue());
                    break;
                case FAILURE:
                    Log.i("AuthQuickStart", "IdentityId not present because: " + cognitoAuthSession.getIdentityId().getError().toString());
            }
        },
        error -> Log.e("AuthQuickStart", error.toString())
);

But in practice when I use this code - I get an error printed out in LogCat:

AuthQuickStart: FAILURE IdentityId not present because: AmplifyException {message=You are currently signed out., cause=null, recoverySuggestion=Please sign in and reattempt the operation.}

Note: I did configure AWS Cognito to support Unauthenticaed users!

I've also looked everywhere for the Amplify Android API doc to see what other APIs are supported - couldn't find any Android API docs. And looking into the AWS Amplify.Auth methods i could not find ANY function that deals with unauthenticated users

Question:

Any clue how can i use Amplify (Android) and have AWS credentials via AWS Cognito for unauthenticated users ???

like image 594
Mercury Avatar asked Sep 09 '20 11:09

Mercury


People also ask

How do you connect amplify to Cognito?

Import existing Amazon Cognito resources into your Amplify project. Get started by running amplify import auth command to search for & import an existing Cognito User Pool & Identity Pool in your account. The amplify import auth command will: automatically populate your Amplify Library configuration files (aws-exports.

Does amplify use Cognito?

The Amplify Framework uses Amazon Cognito as the main authentication provider. Amazon Cognito is a robust user directory service that handles user registration, authentication, account recovery & other operations.

What is the difference between Cognito user pool and identity pool?

Short description. User pools are for authentication (identity verification). With a user pool, your app users can sign in through the user pool or federate through a third-party identity provider (IdP). Identity pools are for authorization (access control).


Video Answer


2 Answers

This is David from the Amplify Android team. I was actually just looking into this the other day and currently there's a hack that's required to make unauth users work.

After setting up unauth/guest users through the CLI (as you mentioned you had) you have to call the getAWSCredentials method on the underlying escape hatch once for the app to get it to work.

Here's a code snippet I'd written that you can run after Amplify.configure (and again, this only needs to be run once per app install):

AWSMobileClient mobileClient = (AWSMobileClient) Amplify.Auth.getPlugin("awsCognitoAuthPlugin").getEscapeHatch();

mobileClient.getAWSCredentials(new Callback<AWSCredentials>() {
     @Override
     public void onResult(AWSCredentials result) {

        // Now you'll see the Identity ID and AWSCredentials in the resulting auth session object.
        Amplify.Auth.fetchAuthSession(
            result2 -> Log.i(TAG, result2.toString()),
            error -> Log.e(TAG, error.toString()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
     }

     @Override
     public void onError(Exception e) {
          // Handle the error however is best for your app
     }
});

I'm working on a solution to avoid this hack right now and adding a documentation section on Unauth users to our site but in the meantime this should get it working for you.

Again note you only have to do this once and from then on out, it should just work when you call fetchAuthSession.

UPDATE: The non patched (official) version:

Amplify.Auth.fetchAuthSession(
    result -> {
        AWSCognitoAuthSession cognitoAuthSession = (AWSCognitoAuthSession) result;
        switch (cognitoAuthSession.getIdentityId().getType()) {
            case SUCCESS:
                Log.i(TAG, "identity: " + cognitoAuthSession.getIdentityId().getValue());
                Log.i(TAG, "credentials: " + cognitoAuthSession.getAWSCredentials().getValue(););
                break;
            case FAILURE:
                Log.i(TAG, "FAILURE IdentityId not present because: " + cognitoAuthSession.getIdentityId().getError().toString());
        }
    },
    error -> Log.e(TAG, "UNAUTH USERS ERR: " + error.toString()));
like image 57
David Daudelin Avatar answered Oct 19 '22 23:10

David Daudelin


You wont be able to retrieve an authenticated session unless you have a logged in user.

If your Identity Pool (not User Pool) is configured for unauthenticated or guest users you can make a simple call to the GetId endpoint:

GetId

Generates (or retrieves) a Cognito ID. Supplying multiple logins will create an implicit linked account.

This is a public API. You do not need any credentials to call this API.

Request Syntax

{
   "AccountId": "string",
   "IdentityPoolId": "string",
   "Logins": { 
      "string" : "string" 
   }
}

https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html

You should then be able to use the ID to retrieve a token using:

GetOpenIdToken

Gets an OpenID token, using a known Cognito ID. This known Cognito ID is returned by GetId. You can optionally add additional logins for the identity. Supplying multiple logins creates an implicit link.

The OpenID token is valid for 10 minutes.

This is a public API. You do not need any credentials to call this API.

Request Syntax

{
   "IdentityId": "string",
   "Logins": { 
      "string" : "string" 
   }
}

https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdToken.html

like image 35
Mike Miller Avatar answered Oct 20 '22 00:10

Mike Miller