Name:
interface
Value:
Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Sep 10, 2024

Add social provider sign-in

You can enable your users to sign-in and authenticate with your app using their existing accounts with social providers like Apple, Amazon, Facebook, and Google. Once you configure your backend resources, you can then configure your app to sign in users for that provider. This process will securely exchange credentials and gather user information. This information can then be used to create a new user in your app or link the social account to an existing user. Incorporating social provider sign-in provides your users with a streamlined registration, more sign-in options, and an integrated experience across their existing accounts and your app.

In this guide we will review how you can add sign-in with social providers by first setting up your developer account with the provider. After this step, you can then configure your Auth category and integrate social sign-in with your app.

Before you begin, you will need:

  • An Amplify project
  • The Amplify libraries installed and configured
Learn more
Review how OAuth authentication works

The preferred way to incorporate social provider sign-in is via an OAuth redirect which lets users sign in using their social media account and creates a corresponding user in the Cognito User Pool.

OAuth 2.0 is the common Authorization framework used by web and mobile applications for accessing user information ("scopes") in a limited manner. Common analogies you will hear in OAuth is that of boarding a plane or staying in a hotel - showing your identification is the authentication piece (signing into an app) and using the boarding pass/hotel key is what you are authorized to access.

OAuth support in Amplify uses Cognito User Pools and supports federation with social providers, which will automatically create a corresponding user in the User Pool after they sign in. With this design you do not need to include an SDK for the social provider in your app. After you set up your developer account with these social providers you can configure the Auth category by running amplify add auth and selecting the social provider option. You can then use signInWithRedirect() in your app to either show a pre-built "Hosted UI" or pass in a provider name (e.g. signInWithRedirect({provider:'Facebook'})) to interface directly and build your own UI. Image

Set up your social auth provider

Before you configure social sign-in with Amplify Auth you will need to set up your developer account with each provider you are using.

Note: Amazon Cognito provides first class support for Facebook Login, Google Sign-In, Login with Amazon, and Sign in with Apple for seamless setup. However you can configure other Identity Providers that support SAML or OpenID Connect (OIDC).

  1. Create a developer account with Facebook.

  2. Sign in with your Facebook credentials.

  3. Choose My Apps from the top navigation bar, and on the page that loads choose Create App. Create App button in the My Apps page of the Facebook developer account.

  4. For your use case, choose Set up Facebook Login. Set up Facebook Login option selected from list.

  5. For platform, choose Website and select No, I'm not building a game.

  6. Give your Facebook app a name and choose Create app. Form fields for the Facebook create app form.

  7. On the left navigation bar, choose Settings and then Basic. App ID and App Secret in the basic settings tab of the dashboard.

  8. Note the App ID and the App Secret. You will use them in the next section in the CLI flow.

  1. Go to Google developer console.

  2. Click Select a project. Select a project button on the nav bar is circled.

  3. Click NEW PROJECT. The new project button is circled on the select a project popup.

  4. Type in project name and click CREATE. The create button is circled in the new project page.

  5. Once the project is created, from the left navigation menu, select APIs & Services, then select Credentials. The top left menu icon is selected, then the APIs and services option, then the credentials option.

  6. Click CONFIGURE CONSENT SCREEN. The configure consent screen button is circled in the oauth consent screen section.

  7. Click CREATE. The create button is circled in the OAuth consent screen section.

  8. Type in App Information and Developer contact information which are required fields and click SAVE AND CONTINUE three times (OAuth consent screen -> Scopes -> Test Users) to finish setting up the consent screen.

  9. Back under the Credentials tab, Create your OAuth2.0 credentials by choosing OAuth client ID from the Create credentials drop-down list. The Create credentials button is circled, then the oauth client ID button is circled in the credentials section..

  10. Choose Web application as Application type and name your OAuth Client.

  11. Click Create.

  12. Take note of Your client ID and Your Client Secret. You will need them for the next section in the CLI flow.

  13. Choose OK.

  1. Create a developer account with Amazon.

  2. Sign in with your Amazon credentials.

  3. You need to create an Amazon security profile to receive the Amazon Client ID and Client Secret. Choose Create a Security Profile. The login with Amazon console with a create a new security profile button displayed.

  4. Type in a Security Profile Name, a Security Profile Description, and a Consent Privacy Notice URL. Security profile management page with steps to fill out a form for the new security profile.

  5. Choose Save.

  6. Choose Show Client ID and Client Secret to show the client ID and secret. You will need them for the next section in the CLI flow. Choosing client ID and client secret.

  1. Sign In with your Apple developer credentials.

  2. On the main developer portal page, select Certificates, IDs, & Profiles.

  3. On the left navigation bar, select Identifier.

  4. On the Identifiers page, select the plus icon (+).

  5. On the Register a New Identifier page, select App IDs.

  6. On the Register an App ID page, under App ID Prefix, take note of the Team ID value.

  7. Provide a description in the Description text box and provide the bundleID of the iOS app. Register an App ID in the certificates, identifiers and profiles section.

  8. Under Capabilities, select Sign in with Apple.

  9. Select Continue, review the configuration, and then select Register.

  10. On the Identifiers page, on the right, select App IDs, and then select Services ID.

  11. Select the plus icon (+) and, on the Register a New Identifier page, select Services IDs.

  12. Provide a description in the Description text box and provide an identifier for the Service ID. Register a services ID in the certificates, identifiers and profiles section.

  13. Select Continue and register the Service ID.

Your developer accounts with the social providers are now set up and you can return to your Amplify project for next steps.

Configure the Auth category

Once you have the social providers configured you can update your Auth configuration through the Amplify CLI.

When configuring social sign-in through the Amplify CLI, it's important to exercise caution when designating attributes as "required". Each social identity provider has different information they send back to Cognito. User Pool attributes that are initially set up as "required" cannot be changed later. You may have to migrate the users or create a new User Pool if you need to change requirements.

To begin with the CLI, run the following in your project’s root folder:

amplify add auth ## "amplify update auth" if already configured

Choose the following options:

? Do you want to use the default authentication and security configuration?
`Default configuration with Social Provider (Federation)`
? 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 you want us to create for you?
`(default)`
? Enter your redirect signin URI:
`myapp://`
? Do you want to add another redirect signin URI
`No`
? Enter your redirect signout URI:
`myapp://`
? Do you want to add another redirect signout URI
`No`
? Select the social providers you want to configure for your user pool:
`<choose your provider and follow the prompts to input the proper tokens>`

Note: You can configure your application to use more than one redirect URL. For more information, refer to the Redirect URLs section below.

Next, run amplify push to publish your changes. Once finished, it will display an auto generated URL for your web UI. You can retrieve your user pool domain URL at anytime by running amplify status using the CLI.

You need to now inform your social provider of this URL:

  1. Sign In to your Facebook developer account with your Facebook credentials.

  2. Choose My Apps from the top navigation bar, and on the Apps page, choose your app you created before.

  3. On the left navigation bar, choose Products. Add Facebook Login if it isn't already added.

  4. If already added, choose Settings under the Configure dropdown. The Settings option is circled from the configure dropdown.

  5. Under Valid OAuth Redirect URIs type your user pool domain with the /oauth2/idpresponse endpoint.

    https://<your-user-pool-domain>/oauth2/idpresponse

Userpool domain is pasted into the text field with /oauth2/ endpoint.

  1. Save your changes.
  1. Go to the Google developer console.

  2. On the left navigation bar, look for APIs and Services under Pinned or under More Products if not pinned.

  3. Within the APIs and Services sub menu, choose Credentials.

  4. Select the client you created in the first step and click the Edit button.

  5. Type your user pool domain into the Authorized Javascript origins form.

  6. Type your user pool domain with the /oauth2/idpresponse endpoint into Authorized Redirect URIs.

    The URLs 1 form fields for authorized Javascript origins and authorized redirect URLs are circled.

    Note: If you saw an error message Invalid Redirect: domain must be added to the authorized domains list before submitting. when adding the endpoint, please go to the Authorized Domains List and add the domain.

  7. Click Save.

  1. Sign in with your Amazon credentials.

  2. Hover over the gear and choose Web Settings associated with the security profile you created in the previous step, and then choose Edit. The web settings option is selected in the dropdown menu from the gear icon.

  3. Type your user pool domain into Allowed Origins and type your user pool domain with the /oauth2/idpresponse endpoint into Allowed Return URLs. Userpool domain is typed into the allowed origins field with /oauth2/ as the endpoint in the Allowed Return URLs field.

  4. Choose Save.

  1. Sign In with your Apple developer credentials.

  2. On the main developer portal page, select Certificates, IDs, & Profiles.

  3. On the left navigation bar, select Identifiers and then select Service IDs from the drop down list on the right.

  4. Select the Service ID created when you set up your auth provider as outlined in the section above.

  5. Enable Sign In with Apple and select Configure.

  6. Under Primary App ID select the App ID that was created before.

  7. Type your user pool domain into Domains and Subdomains.

  8. Type your user pool domain with the /oauth2/idpresponse endpoint into Return URLs. The return URLs text field is selected.

  9. Click Next, review the information, then select Done.

  10. On Edit your Services ID Configuration click Continue, review the information, then select Save.

  11. On the main Certificates, Identifiers & Profiles, select Keys.

  12. On the Keys page, select the plus icon (+).

  13. Provide a name for the key under Key Name.

  14. Enable Sign in with Apple and select Configure. The sign in with apple option is enabled and the key name text field is filled out.

  15. Under Primary App ID select the App ID that was created before.

  16. Click on Save.

  17. On Register a New Key click Continue, review the information, then select Register.

  18. You will be redirected to a new page. Take note of the Key ID and download the .p8 file containing the private key. The download key page is shown with the option to download the .p8 file with the private key.

Note: Federated sign-in does not invoke any Custom authentication challenge Lambda triggers, Migrate user Lambda trigger, Custom message Lambda trigger, or Custom sender Lambda triggers in your user pool. For information on the supported Lambda triggers refer to the AWS documentation

You have configured your Auth category and updated your URL with the social providers. You can now set up the frontend for your app.

Install native module

signInWithRedirect displays the sign-in UI inside a platform-dependent webview. On iOS devices, an ASWebAuthenticationSession will be launched and, on Android, a Custom Tab. After the sign-in process is complete, the sign-in UI will redirect back to your app.

To enable this capability, an additional dependency must be installed.

npm install @aws-amplify/rtn-web-browser

Platform Setup

On iOS, there should be no additional setup steps.

Android

After a successful sign-in, the sign-in UI will attempt to redirect back to your application. To register the redirect URI scheme you configured above with the device, an intent-filter must be added to your application's AndroidManifest.xml file which should be located in your React Native app's android/app/src/main directory.

Add the intent-filter to your application's main activity, replacing myapp with your redirect URI scheme as necessary.

<application ...>
<activity android:name=".MainActivity" ...>
...
<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="myapp" />
</intent-filter>
...
</activity>
</application>

Set up your frontend

After configuring the OAuth endpoints (with Cognito Hosted UI), you can integrate your app by invoking the signInWithRedirect function which will redirect the user to the Cognito Hosted UI and provide options to sign in via username and password as well as any of the Social providers you have configured. Also, note that passing Amazon, Apple, Facebook or Google on the provider argument (e.g signInWithRedirect({ provider: 'Amazon' })) will bypass the Hosted UI and federate immediately with the social provider as shown in the below example.

Note: You can also use the Authenticator UI component to add social sign in flow to your application. The Authenticator reads directly from your Amplify configured socialProviders. Visit Social Provider section to learn more.

Add custom state

A custom state is not required, but if you are looking to add one, you are able to do so by passing a string value (e.g. signInWithRedirect({ customState: 'xyz' })) and listening for the custom state via Hub. You can also use the Hub eventing system to catch errors using signInWithRedirect() to listen for the signInWithRedirect_failure event.

import React, { useEffect, useState } from "react";
import {
Button,
SafeAreaView,
Text,
} from "react-native";
import { AuthUser, getCurrentUser, signInWithRedirect, signOut } from "aws-amplify/auth";
import { Hub } from "@aws-amplify/core";
function App(): JSX.Element {
const [user, setUser] = useState<AuthUser | null>(null);
const [error, setError] = useState<unknown>(null);
const [customState, setCustomState] = useState<string | null>(null);
useEffect(() => {
const unsubscribe = Hub.listen("auth", ({ payload }) => {
switch (payload.event) {
case "signInWithRedirect":
getUser();
break;
case "signInWithRedirect_failure":
setError("An error has occurred during the OAuth flow.");
break;
case "customOAuthState":
setCustomState(payload.data); // this is the customState provided on signInWithRedirect function
break;
}
});
getUser();
return unsubscribe;
}, []);
const getUser = async (): Promise<void> => {
try {
const currentUser = await getCurrentUser();
setUser(currentUser);
} catch (error) {
console.error(error);
console.log("Not signed in");
}
};
return (
<SafeAreaView>
<Button title="Sign In" onPress={() => signInWithRedirect({ customState: "shopping-cart"})}></Button>
<Text>{user?.username}</Text>
<Text>{customState}</Text>
<Button title="Sign Out" onPress={() => signOut()}></Button>
</SafeAreaView>
);
}
import React, { useEffect, useState } from "react";
import {
Button,
SafeAreaView,
Text,
} from "react-native";
import { getCurrentUser, signInWithRedirect, signOut } from "aws-amplify/auth";
import { Hub } from "@aws-amplify/core";
function App() {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
const [customState, setCustomState] = useState(null);
useEffect(() => {
const unsubscribe = Hub.listen("auth", ({ payload }) => {
switch (payload.event) {
case "signInWithRedirect":
getUser();
break;
case "signInWithRedirect_failure":
setError("An error has occurred during the OAuth flow.");
break;
case "customOAuthState":
setCustomState(payload.data);
break;
}
});
getUser();
return unsubscribe;
}, []);
const getUser = async () => {
try {
const currentUser = await getCurrentUser();
setUser(currentUser);
} catch (error) {
console.error(error);
console.log("Not signed in");
}
};
return (
<SafeAreaView>
<Button title="Sign In" onPress={() => signInWithRedirect({ customState: "shopping-cart"})}></Button>
<Text>{user?.username}</Text>
<Text>{customState}</Text>
<Button title="Sign Out" onPress={() => signOut()}></Button>
</SafeAreaView>
);
}

Redirect URLs

Sign in & Sign out redirect URL(s) are used to redirect end users after the sign in or sign out operation has occurred. You may want to specify multiple URLs for various use-cases such as having different URLs for development/ production or redirect users to an intermediate URL before returning them to the app.

Specifying a redirect URL on sign out

If you have multiple sign out redirect URLs configured, you may choose to override the default behavior of selecting a redirect URL and provide the one of your choosing when calling signOut. The provided redirect URL should match at least one of the configured redirect URLs. If no redirect URL is provided to signOut, the first item from the the configured redirect URLs list that does not contain a HTTP nor HTTPS prefix will be picked.

import { Amplify } from 'aws-amplify';
import { signOut } from 'aws-amplify/auth';
// Assuming the following URLS were provided manually or via the Amplify configuration file,
// redirectSignOut: 'myDevApp://,https://authProvider/logout/?logout_uri=myDevApp://'
signOut({
global: false,
oauth: {
redirectUrl: 'https://authProvider/logout/?logout_uri=myDevApp://'
}
});
Irrespective of whether a redirectUrl is provided to signOut, a URL that does not contain http or https is expected to be present in the configured redirect URL list. This is because iOS requires an appScheme when creating the web session.

Custom Providers

When using custom providers that are not provided by default in Cognito, you can pass an object to the provider parameter with the name of your custom provider.

import { signInWithRedirect } from 'aws-amplify/auth';
const provider = {
custom: 'MyCustomOIDCProvider'
}
function handleSignInClick() {
signInWithRedirect({ provider })
}

Deploy your backend environment with auth parameters for social sign-in

When you create or update your authentication configuration, Amplify will setup the configuration locally, but it does not automatically deploy the changes to your backend environment. You will need to run amplify push to deploy the changes to your backed environment.

Conclusion

Congratulations! You finished the Add social provider sign-in guide. In this guide, you learned how to set up your social auth provider, configure the Amplify Auth category for social sign-in, and set up the frontend. Your users can now sign into your app using their social provider accounts.

Next steps

Now that you have social provider sign-in you may also want to learn additional ways to customize these workflows. We recommend you learn more about: