Page updated Nov 14, 2023

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 Auth.federatedSignIn() in your app to either show a pre-built "Hosted UI" or pass in a provider name (e.g. Auth.federatedSignIn({provider: 'Facebook'})) to interface directly and build your own UI. Image Alternatively, you can also get credentials directly from Identity Pools by passing tokens from a social provider directly with Auth.federatedSignIn(). However you will have to use that provider's SDK in your app as well as manage the tokens from the provider and their refresh cycles manually.

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.

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
1amplify 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>`
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 `myapp://`
11? Do you want to add another redirect signin URI
12 `No`
13? Enter your redirect signout URI:
14 `myapp://`
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.

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 Auth.federatedSignIn() function which will redirect the user to the Cognito Hosted UI and provide options to sign in via user name password as well as any of the Social providers you have configured. Also, note that passing LoginWithAmazon, Facebook, Google, or SignInWithApple on the provider argument (e.g Auth.federatedSignIn({ provider: 'LoginWithAmazon' })) will bypass the Hosted UI and federate immediately with the social provider as shown in the below example.

If you are looking to add a custom state, you are able to do so by passing a string value (e.g. Auth.federatedSignIn({ customState: 'xyz' })) and listening for the custom state via Hub.

import { useEffect, useState } from "react"; import { Text, View, Linking, Button } from "react-native"; import { CognitoHostedUIIdentityProvider } from "@aws-amplify/auth"; import { Amplify, Auth, Hub } from "aws-amplify"; import awsconfig from "./aws-exports"; Amplify.configure(awsconfig); export default function App() { const [user, setUser] = useState(null); const [customState, setCustomState] = useState<string | null>(null); useEffect(() => { const unsubscribe = Hub.listen("auth", ({ payload: { event, data }}) => { switch (event) { case "signIn": setUser(data); break; case "signOut": setUser(null); break; case "customOAuthState": setCustomState(data); } }); getUser(); return unsubscribe; }, []); const getUser = async (): Promise<void> => { try { const currentUser = await Auth.currentAuthenticatedUser(); setUser(currentUser); } catch(error) { console.error(error); console.log("Not signed in"); } }; return ( <View> <Button title="Open Amazon" onPress={() => Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Amazon, }) } /> <Button title="Open Hosted UI" onPress={() => Auth.federatedSignIn()} /> <Button title="Sign Out" onPress={() => Auth.signOut()} /> <Text>{user?.getUsername()}</Text> </View> ); }
1import { useEffect, useState } from "react";
2import { Text, View, Linking, Button } from "react-native";
3import { CognitoHostedUIIdentityProvider } from "@aws-amplify/auth";
4import { Amplify, Auth, Hub } from "aws-amplify";
5import awsconfig from "./aws-exports";
6
7Amplify.configure(awsconfig);
8
9export default function App() {
10 const [user, setUser] = useState(null);
11 const [customState, setCustomState] = useState<string | null>(null);
12
13 useEffect(() => {
14 const unsubscribe = Hub.listen("auth", ({ payload: { event, data }}) => {
15 switch (event) {
16 case "signIn":
17 setUser(data);
18 break;
19 case "signOut":
20 setUser(null);
21 break;
22 case "customOAuthState":
23 setCustomState(data);
24 }
25 });
26
27 getUser();
28
29 return unsubscribe;
30 }, []);
31
32 const getUser = async (): Promise<void> => {
33 try {
34 const currentUser = await Auth.currentAuthenticatedUser();
35 setUser(currentUser);
36 } catch(error) {
37 console.error(error);
38 console.log("Not signed in");
39 }
40 };
41
42 return (
43 <View>
44 <Button
45 title="Open Amazon"
46 onPress={() =>
47 Auth.federatedSignIn({
48 provider: CognitoHostedUIIdentityProvider.Amazon,
49 })
50 }
51 />
52 <Button title="Open Hosted UI" onPress={() => Auth.federatedSignIn()} />
53 <Button title="Sign Out" onPress={() => Auth.signOut()} />
54 <Text>{user?.getUsername()}</Text>
55 </View>
56 );
57}

Redirect URLs

For Sign in Redirect URI(s) inputs, you can put one URI for local development and one for production. For example, in Expo: exp://127.0.0.1:19000/--/ in dev and myapp:// in production. The same is true for Sign out redirect URI(s).

If you have multiple redirect URI inputs, you'll need to handle both of them where you configure your Amplify project. For example:

import awsConfig from './aws-exports'; const isLocalhost = Boolean(__DEV__); // Assuming you have two redirect URIs, and the first is for localhost and second is for production const [localRedirectSignIn, productionRedirectSignIn] = awsConfig.oauth.redirectSignIn.split(','); const [localRedirectSignOut, productionRedirectSignOut] = awsConfig.oauth.redirectSignOut.split(','); const updatedAwsConfig = { ...awsConfig, oauth: { ...awsConfig.oauth, redirectSignIn: isLocalhost ? localRedirectSignIn : productionRedirectSignIn, redirectSignOut: isLocalhost ? localRedirectSignOut : productionRedirectSignOut } }; Amplify.configure(updatedAwsConfig);
1import awsConfig from './aws-exports';
2
3const isLocalhost = Boolean(__DEV__);
4
5// Assuming you have two redirect URIs, and the first is for localhost and second is for production
6const [localRedirectSignIn, productionRedirectSignIn] =
7 awsConfig.oauth.redirectSignIn.split(',');
8
9const [localRedirectSignOut, productionRedirectSignOut] =
10 awsConfig.oauth.redirectSignOut.split(',');
11
12const updatedAwsConfig = {
13 ...awsConfig,
14 oauth: {
15 ...awsConfig.oauth,
16 redirectSignIn: isLocalhost
17 ? localRedirectSignIn
18 : productionRedirectSignIn,
19 redirectSignOut: isLocalhost
20 ? localRedirectSignOut
21 : productionRedirectSignOut
22 }
23};
24
25Amplify.configure(updatedAwsConfig);

For React Native applications, you need to define a custom URL scheme for your application before testing locally or publishing to the app store. This is different for Expo or vanilla React Native. For Expo, follow the steps in Expo Linking Guide. For vanilla React Native, follow the steps in React Native Linking Guide. After completing those steps, assuming you are using myapp as the name of your URL Scheme (or whatever friendly name you have chosen), you will use these URLs as Sign in Redirect URI(s) and/or Sign out redirect URI(s) inputs. Your URIs could look like any of these:

  • myapp://
  • exp://127.0.0.1:19000/--/ (Local development if your app is running in the Expo client).
<plist version="1.0"> <dict> <!-- YOUR OTHER PLIST ENTRIES HERE --> <!-- ADD AN ENTRY TO CFBundleURLTypes for Cognito Auth --> <!-- IF YOU DO NOT HAVE CFBundleURLTypes, YOU CAN COPY THE WHOLE BLOCK BELOW --> <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>myapp</string> </array> </dict> </array> <!-- ... --> </dict>
1<plist version="1.0">
2
3 <dict>
4 <!-- YOUR OTHER PLIST ENTRIES HERE -->
5
6 <!-- ADD AN ENTRY TO CFBundleURLTypes for Cognito Auth -->
7 <!-- IF YOU DO NOT HAVE CFBundleURLTypes, YOU CAN COPY THE WHOLE BLOCK BELOW -->
8 <key>CFBundleURLTypes</key>
9 <array>
10 <dict>
11 <key>CFBundleURLSchemes</key>
12 <array>
13 <string>myapp</string>
14 </array>
15 </dict>
16 </array>
17
18 <!-- ... -->
19 </dict>

Use the in-app browser plugin for React Native

By default, Amplify will open the Cognito Hosted UI in Safari/Chrome, but you can override that behavior by providing a custom urlOpener. While this is optional, it is recommended.

Note for iOS Apps: In order for Amplify to listen for data from Cognito when linking back to your app, you will need to setup the Linking module in AppDelegate.m (see React Native docs for more information):

#import <React/RCTLinkingManager.h> - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options { return [RCTLinkingManager application:application openURL:url options:options]; }
1#import <React/RCTLinkingManager.h>
2
3- (BOOL)application:(UIApplication *)application
4 openURL:(NSURL *)url
5 options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
6{
7 return [RCTLinkingManager application:application openURL:url options:options];
8}

The sample below uses react-native-inappbrowser-reborn, but you can use any other in-app browser available.

