DEV Community

loading...
Cover image for Login With Amazon using AWS Amplify Auth

Login With Amazon using AWS Amplify Auth

offlineprogrammer profile image Offline Programmer Originally published at offlineprogrammer.com Updated on ・8 min read

In this tutorial you will learn how use AWS Amplify authentication service to enable Login With Amazon in an Android application. The App experience will look like below

 

 

  • Create a new Android Studio project using the Empty Activity template

http://www.offlineprogrammer.com/wp-content/uploads/2020/07/Screen_Shot_2020-07-28_at_12.21.53_PM.png

  • We are going to use MyAuthApplication for the name field

http://www.offlineprogrammer.com/wp-content/uploads/2020/07/creen_Shot_2020-07-30_at_3.56.43_PM.png

  • Update build.gradle (Project: MyAuthApplication) as below
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
        // ******* Add this line *******
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.1"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

        // ******* Add this line *******
        mavenCentral()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
  • Update build.gradle (Module:app) as below
apply plugin: 'com.android.application'

android {
    compileSdkVersion 29

    defaultConfig {
        applicationId "com.offlineprogrammer.myauthapplication"
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    // ******* Add these lines *******
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    // ******* Add these lines *******
    implementation 'com.amplifyframework:core:1.1.1'
    implementation 'com.amplifyframework:aws-auth-cognito:1.1.1'

}
  • Make sure to run Gradle Sync
  • Run the command below on Android Studio Terminal
amplify init
  • You will prompted for few details as below
? Enter a name for the project MyAuthApplication
? Enter a name for the environment amplify
? Choose your default editor: None
? Choose the type of app that you're building android
Please tell us about your project
? Where is your Res directory:  app/src/main/res
Using default provider  awscloudformation

For more information on AWS Profiles, see:
<https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html>

? Do you want to use an AWS profile? Yes
? Please choose the profile you want to use default
Adding backend environment amplify to AWS Amplify Console app: d2yvhmdiprhhlh

  • Once complete you will get the confirmation below
Your project has been successfully initialized and connected to the cloud!
  • Create a new class and name it MyAuthApplication
  • We will use this class to initialize Amplify as below - note how the class extends from Application
public class MyAuthApplication  extends Application {
    private static final String TAG = "MyAuthApplication";

    @Override
    public void onCreate() {
        super.onCreate();

        try {
            Amplify.addPlugin(new AWSCognitoAuthPlugin());

            Amplify.configure(getApplicationContext());

            Log.i(TAG, "Initialized Amplify");
        } catch (AmplifyException error) {
            Log.e(TAG, "Could not initialize Amplify", error);
        }

    }
}
  • Update AndroidManifest.xml to add a android:name attribute with the value of .MyAuthApplication as below
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.offlineprogrammer.loginwithamazon">

    <application
        android:name=".MyAuthApplication"
                ....
  • Login here using your Amazon developer account to create a Security Profile
http://www.offlineprogrammer.com/wp-content/uploads/2020/07/Screen_Shot_2020-07-28_at_4.10.12_PM.png
  • Enter a Security Profile Name, a Security Profile Description, and a Consent Privacy Notice URL then click Save
  • Take not of the client ID & Client secret
http://www.offlineprogrammer.com/wp-content/uploads/2020/07/Screen_Shot_2020-07-31_at_1.12.05_PM.png
  • Run the command below to configure the Auth Category
amplify add auth
  • Set the details below when prompted
Do you want to use the default authentication and security configuration? Default configuration with Social Provider (Federation)
 Warning: you will not be able to edit these selections. 
 How do you want users to be able to sign in? Username
 Do you want to configure advanced settings? No, I am done.
 What domain name prefix do you want to use? myauthapplication7ae1f03e-7ae1f03e
 Enter your redirect signin URI: myauthapp://callback/
? Do you want to add another redirect signin URI No
 Enter your redirect signout URI: myauthapp://signout/
? Do you want to add another redirect signout URI No
 Select the social providers you want to configure for your user pool: Login With Amazon
  
 You've opted to allow users to authenticate via Amazon.  If you haven't already, you'll need to create an Amazon App ID. 
 
 Enter your Amazon App ID for your OAuth flow:  amzn1.application-oa2-client.88a2ae52a05349d8a8027c93d9e5fc51
 Enter your Amazon App Secret for your OAuth flow:  b9f0fa476eea36200d8f1f304adc7711a63fa6422d22d515b50f729f33560a61
Successfully added resource myauthapplication7ae1f03e locally

  • Publish those changes by running the command below
amplify push
  • Once complete it will display your UI endpoint Url as belwo
✔ All resources are updated in the cloud

Hosted UI Endpoint: <https://myauthapplication7ae1f03e-7ae1f03e-amplify.auth.us-east-1.amazoncognito.com/>
Test Your Hosted UI Endpoint: <https://myauthapplication7ae1f03e-7ae1f03e-amplify.auth.us-east-1.amazoncognito.com/login?response_type=code&client_id=5ig0u8445jd6v23ejt9db1ks3p&redirect_uri=myauthapp://callback/>
  • On Amazon developer portal, click on the security profile you created above and select the web Settings tab

http://www.offlineprogrammer.com/wp-content/uploads/2020/07/Screen_Shot_2020-07-31_at_3.13.24_PM.png

  • Choose Edit then Type your UI endpoint Url into Allowed Origins and type UI endpoint Url with the /oauth2/idpresponse endpoint into Allowed Return URLs.

http://www.offlineprogrammer.com/wp-content/uploads/2020/07/Screen_Shot_2020-07-31_at_1.24.02_PM.png

  • Update the AndroidManifest.xm to set the android:launchMode and intent-filter for the MainActivity as below
<activity android:name=".MainActivity"
            android:launchMode="singleInstance">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="myauthapp" />
            </intent-filter>
        </activity>
  • To capture the response from the sign in web UI add the method below to MainActivity
@Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        if(intent.getData() != null && "myauthapp".equals(intent.getData().getScheme())) {
            Amplify.Auth.handleWebUISignInResponse(intent);
        }
    }
  • Download the login button from here and add it to your Drawable folder. we are going to use both (btnlwa_gold_login.png) & (btnlwa_gold_login_pressed.png).
  • Right click on Drawable folder and create a Drawable Resource File . Name it login_button_image_state.xml
  • This file will define the selector for the login button as below

    
    
  • Update the activity_main.xml to add the login button & progress bar as below



    


    

    

        
    


  • Update the MainActivity.java to introduce a login method to be called when the user click on the signIn button. below is the final code of MainActivity.java
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    ImageButton login_with_amazon;
    TextView login_textView;
    ProgressBar log_in_progress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        login_with_amazon = findViewById(R.id.login_with_amazon);
        login_textView = findViewById(R.id.login_textView);
        log_in_progress = findViewById(R.id.log_in_progress);

        login_with_amazon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                log_in_progress.setVisibility(View.VISIBLE);
                login_with_amazon.setVisibility(View.GONE);
                login();
            }
        });


    }

    private void login() {
        Amplify.Auth.signInWithSocialWebUI(
                AuthProvider.amazon(),
                this,
                result -> {
                    Log.i(TAG, "AuthQuickstart RESULT " + result.toString());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            login_textView.setText("Login is successfull");
                            login_with_amazon.setVisibility(View.GONE);
                            log_in_progress.setVisibility(View.GONE);
                        }
                    });
                },
                error -> {
                    Log.e(TAG, "AuthQuickstart ERROR " + error.toString());
                }
        );

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        if(intent.getData() != null && "myauthapp".equals(intent.getData().getScheme())) {
            Amplify.Auth.handleWebUISignInResponse(intent);
        }
    }

}

Check the full code on github and follow me on Twitter for more tips about #coding, #learning, #technology, #Java, #JavaScript, #Autism, #Parenting...etc.

Check my Apps on Google Play

 

 

Discussion (1)

pic
Editor guide
Collapse
starpebble profile image
starpebble

Login with Amazon has an amazing future benefit: it's really simple to create an Alexa skill with Login with Amazon and therefore a single user can have an authenticated experience with both a company's web app and Alexa skill. 👍