Page updated Feb 19, 2024

Preview: AWS Amplify's new code-first DX (Gen 2)

The next generation of Amplify's backend building experience with a TypeScript-first DX.

Get started

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:

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

Choose the following options:

1? Do you want to use the default authentication and security configuration?
2 `Default configuration with Social Provider (Federation)`
3? How do you want users to be able to sign in?
4 `Username`
5? Do you want to configure advanced settings?
6 `No, I am done.`
7? What domain name prefix you want us to create for you?
8 `(default)`
9? Enter your redirect signin URI:
10 `http://localhost:3000/`
11? Do you want to add another redirect signin URI
12 `No`
13? Enter your redirect signout URI:
14 `http://localhost:3000/`
15? Do you want to add another redirect signout URI
16 `No`
17? Select the social providers you want to configure for your user pool:
18 `<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.

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. 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.

1import { Hub } from "aws-amplify/utils";
2import { signInWithRedirect, getCurrentUser, AuthUser } from "aws-amplify/auth";
3
4Hub.listen("auth", ({ payload }) => {
5 switch (payload.event) {
6 case "signInWithRedirect":
7 const user = await getCurrentUser();
8 console.log(user.username);
9 break;
10 case "signInWithRedirect_failure":
11 // handle sign in failure
12 break;
13 case "customOAuthState":
14 const state = payload.data; // this will be customState provided on signInWithRedirect function
15 console.log(state);
16 break;
17 }
18});
19
20function handleSignInClick(customState: string) {
21 signInWithRedirect({
22 provider: "Google",
23 customState
24 });
25}
1import { Hub } from "aws-amplify/utils";
2import { signInWithRedirect, getCurrentUser } from "aws-amplify/auth";
3
4Hub.listen("auth", ({ payload }) => {
5 switch (payload.event) {
6 case "signInWithRedirect":
7 const user = await getCurrentUser();
8 console.log(user.username);
9 break;
10 case "signInWithRedirect_failure":
11 // handle sign in failure
12 break;
13 case "customOAuthState":
14 const state = payload.data; // this will be customState provided on signInWithRedirect function
15 console.log(state);
16 break;
17 }
18});
19
20function handleSignInClick(customState) {
21 signInWithRedirect({
22 provider: "Google",
23 customState
24 });
25}

Redirect URLs

For Sign in Redirect URI(s) inputs, you can put one URI for local development and one for production. Example: http://localhost:3000/ in dev and https://www.example.com/ in production. The same is true for Sign out redirect URI(s).

If you have multiple redirect URI inputs, you'll need to pass them in your Amplify configuration. For example:

1Amplify.configure({
2 Auth: {
3 Cognito: {
4 loginWith: {
5 oauth: {
6 redirectSignIn: [
7 'http://localhost:3000/',
8 'https://www.example.com/'
9 ],
10 redirectSignOut: [
11 'http://localhost:3000/',
12 'https://www.example.com/'
13 ],
14 ...oauthConfig
15 }
16 },
17 ...userPoolConfig
18 }
19 }
20});
Example
Full Example using multiple redirect URIs
1import React, { useEffect, useState } from "react";
2import { Amplify } from "aws-amplify";
3import { Hub } from "aws-amplify/utils";
4import { signInWithRedirect, signOut, getCurrentUser } from "aws-amplify/auth";
5import { AuthUser } from "aws-amplify/auth";
6
7Amplify.configure({
8 Auth: {
9 Cognito: {
10 loginWith: {
11 oauth: {
12 redirectSignIn: [
13 "http://localhost:3000/",
14 "https://www.example.com/",
15 ],
16 redirectSignOut: [
17 "http://localhost:3000/",
18 "https://www.example.com/",
19 ],
20 ...oauthConfig
21 },
22 },
23 ...userPoolConfig
24 },
25 },
26});
27
28function App() {
29 const [user, setUser] = useState<AuthUser | null>(null);
30 const [error, setError] = useState<unknown>(null);
31 const [customState, setCustomState] = useState<string | null>(null);
32
33 useEffect(() => {
34 const unsubscribe = Hub.listen("auth", ({ payload }) => {
35 switch (payload.event) {
36 case "signInWithRedirect":
37 getUser();
38 break;
39 case "signInWithRedirect_failure":
40 setError("An error has occurred during the Oauth flow.");
41 break;
42 case "customOAuthState":
43 setCustomState(payload.data);
44 break;
45 }
46 });
47
48 getUser();
49
50 return unsubscribe;
51 }, []);
52
53 const getUser = async (): Promise<void> => {
54 try {
55 const currentUser = await getCurrentUser();
56 setUser(currentUser);
57 } catch (error) {
58 console.error(error);
59 console.log("Not signed in");
60 }
61 };
62
63 return (
64 <div className="App">
65 <button onClick={() => signInWithRedirect()}>Open Hosted UI</button>
66 <button onClick={() => signOut()}>Sign Out</button>
67 <div>{user?.username}</div>
68 </div>
69 );
70}
1import React, { useEffect, useState } from 'react';
2import { Amplify } from 'aws-amplify';
3import { Hub } from 'aws-amplify/utils';
4import { signInWithRedirect, signOut, getCurrentUser } from 'aws-amplify/auth';
5
6Amplify.configure({
7 Auth: {
8 Cognito: {
9 loginWith: {
10 oauth: {
11 redirectSignIn: [
12 'http://localhost:3000/',
13 'https://www.example.com/'
14 ],
15 redirectSignOut: [
16 'http://localhost:3000/',
17 'https://www.example.com/'
18 ],
19 ...oauthConfig
20 }
21 },
22 ...userPoolConfig
23 }
24 }
25});
26
27function App() {
28 const [user, setUser] = useState(null);
29 const [error, setError] = useState(null);
30 const [customState, setCustomState] = useState(null);
31
32 useEffect(() => {
33 const unsubscribe = Hub.listen('auth', ({ payload }) => {
34 switch (payload.event) {
35 case 'signInWithRedirect':
36 getUser();
37 break;
38 case 'signInWithRedirect_failure':
39 setError('An error has occurred during the Oauth flow.');
40 break;
41 case 'customOAuthState':
42 setCustomState(payload.data);
43 break;
44 }
45 });
46
47 getUser();
48
49 return unsubscribe;
50 }, []);
51
52 const getUser = async () => {
53 try {
54 const currentUser = await getCurrentUser();
55 setUser(currentUser);
56 } catch (error) {
57 console.error(error);
58 console.log('Not signed in');
59 }
60 };
61
62 return (
63 <div className="App">
64 <button onClick={() => signInWithRedirect()}>Open Hosted UI</button>
65 <button onClick={() => signInWithRedirect({ provider: 'Facebook' })}>
66 Open Facebook
67 </button>
68 <button onClick={() => signInWithRedirect({ provider: 'Google' })}>
69 Open Google
70 </button>
71 <button onClick={() => signInWithRedirect({ provider: 'Amazon' })}>
72 Open Amazon
73 </button>
74 <button onClick={() => signInWithRedirect({ provider: 'Apple' })}>
75 Open Apple
76 </button>
77 <button onClick={() => signOut()}>Sign Out</button>
78 <div>{user?.username}</div>
79 </div>
80 );
81}

(Required for Multi-Page Applications) Complete Social Sign In after Redirect

If you are developing a multi-page application, and the redirected page is not the same page that initiated the sign in, you will need to add the following code to the redirected page to ensure the sign in gets completed:

1import 'aws-amplify/auth/enable-oauth-listener';

NOTE: The listener only works on the client side in the context of a SSR-enabled project, so ensure to import the listener on the client side only. For example, in a Next.js project, you should add the above import statement to a component that renders on the client side only by 'use client'.

Under the hood
Why Social Sign In needs to be explicitly handled for Multi-Page Applications

When you import and use the signInWithRedirect function, it will add a listener as a side effect that will complete the social sign in when an end user is redirected back to your app. This works well in a single-page application but in a multi-page application, you might get redirected to a page that doesn't include the listener that was originally added as a side-effect. Hence you must include the specific OAuth listener on your login success page.

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.

1import { signInWithRedirect } from 'aws-amplify/auth';
2
3const provider = {
4 custom: 'MyCustomOIDCProvider'
5}
6
7function handleSignInClick() {
8 signInWithRedirect({ provider })
9}

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.

You can deploy your app to the Amplify Console with continuous deployment of the frontend and backend, please follow these instructions.

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: