Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 1238 lines (810 sloc) 60.8 KB

Add User Sign-in to Your Mobile App with Amazon Cognito

The following reference content only applies to existing apps that were built using the AWS Mobile SDKs for iOS and Android. If you’re building a new mobile or web app, or you're adding cloud capabilities to an existing app, visit the Amplify Framework website instead. Documentation for the AWS Mobile SDKs for iOS and Android is now part of the Amplify Framework.

Enable your users to sign-in using credentials from Facebook, Google, or your own custom user directory. The AWS Mobile Hub :ref:`User Sign-in <user-sign-in>` feature is powered by Amazon Cognito, and the SDK provides a pre-built, :ref:`configurable <mobile-hub-add-aws-mobile-user-sign-in-customize>` Sign-in UI based on the identity provider(s) you configure.

Set Up Your Backend

Prerequisite Complete the :ref:`Get Started <mobile-hub-getting-started>` steps before your proceed.

Email & Password
  1. Enable :guilabel:`User Sign-in`: Open your project in Mobile Hub console and choose the :guilabel:`User Sign-in` tile.

  2. Choose :guilabel:`Email and Password sign-in`

    images/add-aws-mobile-sdk-email-and-password.png

    Or:

    • Choose :guilabel:`Import an existing user pool`, select a user pool from the list of pools that are available in the account. Choose if sign-in is required, and then choose :guilabel:`Create user pool`. If you import a user pool that is in use by another app, then the two apps will share the user directory and authenticate sign-in by the same set of users.

      images/add-aws-mobile-sdk-email-and-password-import.png
  3. When you are done configuring providers, choose :guilabel:`Click here to return to project details page` in the blue banner at the top.

    images/updated-cloud-config.png
  4. On the project detail page, choose the flashing :guilabel:`Integrate` button, and then complete the steps that guide you to connect your backend.

    If your project contains apps for more than one platform, any that need to complete those steps will also display a flashing :guilabel:`Integrate` button. The reminder banner will remain in place until you have taken steps to update the configuration of each app in the project.

    images/updated-cloud-config2.png
  5. Follow the :ref:`Set up Email & Password Login <mobile-hub-set-up-email-and-password>` steps to connect to your backend from your app.

Facebook
  1. Enable :guilabel:`User Sign-in`: Open your project in Mobile Hub console and choose the :guilabel:`User Sign-in` tile.

  2. Configure Facebook sign-in: Choose the feature and then type your Facebook App ID and then choose :guilabel:`Enable Facebook login`. To retrieve or create your Facebook App ID, see Setting Up Facebook Authentication..

    images/add-aws-mobile-sdk-facebook.png
  3. When you are done configuring providers, choose :guilabel:`Click here to return to project details page` in the blue banner at the top.

    images/updated-cloud-config.png
  4. On the project detail page, choose the flashing :guilabel:`Integrate` button, and then complete the steps that guide you to connect your backend.

    If your project contains apps for more than one platform, any that need to complete those steps will also display a flashing :guilabel:`Integrate` button. The reminder banner will remain in place until you have taken steps to update the configuration of each app in the project.

    images/updated-cloud-config2.png
  5. Follow the steps at :ref:`Set Up Facebook Login <mobile-hub-set-up-facebook>` to connect to your backend from your app.

Google
  1. Enable :guilabel:`User Sign-in`: Open your project in Mobile Hub console and choose the :guilabel:`User Sign-in` tile.

  2. Configure Google sign-in: Choose the feature and then type in your Google Web App Client ID, and the Google Android or iOS Client ID (or both), and then choose Enable Google Sign-In. To retrieve or create your Google Client IDs, see Setting Up Google Authentication.

    images/add-aws-mobile-sdk-google.png
  3. When you are done configuring providers, choose :guilabel:`Click here to return to project details page` in the blue banner at the top.

    images/updated-cloud-config.png
  4. On the project detail page, choose the flashing :guilabel:`Integrate` button, and then complete the steps that guide you to connect your backend.

    If your project contains apps for more than one platform, any that need to complete those steps will also display a flashing :guilabel:`Integrate` button. The reminder banner will remain in place until you have taken steps to update the configuration of each app in the project.

    images/updated-cloud-config2.png
  5. Follow the steps at :ref:`Set Up Google Login <mobile-hub-set-up-google>` to connect to your backend from your app.

Setup Email & Password Login in your Mobile App

Choose your platform:

Android - Java
Use Android API level 23 or higher The AWS Mobile SDK library for Android sign-in (aws-android-sdk-auth-ui) provides the activity and view for presenting a SignInUI for the sign-in providers you configure. This library depends on the Android SDK API Level 23 or higher.
  1. Add or update your AWS backend configuration file to incorporate your new sign-in. For details, see the last steps in the :ref:`Get Started: Set Up Your Backend <mobile-hub-add-aws-mobile-sdk-basic-setup>` section.

  2. Add these permissions to the :file:`AndroidManifest.xml` file:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  3. Add these dependencies to the :file:`app/build.gradle` file:

    dependencies {
         // Mobile Client for initializing the SDK
         implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.7.+@aar') { transitive = true }
    
         // Cognito UserPools for SignIn
         implementation 'com.android.support:support-v4:24.+'
         implementation ('com.amazonaws:aws-android-sdk-auth-userpools:2.7.+@aar') { transitive = true }
    
         // Sign in UI Library
         implementation 'com.android.support:appcompat-v7:24.+'
         implementation ('com.amazonaws:aws-android-sdk-auth-ui:2.7.+@aar') { transitive = true }
    }
  4. Create an activity that will present your sign-in screen.

    In Android Studio, choose :guilabel:`File > New > Activity > Basic Activity` and type an activity name, such as :userinput:`AuthenticatorActivity`. If you want to make this your starting activity, move the intent filter block containing .LAUNCHER to the AuthenticatorActivity in your app's :file:`AndroidManifest.xml`.

    <activity android:name=".AuthenticatorActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
  5. Update the onCreate function of your AuthenticatorActivity to call AWSMobileClient. This component provides the functionality to resume a signed-in authentication session. It makes a network call to retrieve the AWS credentials that allow users to access your AWS resources and registers a callback for when that transaction completes.

    If the user is signed in, the app goes to the NextActivity, otherwise it presents the user with the AWS Mobile ready made, configurable sign-in UI. NextActivity Activity class a user sees after a successful sign-in.

    import android.app.Activity;
    import android.os.Bundle;
    
    import com.amazonaws.mobile.auth.ui.SignInUI;
    import com.amazonaws.mobile.client.AWSMobileClient;
    import com.amazonaws.mobile.client.AWSStartupHandler;
    import com.amazonaws.mobile.client.AWSStartupResult;
    
    public class AuthenticatorActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_authenticator);
    
            // Add a call to initialize AWSMobileClient
            AWSMobileClient.getInstance().initialize(this, new AWSStartupHandler() {
                @Override
                public void onComplete(AWSStartupResult awsStartupResult) {
                    SignInUI signin = (SignInUI) AWSMobileClient.getInstance().getClient(
                          AuthenticatorActivity.this,
                          SignInUI.class);
                    signin.login(
                          AuthenticatorActivity.this,
                          NextActivity.class).execute();
                }
            }).execute();
        }
    }

Choose the run icon (|play|) in Android Studio to build your app and run it on your device/emulator. You should see our ready made sign-in UI for your app. To learn how to :ref:`customize your UI <mobile-hub-add-aws-mobile-user-sign-in-customize>`.

API References
  • AWSMobileClient

    A library that initializes the SDK, constructs CredentialsProvider and AWSConfiguration objects, fetches the AWS credentials, and creates a SDK SignInUI client instance.

  • Auth UserPools

    A wrapper Library for Amazon Cognito UserPools that provides a managed Email/Password sign-in UI.

  • Auth Core

    A library that caches and federates a login provider authentication token using Amazon Cognito Federated Identities, caches the federated AWS credentials, and handles the sign-in flow.

Android - Kotlin
Use Android API level 23 or higher The AWS Mobile SDK library for Android sign-in (aws-android-sdk-auth-ui) provides the activity and view for presenting a SignInUI for the sign-in providers you configure. This library depends on the Android SDK API Level 23 or higher.
  1. Add or update your AWS backend configuration file to incorporate your new sign-in. For details, see the last steps in the :ref:`Get Started: Set Up Your Backend <mobile-hub-add-aws-mobile-sdk-basic-setup>` section.

  2. Add these permissions to the :file:`AndroidManifest.xml` file:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  3. Add these dependencies to the :file:`app/build.gradle` file:

    dependencies {
         // Mobile Client for initializing the SDK
         implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.7.+@aar') { transitive = true }
    
         // Cognito UserPools for SignIn
         implementation 'com.android.support:support-v4:24.+'
         implementation ('com.amazonaws:aws-android-sdk-auth-userpools:2.7.+@aar') { transitive = true }
    
         // Sign in UI Library
         implementation 'com.android.support:appcompat-v7:24.+'
         implementation ('com.amazonaws:aws-android-sdk-auth-ui:2.7.+@aar') { transitive = true }
    }
  4. Create an activity that will present your sign-in screen.

    In Android Studio, choose :guilabel:`File > New > Activity > Basic Activity` and type an activity name, such as :userinput:`AuthenticatorActivity`. If you want to make this your starting activity, move the intent filter block containing .LAUNCHER to the AuthenticatorActivity in your app's :file:`AndroidManifest.xml`.

    <activity android:name=".AuthenticatorActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
  5. Update the onCreate function of your AuthenticatorActivity to call AWSMobileClient. This component provides the functionality to resume a signed-in authentication session. It makes a network call to retrieve the AWS credentials that allow users to access your AWS resources and registers a callback for when that transaction completes.

    If the user is signed in, the app goes to the NextActivity, otherwise it presents the user with the AWS Mobile ready made, configurable sign-in UI. NextActivity Activity class a user sees after a successful sign-in.

    import android.app.Activity;
    import android.os.Bundle;
    
    import com.amazonaws.mobile.auth.ui.SignInUI;
    import com.amazonaws.mobile.client.AWSMobileClient;
    import com.amazonaws.mobile.client.AWSStartupHandler;
    import com.amazonaws.mobile.client.AWSStartupResult;
    
    class AuthenticatorActivity : Activity() {
      override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    
      AWSMobileClient.getInstance().initialize(this) {
          val ui = AWSMobileClient.getInstance().getClient(
                this@AuthenticatorActivity,
                SignInUI::class.java) as SignInUI?
          ui?.login(
                this@AuthenticatorActivity,
                MainActivity::class.java)?.execute()
      }.execute()
    }

Choose the run icon (|play|) in Android Studio to build your app and run it on your device/emulator. You should see our ready made sign-in UI for your app. Checkout the next steps to learn how to :ref:`customize your UI <mobile-hub-add-aws-mobile-user-sign-in-customize>`.

API References
  • AWSMobileClient

    A library that initializes the SDK, constructs CredentialsProvider and AWSConfiguration objects, fetches the AWS credentials, and creates a SDK SignInUI client instance.

  • Auth UserPools

    A wrapper Library for Amazon Cognito UserPools that provides a managed Email/Password sign-in UI.

  • Auth Core

    A library that caches and federates a login provider authentication token using Amazon Cognito Federated Identities, caches the federated AWS credentials, and handles the sign-in flow.

iOS - Swift
  1. Add or update your AWS backend configuration file to incorporate your new sign-in. For details, see the last steps in the :ref:`Get Started: Set Up Your Backend <mobile-hub-add-aws-mobile-sdk-basic-setup>` section.

  2. Add the following dependencies in your project's :file:`Podfile`.

    platform :ios, '9.0'
    target :'YOUR-APP-NAME' do
        use_frameworks!
        pod 'AWSUserPoolsSignIn', '~> 2.6.13'
        pod 'AWSAuthUI', '~> 2.6.13'
        pod 'AWSMobileClient', '~> 2.6.13'
        # other pods
    end
  3. Pull the SDK libraries into your local repo.

    $ pod install --repo-update
    

    If you encounter an error message that begins "[!] Failed to connect to GitHub to update the CocoaPods/Specs . . .", and your internet connectivity is working, you may need to update openssl and Ruby.

  4. Create a AWSMobileClient and initialize the SDK.

    Add code to create an instance of AWSMobileClient in the application:open url function of your AppDelegate.swift, to resume a previously signed-in authenticated session.

    Then add another instance of AWSMobileClient in the didFinishLaunching function to register the sign in providers, and to fetch an Amazon Cognito credentials that AWS will use to authorize access once the user signs in.

    import UIKit
    
    import AWSMobileClient
    
    @UIApplicationMain
    
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        // Add a AWSMobileClient call in application:open url
        func application(_ application: UIApplication, open url: URL,
            sourceApplication: String?, annotation: Any) -> Bool {
    
            return AWSMobileClient.sharedInstance().interceptApplication(
                application, open: url,
                sourceApplication: sourceApplication,
                annotation: annotation)
    
        }
    
        // Add a AWSMobileClient call in application:didFinishLaunching
         func application(
            _ application: UIApplication,
                didFinishLaunchingWithOptions launchOptions:
                    [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
             return AWSMobileClient.sharedInstance().interceptApplication(
                 application, didFinishLaunchingWithOptions:
                 launchOptions)
        }
    
        // Other functions in AppDelegate . . .
    
      }
  5. Implement your sign-in UI by calling the library provided in the SDK.

    import UIKit
    import AWSAuthCore
    import AWSAuthUI
    
    class SampleViewController: UIViewController {
    
        override func viewDidLoad() {
    
            super.viewDidLoad()
    
            if !AWSSignInManager.sharedInstance().isLoggedIn {
               AWSAuthUIViewController
                 .presentViewController(with: self.navigationController!,
                      configuration: nil,
                      completionHandler: { (provider: AWSSignInProvider, error: Error?) in
                         if error != nil {
                             print("Error occurred: \(String(describing: error))")
                         } else {
                             // Sign in successful.
                         }
                      })
            }
        }
    }
Choose the run icon (|play|) in the top left of the Xcode window or type |Acommand|-R to build and run your app. You should see our pre-built sign-in UI for your app. Checkout the next steps to learn how to :ref:`customize your UI <mobile-hub-add-aws-mobile-user-sign-in-customize>`.
API References
  • AWSMobileClient

    A library that initializes the SDK, fetches the AWS credentials, and creates a SDK SignInUI client instance.

  • Auth UserPools

    A wrapper Library for Amazon Cognito UserPools that provides a managed Email/Password sign-in UI.

  • Auth Core

    A library that caches and federates a login provider authentication token using Amazon Cognito Federated Identities, caches the federated AWS credentials, and handles the sign-in flow.

Setup Facebook Login in your Mobile App

Android - Java
Use Android API level 23 or higher The AWS Mobile SDK library for Android sign-in (aws-android-sdk-auth-ui) provides the activity and view for presenting a SignInUI for the sign-in providers you configure. This library depends on the Android SDK API Level 23 or higher.
  1. Add or update your AWS backend configuration file to incorporate your new sign-in. For details, see the last steps in the :ref:`Get Started: Set Up Your Backend <mobile-hub-add-aws-mobile-sdk-basic-setup>` section.

  2. Add the following permissions and Activity to your AndroidManifest.xml file:

    <!-- ... -->
    
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    
    <!-- ... -->
    
    <activity
        android:name="com.facebook.FacebookActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="@string/fb_login_protocol_scheme" />
        </intent-filter>
    </activity>
    
    <!-- ... -->
    
    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id" />
    
    <!-- ... -->
  3. Add these dependencies to your app/build.gradle file:

    dependencies {
      // Mobile Client for initializing the SDK
      implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.7.+@aar') { transitive = true }
    
      // Facebook SignIn
      implementation 'com.android.support:support-v4:24.+'
      implementation ('com.amazonaws:aws-android-sdk-auth-facebook:2.7.+@aar') { transitive = true }
    
      // Sign in UI
      implementation 'com.android.support:appcompat-v7:24.+'
      implementation ('com.amazonaws:aws-android-sdk-auth-ui:2.7.+@aar') { transitive = true }
    }
  4. In :file:`strings.xml`, add string definitions for your Facebook App ID and login protocol scheme.The value should contain your Facebook AppID in both cases, the login protocol value is always prefaced with fb.

    <string name="facebook_app_id">1231231231232123123</string>
    <string name="fb_login_protocol_scheme">fb1231231231232123123</string>
  5. Create an activity that will present your sign-in screen.

    In Android Studio, choose :guilabel:`File > New > Activity > Basic Activity` and type an activity name, such as :userinput:`AuthenticatorActivity`. If you want to make this your starting activity, move the intent filter block containing .LAUNCHER to the AuthenticatorActivity in your app's :file:`AndroidManifest.xml`.

    <activity android:name=".AuthenticatorActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
  6. Update the onCreate function of your AuthenticatorActivity to call AWSMobileClient. This component provides the functionality to resume a signed-in authentication session. It makes a network call to retrieve the AWS credentials that allow users to access your AWS resources and registers a callback for when that transaction completes.

    If the user is signed in, the app goes to the NextActivity, otherwise it presents the user with the AWS Mobile ready made, configurable sign-in UI. NextActivity Activity class a user sees after a successful sign-in.

    import android.app.Activity;
    import android.os.Bundle;
    
    import com.amazonaws.mobile.auth.ui.SignInUI;
    import com.amazonaws.mobile.client.AWSMobileClient;
    import com.amazonaws.mobile.client.AWSStartupHandler;
    import com.amazonaws.mobile.client.AWSStartupResult;
    
    public class AuthenticatorActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_authenticator);
    
            // Add a call to initialize AWSMobileClient
            AWSMobileClient.getInstance().initialize(this, new AWSStartupHandler() {
                @Override
                public void onComplete(AWSStartupResult awsStartupResult) {
                    SignInUI signin = (SignInUI) AWSMobileClient.getInstance().getClient(AuthenticatorActivity.this, SignInUI.class);
                    signin.login(AuthenticatorActivity.this, NextActivity.class).execute();
                }
            }).execute();
        }
    }

Choose the run icon (|play|) in Android Studio to build your app and run it on your device/emulator. You should see our ready made sign-in UI for your app. Checkout the next steps to learn how to :ref:`customize your UI <mobile-hub-add-aws-mobile-user-sign-in-customize>`.

API References
  • AWSMobileClient

    A library that initializes the SDK, constructs CredentialsProvider and AWSConfiguration objects, fetches the AWS credentials, and creates a SDK SignInUI client instance.

  • Auth UserPools

    A wrapper Library for Amazon Cognito UserPools that provides a managed Email/Password sign-in UI.

  • Auth Core

    A library that caches and federates a login provider authentication token using Amazon Cognito Federated Identities, caches the federated AWS credentials, and handles the sign-in flow.

Android - Kotlin
Use Android API level 23 or higher The AWS Mobile SDK library for Android sign-in (aws-android-sdk-auth-ui) provides the activity and view for presenting a SignInUI for the sign-in providers you configure. This library depends on the Android SDK API Level 23 or higher.
  1. Add or update your AWS backend configuration file to incorporate your new sign-in. For details, see the last steps in the :ref:`Get Started: Set Up Your Backend <mobile-hub-add-aws-mobile-sdk-basic-setup>` section.

  2. Add the following permissions and Activity to your AndroidManifest.xml file:

    <!-- ... -->
    
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    
    <!-- ... -->
    
    <activity
        android:name="com.facebook.FacebookActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="@string/fb_login_protocol_scheme" />
        </intent-filter>
    </activity>
    
    <!-- ... -->
    
    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id" />
    
    <!-- ... -->
  3. Add these dependencies to your app/build.gradle file:

    dependencies {
      // Mobile Client for initializing the SDK
      implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.7.+@aar') { transitive = true }
    
      // Facebook SignIn
      implementation 'com.android.support:support-v4:24.+'
      implementation ('com.amazonaws:aws-android-sdk-auth-facebook:2.7.+@aar') { transitive = true }
    
      // Sign in UI
      implementation 'com.android.support:appcompat-v7:24.+'
      implementation ('com.amazonaws:aws-android-sdk-auth-ui:2.7.+@aar') { transitive = true }
    }
  4. In :file:`strings.xml`, add string definitions for your Facebook App ID and login protocol scheme.The value should contain your Facebook AppID in both cases, the login protocol value is always prefaced with fb.

    <string name="facebook_app_id">1231231231232123123</string>
    <string name="fb_login_protocol_scheme">fb1231231231232123123</string>
  5. Create an activity that will present your sign-in screen.

    In Android Studio, choose :guilabel:`File > New > Activity > Basic Activity` and type an activity name, such as :userinput:`AuthenticatorActivity`. If you want to make this your starting activity, move the intent filter block containing .LAUNCHER to the AuthenticatorActivity in your app's :file:`AndroidManifest.xml`.

    <activity android:name=".AuthenticatorActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
  6. Update the onCreate function of your AuthenticatorActivity to call AWSMobileClient. This component provides the functionality to resume a signed-in authentication session. It makes a network call to retrieve the AWS credentials that allow users to access your AWS resources and registers a callback for when that transaction completes.

    If the user is signed in, the app goes to the NextActivity, otherwise it presents the user with the AWS Mobile ready made, configurable sign-in UI. NextActivity Activity class a user sees after a successful sign-in.

    import android.app.Activity;
    import android.os.Bundle;
    
    import com.amazonaws.mobile.auth.ui.SignInUI;
    import com.amazonaws.mobile.client.AWSMobileClient;
    import com.amazonaws.mobile.client.AWSStartupHandler;
    import com.amazonaws.mobile.client.AWSStartupResult;
    
      class AuthenticatorActivity : Activity() {
        override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
    
        AWSMobileClient.getInstance().initialize(this) {
            val ui = AWSMobileClient.getInstance().getClient(
                  this@AuthenticatorActivity,
                  SignInUI::class.java) as SignInUI?
            ui?.login(
                  this@AuthenticatorActivity,
                  MainActivity::class.java)?.execute()
        }.execute()
      }

Choose the run icon (|play|) in Android Studio to build your app and run it on your device/emulator. You should see our ready made sign-in UI for your app. Checkout the next steps to learn how to :ref:`customize your UI <mobile-hub-add-aws-mobile-user-sign-in-customize>`.

API References
  • AWSMobileClient

    A library that initializes the SDK, constructs CredentialsProvider and AWSConfiguration objects, fetches the AWS credentials, and creates a SDK SignInUI client instance.

  • Auth UserPools

    A wrapper Library for Amazon Cognito UserPools that provides a managed Email/Password sign-in UI.

  • Auth Core

    A library that caches and federates a login provider authentication token using Amazon Cognito Federated Identities, caches the federated AWS credentials, and handles the sign-in flow.

iOS - Swift
  1. Add or update your AWS backend configuration file to incorporate your new sign-in. For details, see the last steps in the :ref:`Get Started: Set Up Your Backend <mobile-hub-add-aws-mobile-sdk-basic-setup>` section.

  2. Add the following dependencies in your project's :file:`Podfile`.

    platform :ios, '9.0'
      target :'YOUR-APP-NAME' do
        use_frameworks!
        pod 'AWSMobileClient', '~> 2.6.13'
        pod 'AWSFacebookSignIn', '~> 2.6.13'
        pod 'AWSAuthUI', '~> 2.6.13'
        # other pods
      end

    Run pod install --repo-update.

    If you encounter an error message that begins "[!] Failed to connect to GitHub to update the CocoaPods/Specs . . .", and your internet connectivity is working, you may need to update openssl and Ruby.

  3. Add Facebook meta data to :file:`Info.plist`.

    To configure your Xcode project to use Facebook Login, right-choose :file:`Info.plist` and then choose :guilabel:`Open As > Source Code`.

    Add the following entry, using your project name, Facebook ID and login scheme ID.

    <plist version="1.0">
    <!-- ... -->
    <dict>
    <key>FacebookAppID</key>
    <string>0123456789012345</string>
    <key>FacebookDisplayName</key>
    <string>YOUR-PROJECT-NAME</string>
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>fbapi</string>
        <string>fb-messenger-api</string>
        <string>fbauth2</string>
        <string>fbshareextension</string>
    </array>
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>fb0123456789012345</string>
            </array>
        </dict>
    </array>
    </dict>
    <!-- ... -->
  4. Create a AWSMobileClient and initialize the SDK.

    Add code to create an instance of AWSMobileClient in the application:open url function of your AppDelegate.swift, to resume a previously signed-in authenticated session.

    Then add another instance of AWSMobileClient in the didFinishLaunching function to register the sign in providers, and to fetch an Amazon Cognito credentials that AWS will use to authorize access once the user signs in.

    import UIKit
    
    //import AWSMobileClient
    import AWSMobileClient
    
    @UIApplicationMain
    
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        // Add a AWSMobileClient call in application:open url
        func application(_ application: UIApplication, open url: URL,
            sourceApplication: String?, annotation: Any) -> Bool {
    
            return AWSMobileClient.sharedInstance().interceptApplication(
                application, open: url,
                sourceApplication: sourceApplication,
                annotation: annotation)
    
        }
    
        // Add a AWSMobileClient call in application:didFinishLaunching
         func application(
            _ application: UIApplication,
                didFinishLaunchingWithOptions launchOptions:
                    [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
             return AWSMobileClient.sharedInstance().interceptApplication(
                 application, didFinishLaunchingWithOptions:
                 launchOptions)
        }
    
        // Other functions in AppDelegate . . .
    
      }
  5. Implement your sign-in UI by calling the library provided by the SDK.

    import UIKit
    import AWSAuthCore
    import AWSAuthUI
    
    class SampleViewController: UIViewController {
    
        override func viewDidLoad() {
    
            super.viewDidLoad()
    
            if !AWSSignInManager.sharedInstance().isLoggedIn {
               AWSAuthUIViewController
                 .presentViewController(with: self.navigationController!,
                      configuration: nil,
                      completionHandler: { (provider: AWSSignInProvider, error: Error?) in
                         if error != nil {
                             print("Error occurred: \(String(describing: error))")
                         } else {
                             // sign in successful.
                         }
                      })
            }
        }
    }

Choose the run icon (|play|) in the top left of the Xcode window or type |Acommand|-R to build and run your app. You should see our pre-built sign-in UI for your app. Checkout the next steps to learn how to :ref:`customize your UI <mobile-hub-add-aws-mobile-user-sign-in-customize>`.

API References
  • AWSMobileClient

    A library that initializes the SDK, fetches the AWS credentials, and creates a SDK SignInUI client instance.

  • Auth UserPools

    A wrapper Library for Amazon Cognito UserPools that provides a managed Email/Password sign-in UI.

  • Auth Core

    A library that caches and federates a login provider authentication token using Amazon Cognito Federated Identities, caches the federated AWS credentials, and handles the sign-in flow.

Setup Google Login in your Mobile App

Android - Java
Use Android API level 23 or higher The AWS Mobile SDK library for Android sign-in (aws-android-sdk-auth-ui) provides the activity and view for presenting a SignInUI for the sign-in providers you configure. This library depends on the Android SDK API Level 23 or higher.
  1. Add or update your AWS backend configuration file to incorporate your new sign-in. For details, see the last steps in the :ref:`Get Started: Set Up Your Backend <mobile-hub-add-aws-mobile-sdk-basic-setup>` section.

  2. Add these permissions to your AndroidManifest.xml file:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  3. Add these dependencies to your app/build.gradle file:

    dependencies {
        // Mobile Client for initializing the SDK
        implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.7.+@aar') { transitive = true }
    
        // Google SignIn
        implementation 'com.android.support:support-v4:24.+'
        implementation ('com.amazonaws:aws-android-sdk-auth-google:2.7.+@aar') { transitive = true }
    
        // Sign in UI Library
        implementation 'com.android.support:appcompat-v7:24.+'
        implementation ('com.amazonaws:aws-android-sdk-auth-ui:2.7.+@aar') { transitive = true }
    }
  4. Create an activity that will present your sign-in screen.

    In Android Studio, choose :guilabel:`File > New > Activity > Basic Activity` and type an activity name, such as :userinput:`AuthenticatorActivity`. If you want to make this your starting activity, move the intent filter block containing .LAUNCHER to the AuthenticatorActivity in your app's :file:`AndroidManifest.xml`.

    <activity android:name=".AuthenticatorActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
  5. Update the onCreate function of your AuthenticatorActivity to call AWSMobileClient. This component provides the functionality to resume a signed-in authentication session. It makes a network call to retrieve the AWS credentials that allow users to access your AWS resources and registers a callback for when that transaction completes.

    If the user is signed in, the app goes to the NextActivity, otherwise it presents the user with the AWS Mobile ready made, configurable sign-in UI. NextActivity Activity class a user sees after a successful sign-in.

    import android.app.Activity;
    import android.os.Bundle;
    
    import com.amazonaws.mobile.auth.ui.SignInUI;
    import com.amazonaws.mobile.client.AWSMobileClient;
    import com.amazonaws.mobile.client.AWSStartupHandler;
    import com.amazonaws.mobile.client.AWSStartupResult;
    
    public class AuthenticatorActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_authenticator);
    
            // Add a call to initialize AWSMobileClient
            AWSMobileClient.getInstance().initialize(this, new AWSStartupHandler() {
                @Override
                public void onComplete(AWSStartupResult awsStartupResult) {
                    SignInUI signin = (SignInUI) AWSMobileClient.getInstance().getClient(AuthenticatorActivity.this, SignInUI.class);
                    signin.login(AuthenticatorActivity.this, MainActivity.class).execute();
                }
            }).execute();
        }
    }

Choose the run icon (|play|) in Android Studio to build your app and run it on your device/emulator. You should see our ready made sign-in UI for your app. Checkout the next steps to learn how to :ref:`customize your UI <mobile-hub-add-aws-mobile-user-sign-in-customize>`.

API References
  • AWSMobileClient

    A library that initializes the SDK, constructs CredentialsProvider and AWSConfiguration objects, fetches the AWS credentials, and creates a SDK SignInUI client instance.

  • Auth UserPools

    A wrapper Library for Amazon Cognito UserPools that provides a managed Email/Password sign-in UI.

  • Auth Core

    A library that caches and federates a login provider authentication token using Amazon Cognito Federated Identities, caches the federated AWS credentials, and handles the sign-in flow.

Android - Kotlin
Use Android API level 23 or higher The AWS Mobile SDK library for Android sign-in (aws-android-sdk-auth-ui) provides the activity and view for presenting a SignInUI for the sign-in providers you configure. This library depends on the Android SDK API Level 23 or higher.
  1. Add or update your AWS backend configuration file to incorporate your new sign-in. For details, see the last steps in the :ref:`Get Started: Set Up Your Backend <mobile-hub-add-aws-mobile-sdk-basic-setup>` section.

  2. Add these permissions to your AndroidManifest.xml file:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  3. Add these dependencies to your app/build.gradle file:

    dependencies {
        // Mobile Client for initializing the SDK
        implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.7.+@aar') { transitive = true }
    
        // Google SignIn
        implementation 'com.android.support:support-v4:24.+'
        implementation ('com.amazonaws:aws-android-sdk-auth-google:2.7.+@aar') { transitive = true }
    
        // Sign in UI Library
        implementation 'com.android.support:appcompat-v7:24.+'
        implementation ('com.amazonaws:aws-android-sdk-auth-ui:2.7.+@aar') { transitive = true }
    }
  4. Create an activity that will present your sign-in screen.

    In Android Studio, choose :guilabel:`File > New > Activity > Basic Activity` and type an activity name, such as :userinput:`AuthenticatorActivity`. If you want to make this your starting activity, move the intent filter block containing .LAUNCHER to the AuthenticatorActivity in your app's :file:`AndroidManifest.xml`.

    <activity android:name=".AuthenticatorActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
  5. Update the onCreate function of your AuthenticatorActivity to call AWSMobileClient. This component provides the functionality to resume a signed-in authentication session. It makes a network call to retrieve the AWS credentials that allow users to access your AWS resources and registers a callback for when that transaction completes.

    If the user is signed in, the app goes to the NextActivity, otherwise it presents the user with the AWS Mobile ready made, configurable sign-in UI. NextActivity Activity class a user sees after a successful sign-in.

    import android.app.Activity;
    import android.os.Bundle;
    
    import com.amazonaws.mobile.auth.ui.SignInUI;
    import com.amazonaws.mobile.client.AWSMobileClient;
    import com.amazonaws.mobile.client.AWSStartupHandler;
    import com.amazonaws.mobile.client.AWSStartupResult;
    
      class AuthenticatorActivity : Activity() {
        override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
    
        AWSMobileClient.getInstance().initialize(this) {
            val ui = AWSMobileClient.getInstance().getClient(
                  this@AuthenticatorActivity,
                  SignInUI::class.java) as SignInUI?
            ui?.login(
                  this@AuthenticatorActivity,
                  MainActivity::class.java)?.execute()
        }.execute()
    }

Choose the run icon (|play|) in Android Studio to build your app and run it on your device/emulator. You should see our ready made sign-in UI for your app. Checkout the next steps to learn how to :ref:`customize your UI <mobile-hub-add-aws-mobile-user-sign-in-customize>`.

API References
  • AWSMobileClient

    A library that initializes the SDK, constructs CredentialsProvider and AWSConfiguration objects, fetches the AWS credentials, and creates a SDK SignInUI client instance.

  • Auth UserPools

    A wrapper Library for Amazon Cognito UserPools that provides a managed Email/Password sign-in UI.

  • Auth Core

    A library that caches and federates a login provider authentication token using Amazon Cognito Federated Identities, caches the federated AWS credentials, and handles the sign-in flow.

iOS - Swift
  1. Add or update your AWS backend configuration file to incorporate your new sign-in. For details, see the last steps in the :ref:`Get Started: Set Up Your Backend <mobile-hub-add-aws-mobile-sdk-basic-setup>` section.

  2. Add the following dependencies in the Podfile.

    platform :ios, '9.0'
      target :'YOUR-APP-NAME' do
        use_frameworks!
        pod 'AWSMobileClient', '~> 2.6.13'
        pod 'AWSGoogleSignIn', '~> 2.6.13'
        pod 'AWSAuthUI', '~> 2.6.13'
        pod 'GoogleSignIn', '~> 4.0'
        # other pods
      end

    Run pod install --repo-update before you continue.

    If you encounter an error message that begins "[!] Failed to connect to GitHub to update the CocoaPods/Specs . . .", and your internet connectivity is working, you may need to update openssl and Ruby.

  3. Add Google metadata to info.plist

    To configure your Xcode project to use Google Login, open its Info.plist file using Right-click > Open As > Source Code. Add the following entry. Substitute your project name for the placeholder string.

    <plist version="1.0">
    <!-- ... -->
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>com.googleusercontent.apps.xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</string>
        </array>
        </dict>
    </array>
    <!-- ... -->
  4. Create a AWSMobileClient and initialize the SDK.

    Add code to create an instance of AWSMobileClient in the application:open url function of your AppDelegate.swift, to resume a previously signed-in authenticated session.

    Then add another instance of AWSMobileClient in the didFinishLaunching function to register the sign in providers, and to fetch an Amazon Cognito credentials that AWS will use to authorize access once the user signs in.

    import UIKit
    
    //import AWSMobileClient
    import AWSMobileClient
    
    @UIApplicationMain
    
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        // Add a AWSMobileClient call in application:open url
        func application(_ application: UIApplication, open url: URL,
            sourceApplication: String?, annotation: Any) -> Bool {
    
            return AWSMobileClient.sharedInstance().interceptApplication(
                application, open: url,
                sourceApplication: sourceApplication,
                annotation: annotation)
    
        }
    
        // Add a AWSMobileClient call in application:didFinishLaunching
        func application(
            _ application: UIApplication,
                didFinishLaunchingWithOptions launchOptions:
                    [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
             return AWSMobileClient.sharedInstance().interceptApplication(
                 application, didFinishLaunchingWithOptions:
                 launchOptions)
        }
    
        // Other functions in AppDelegate . . .
    
      }
  5. Implement your sign-in UI by calling the library provided by the SDK.

    import UIKit
    import AWSAuthCore
    import AWSAuthUI
    
    class SampleViewController: UIViewController {
    
        override func viewDidLoad() {
    
            super.viewDidLoad()
    
            if !AWSSignInManager.sharedInstance().isLoggedIn {
               AWSAuthUIViewController
                 .presentViewController(with: self.navigationController!,
                      configuration: nil,
                      completionHandler: { (provider: AWSSignInProvider, error: Error?) in
                         if error != nil {
                             print("Error occurred: \(String(describing: error))")
                         } else {
                             // Sign in successful.
                         }
                      })
            }
        }
    }

Choose the run icon (|play|) in the top left of the Xcode window or type |Acommand|-R to build and run your app. You should see our pre-built sign-in UI for your app. Checkout the next steps to learn how to :ref:`customize your UI <mobile-hub-add-aws-mobile-user-sign-in-customize>`.

API References
  • AWSMobileClient

    A library that initializes the SDK, fetches the AWS credentials, and creates a SDK SignInUI client instance.

  • Auth UserPools

    A wrapper Library for Amazon Cognito UserPools that provides a managed Email/Password sign-in UI.

  • Auth Core

    A library that caches and federates a login provider authentication token using Amazon Cognito Federated Identities, caches the federated AWS credentials, and handles the sign-in flow.

Enable Sign-out

Android - Java

To enable a user to sign-out of your app, register a callback for sign-in events by adding a SignInStateChangeListener to IdentityManager. The listener captures both onUserSignedIn and onUserSignedOut events.

IdentityManager.getDefaultIdentityManager().addSignInStateChangeListener(new SignInStateChangeListener() {
    @Override
    // Sign-in listener
    public void onUserSignedIn() {
        Log.d(LOG_TAG, "User Signed In");
    }

    // Sign-out listener
    @Override
    public void onUserSignedOut() {

        // return to the sign-in screen upon sign-out
       showSignIn();
    }
});

To initiate a sign-out, call the signOut method of IdentityManager.

IdentityManager.getDefaultIdentityManager().signOut();
Android - Kotlin

To enable a user to sign-out of your app, register a callback for sign-in events by adding a SignInStateChangeListener to IdentityManager. The listener captures both onUserSignedIn and onUserSignedOut events.

IdentityManager.getDefaultIdentityManager().addSignInStateChangeListener(
    object : SignInStateChangeListener() {
        override fun onUserSignedIn() {
            Log.d(TAG, "User signed in");
        }

        override fun onUserSignedOut() {
            Log.d(TAG, "User signed out");
        }
    }
);

To initiate a sign-out, call the signOut method of IdentityManager.

IdentityManager.getDefaultIdentityManager().signOut();
iOS - Swift

To initiate a sign-out, add a call to AWSSignInManager.sharedInstance().logout.

@IBAction func signOutButtonPress(_ sender: Any) {

    AWSSignInManager.sharedInstance().logout(completionHandler: {(result: Any?, error: Error?) in
        self.showSignIn()
        // print("Sign-out Successful: \(signInProvider.getDisplayName)");

    })
}

Next Steps