AWS Cognito - JamesDansie/data-structures-and-algorithms GitHub Wiki

Cognito

Author: James Dansie

Cognito is a log in service from AWS. It sounds fairly similar to Spring. You can check if a user is logged in, and redirect them to log in as well. It has the extra functionality of different levels of credentials, and choosing for how long the credentials are valid for.

To add auth;

  1. $ amplify add auth or amplify auth update if you already have api installed.
  2. amplify push
  3. add dependencies
//For AWSMobileClient only:
implementation 'com.amazonaws:aws-android-sdk-mobile-client:2.15.+'

//For the drop-in UI also:
implementation 'com.amazonaws:aws-android-sdk-auth-userpools:2.15.+'
implementation 'com.amazonaws:aws-android-sdk-auth-ui:2.15.+'

might need to bump the minSdkVersion to 23 ( also in build.gradle).

  1. add permissions to the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  1. in main activity onCreate() run the initialization, make sure the Callback and UserStateDetails point to amazon aws, and not the defaults;
AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() {

        @Override
        public void onResult(UserStateDetails userStateDetails) {
                Log.i("INIT", "onResult: " + result.getUserState().toString());
        }

        @Override
        public void onError(Exception e) {
            Log.e("INIT", "Initialization error.", e);
        }
    }
);

This will show the login/logout status. We still need to add the ability to log in and log out.

Log In

  1. Add a log in button.
  2. Set an event listener for the button.
Button signinButton = findViewById(R.id.SOMEBUTTONID);
signoutButton.setOnClickListener((event) -> {
  //do Stuff with the listener


  // Add all the log in stuff
  // 'this' refers the the current active activity, probably replace with MainActivity.this
  AWSMobileClient.getInstance().showSignIn(this, new Callback<UserStateDetails>() {
    @Override
    public void onResult(UserStateDetails result) {
        Log.d(TAG, "onResult: " + result.getUserState());
    }

    @Override
    public void onError(Exception e) {
        Log.e(TAG, "onError: ", e);
    }
  });

});

You can log into coginto on the aws portal and see the user pools (user DB).

Log Out

  1. Add a log out button.
  2. Set an event listener for the button.
Button signoutButton = findViewById(R.id.SOMEBUTTONID);
signoutButton.setOnClickListener((event) -> {
  //do Stuff with the listener
  AWSMobileClient.getInstance().signOut();
});

References