import { useEffect, useState } from 'react'; import { Button, Linking, Text, View } from 'react-native'; import InAppBrowser from 'react-native-inappbrowser-reborn'; import { Amplify, Auth, Hub } from 'aws-amplify'; import { CognitoHostedUIIdentityProvider } from '@aws-amplify/auth'; import awsconfig from './aws-exports'; async function urlOpener(url: string, redirectUrl: string): Promise<void> { await InAppBrowser.isAvailable(); const authSessionResult = await InAppBrowser.openAuth(url, redirectUrl, { showTitle: false, enableUrlBarHiding: true, enableDefaultShare: false, ephemeralWebSession: false, }); if (authSessionResult.type === 'success') { Linking.openURL(authSessionResult.url); } } Amplify.configure({ ...awsconfig, oauth: { ...awsconfig.oauth, urlOpener, }, }); function App() { const [user, setUser] = useState(null); useEffect(() => { Hub.listen('auth', ({ payload: { event, data } }) => { switch (event) { case 'signIn': case 'cognitoHostedUI': getUser(); break; case 'signOut': setUser(null); break; case 'signIn_failure': case 'cognitoHostedUI_failure': console.log('Sign in failure', data); break; } }); getUser() }, []); const getUser = async (): Promise<void> => { try { const userData = await Auth.currentAuthenticatedUser(); setUser(userData) } catch(error) { console.error(error); console.log("Not signed in"); } }; return ( <View> <Text>User: {user ? JSON.stringify(user.attributes) : 'None'}</Text> {user ? ( <Button title="Sign Out" onPress={() => Auth.signOut()} /> ) : ( <> {/* Go to the Cognito Hosted UI */} <Button title="Cognito" onPress={() => Auth.federatedSignIn()} /> {/* Go directly to a configured identity provider */} <Button title="Facebook" onPress={() => Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Facebook })} /> <Button title="Google" onPress={() => Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Google })} /> <Button title="Amazon" onPress={() => Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Amazon })} /> </> )} </View> ); } export default App;
1import { useEffect, useState } from 'react';
2import { Button, Linking, Text, View } from 'react-native';
3import InAppBrowser from 'react-native-inappbrowser-reborn';
4
5import { Amplify, Auth, Hub } from 'aws-amplify';
6import { CognitoHostedUIIdentityProvider } from '@aws-amplify/auth';
7import awsconfig from './aws-exports';
8
9async function urlOpener(url: string, redirectUrl: string): Promise<void> {
10 await InAppBrowser.isAvailable();
11 const authSessionResult = await InAppBrowser.openAuth(url, redirectUrl, {
12 showTitle: false,
13 enableUrlBarHiding: true,
14 enableDefaultShare: false,
15 ephemeralWebSession: false,
16 });
17
18 if (authSessionResult.type === 'success') {
19 Linking.openURL(authSessionResult.url);
20 }
21}
22
23Amplify.configure({
24 ...awsconfig,
25 oauth: {
26 ...awsconfig.oauth,
27 urlOpener,
28 },
29});
30
31function App() {
32 const [user, setUser] = useState(null);
33
34 useEffect(() => {
35 Hub.listen('auth', ({ payload: { event, data } }) => {
36 switch (event) {
37 case 'signIn':
38 case 'cognitoHostedUI':
39 getUser();
40 break;
41 case 'signOut':
42 setUser(null);
43 break;
44 case 'signIn_failure':
45 case 'cognitoHostedUI_failure':
46 console.log('Sign in failure', data);
47 break;
48 }
49 });
50
51 getUser()
52 }, []);
53
54 const getUser = async (): Promise<void> => {
55 try {
56 const userData = await Auth.currentAuthenticatedUser();
57 setUser(userData)
58 } catch(error) {
59 console.error(error);
60 console.log("Not signed in");
61 }
62 };
63
64 return (
65 <View>
66 <Text>User: {user ? JSON.stringify(user.attributes) : 'None'}</Text>
67 {user ? (
68 <Button title="Sign Out" onPress={() => Auth.signOut()} />
69 ) : (
70 <>
71 {/* Go to the Cognito Hosted UI */}
72 <Button title="Cognito" onPress={() => Auth.federatedSignIn()} />
73
74 {/* Go directly to a configured identity provider */}
75 <Button title="Facebook" onPress={() => Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Facebook })} />
76 <Button title="Google" onPress={() => Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Google })} />
77 <Button title="Amazon" onPress={() => Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Amazon })} />
78 </>
79 )}
80 </View>
81 );
82}
83
84export default App;

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: