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 moreReview 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. 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.
-
Create a developer account with Facebook.
-
Sign in with your Facebook credentials.
-
Choose My Apps from the top navigation bar, and on the page that loads choose Create App.
-
For your use case, choose Set up Facebook Login.
-
For platform, choose Website and select No, I'm not building a game.
-
Give your Facebook app a name and choose Create app.
-
On the left navigation bar, choose Settings and then Basic.
-
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.
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 URI12 `No`13? Enter your redirect signout URI:14 `http://localhost:3000/`15? Do you want to add another redirect signout URI16 `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>`
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:
-
Sign In to your Facebook developer account with your Facebook credentials.
-
Choose My Apps from the top navigation bar, and on the Apps page, choose your app you created before.
-
On the left navigation bar, choose Products. Add Facebook Login if it isn't already added.
-
If already added, choose Settings under the Configure dropdown.
-
Under Valid OAuth Redirect URIs type your user pool domain with the
/oauth2/idpresponse
endpoint.https://<your-user-pool-domain>/oauth2/idpresponse
- Save your changes.
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. You can also use the Hub eventing system to catch errors using Auth.federatedSignIn()
to listen for the signIn_failure
event.
1import React, { useEffect, useState } from 'react';2import { Amplify, Auth, Hub } from 'aws-amplify';3import { CognitoHostedUIIdentityProvider } from '@aws-amplify/auth';4import awsConfig from './aws-exports';5
6Amplify.configure(awsConfig);7
8function App() {9 const [user, setUser] = useState(null);10 const [customState, setCustomState] = useState<string | null>(null);11
12 useEffect(() => {13 const unsubscribe = Hub.listen("auth", ({ payload: { event, data }}) => {14 switch (event) {15 case "signIn":16 setUser(data);17 break;18 case "signOut":19 setUser(null);20 break;21 case "customOAuthState":22 setCustomState(data);23 }24 });25
26 getUser();27
28 return unsubscribe;29 }, []);30
31 const getUser = async (): Promise<void> => {32 try {33 const currentUser = await Auth.currentAuthenticatedUser();34 setUser(currentUser);35 } catch(error) {36 console.error(error);37 console.log("Not signed in");38 }39 };40
41 return (42 <div className="App">43 <button onClick={() => Auth.federatedSignIn()}>Open Hosted UI</button>44 <button onClick={() => Auth.federatedSignIn({provider: CognitoHostedUIIdentityProvider.Facebook })}>Open Facebook</button>45 <button onClick={() => Auth.federatedSignIn({provider: CognitoHostedUIIdentityProvider.Google })}>Open Google</button>46 <button onClick={() => Auth.federatedSignIn({provider: CognitoHostedUIIdentityProvider.Amazon })}>Open Amazon</button>47 <button onClick={() => Auth.federatedSignIn({provider: CognitoHostedUIIdentityProvider.Apple })}>Open Apple</button>48 <button onClick={() => Auth.signOut()}>Sign Out</button>49 <div>{user?.getUsername()}</div>50 </div>51 );52}53
54 //You can catch errors by listening to the signIn-failure event55 Hub.listen('auth', (data) => {56 if (data.payload.event === 'signIn_failure') {57 // Do something here58 }59})
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 handle both of them where you configure your Amplify project. For example:
1import awsConfig from './aws-exports';2
3const isLocalhost = Boolean(4 window.location.hostname === 'localhost' ||5 // [::1] is the IPv6 localhost address.6 window.location.hostname === '[::1]' ||7 // 127.0.0.1/8 is considered localhost for IPv4.8 window.location.hostname.match(9 /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/10 )11);12
13// Assuming you have two redirect URIs, and the first is for localhost and second is for production14const [localRedirectSignIn, productionRedirectSignIn] =15 awsConfig.oauth.redirectSignIn.split(',');16
17const [localRedirectSignOut, productionRedirectSignOut] =18 awsConfig.oauth.redirectSignOut.split(',');19
20const updatedAwsConfig = {21 ...awsConfig,22 oauth: {23 ...awsConfig.oauth,24 redirectSignIn: isLocalhost25 ? localRedirectSignIn26 : productionRedirectSignIn,27 redirectSignOut: isLocalhost28 ? localRedirectSignOut29 : productionRedirectSignOut30 }31};32
33Amplify.configure(updatedAwsConfig);
ExampleFull Example using multiple redirect URIs
1import { useEffect, useState } from 'react';2import { Amplify, Auth, Hub } from 'aws-amplify';3import awsConfig from './aws-exports';4
5const isLocalhost = Boolean(6 window.location.hostname === 'localhost' ||7 // [::1] is the IPv6 localhost address.8 window.location.hostname === '[::1]' ||9 // 127.0.0.1/8 is considered localhost for IPv4.10 window.location.hostname.match(11 /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/12 )13);14
15// Assuming you have two redirect URIs, and the first is for localhost and second is for production16const [17 localRedirectSignIn,18 productionRedirectSignIn,19] = awsConfig.oauth.redirectSignIn.split(',');20
21const [22 localRedirectSignOut,23 productionRedirectSignOut,24] = awsConfig.oauth.redirectSignOut.split(',');25
26const updatedAwsConfig = {27 ...awsConfig,28 oauth: {29 ...awsConfig.oauth,30 redirectSignIn: isLocalhost ? localRedirectSignIn : productionRedirectSignIn,31 redirectSignOut: isLocalhost ? localRedirectSignOut : productionRedirectSignOut,32 }33}34
35Amplify.configure(updatedAwsConfig);36
37function App() {38 const [user, setUser] = useState(null);39
40 useEffect(() => {41 Hub.listen('auth', ({ payload: { event, data }}) => {42 switch (event) {43 case 'signIn':44 case 'cognitoHostedUI':45 getUser();46 break;47 case 'signOut':48 setUser(null);49 break;50 case 'signIn_failure':51 case 'cognitoHostedUI_failure':52 console.log('Sign in failure', data);53 break;54 }55 });56
57 getUser();58 }, []);59
60 const getUser = async (): Promise<void> => {61 try {62 const userData = await Auth.currentAuthenticatedUser();63 setUser(userData)64 } catch(error) {65 console.error(error);66 console.log("Not signed in");67 }68 };69
70 return (71 <div>72 <p>User: {user ? JSON.stringify(user.attributes) : 'None'}</p>73 {user ? (74 <button onClick={() => Auth.signOut()}>Sign Out</button>75 ) : (76 <button onClick={() => Auth.federatedSignIn()}>Federated Sign In</button>77 )}78 </div>79 );80}81
82export 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.
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: