Integrating Social Media to your App with AWS Cognito

Mauro Mamani
Sep 9 · 9 min read

In this post we will talk about Amazon Cognito. After reading this post you will have an idea of how to integrate it to your App and what you will gain after doing so.

What is AWS Cognito?

Cognito is a service provided by Amazon Web Services. It handles all of your App’s user authentication process, providing endpoints for SignUp, SignIn and the rest of the features that most of nowadays applications have.

It also provides easy integration with social media auth APIs, like Google, Facebook, Amazon, SAML and OpenID Connect. That is its most valuable feature in my opinion.

Why AWS Cognito?

There are different ways of integrating Social Media Auth to your App. After doing some research, I came to the conclusion that AWS Cognito provides most of the configuration needed and also most of the logic / code. It will ease the integration and you will save tons of time!

How does Cognito work with my app?

We will go through different flows and the way we implemented them in Wolox.

  • SignUp (register user):

The SignUp flow is very simple. In this example we will have the username, email, password and Onboarding information for a new user.

How do we save the user data?

  1. We will send the username, email and password to Cognito, it will process and save the new user.
  2. Once we know Cognito succeeded, we will send all the information we want to save for that user to our App’s backend. In this case, we will use the email as a unique ID for our user list. We will also save the username we want to show our user in our App and some Onboarding information.

Now, we have our user registered in our auth API (Cognito) and we also saved some information for that user in our App’s database.

  • SignIn:

The SignIn flow will be similar to the SignUp.

To use Cognito SignIn endpoint, we decided to use the username or email. Just follow these steps:

  1. We will send any of our ID keys, let’s say we will use email, and our password to Cognito: if the user exists, the API will return a jwtToken with our user information. If the user does not exist, Cognito will send us an error message and we will have to handle it and show the user an error.
  2. Now that we have the jwtToken for this user, we will have to add it as an Authorization parameter in our API’s header.
  3. Then, we will send the SingIn request to our backend and it will return the userData we saved in SignUp.
  4. We used a JWT library in our backend to decode the Authorization header, it will return all the information Cognito gives us, including the ID key we were using the email. So our backend now will just have to return the userData saved for that email.

We are now signed in!

* If you want to check out more information about the JWT token, you can check it here.

  • Social SignIn

As we said before, Cognito allows us to connect our App with social media authentication APIs.

We will now see how to integrate our App with Cognito and Social Media in our project, we will use Google as an example.

  1. First of all, we will have to add a button to open Google API to Sign in. Cognito provides us most of the logic needed for this, we will just have to hit the following URL when the user clicks the Google button (we created a custom made button with a Google image): https://{YOUR_APP_URL}.auth.us-east-1.amazoncognito.com/oauth2/authorize?identity_provider=Google&redirect_uri={REDIRECT_URI}&response_type=CODE&client_id={YOUR_CLIENT_ID}&scope=email phone profile aws.cognito.signin.user.admin openid
  2. Now you will be redirected to “Social media interaction”, that is Google’s authentication process.
  3. Once you have completed Google’s authentication steps, it will redirect to our App and we will receive the information we will have to send Cognito. Which we represented as “body” in the post interaction in our diagram.
  4. Cognito will perform our user SignUp if it is a new user or a SignIn if it exists and will return a jwtToken.
  5. The flow now is exactly the same as the SigningIn flow. We will add the jwtToken as Authorization header and we have two options here:
  • If the user is new, we will have to send the information we want to save. In our case, we want to save the onboarding information.
  • If the user is an existing one, we will just have to ask our backend to return the userData.

We added some listeners to receive the browser’s callback:

componentDidMount() {
Linking.addEventListener(‘url’, this.handleOpenURL);
}
componentWillUnmount() {
Linking.removeEventListener(‘url’, this.handleOpenURL);
}
onGoogleSubmit = () => {
Linking.openURL(getGoogleURL()).catch(err => err);
};

It should work like this:

How can I add Cognito to my application?

Adding Cognito to your project is easy. We will go step by step.

1) Configuring Cognito:

  1. Sign in to the Amazon Cognito console
  2. Choose Manage your User Pools.
  3. Choose Create a User Pool.
  4. In Pool name, type a name for the pool and then choose Review defaults. This creates the pool with the default settings (I recommend this option).
  5. From the left navigation pane, choose Attributes to specify which attributes are required and which attributes to use as aliases. After you set the following attributes and after users in the pool verify their email addresses, they can sign in with their usernames or email addresses.
  6. For email, choose Required and Alias.
  7. For phone number, choose Required and Alias.
  8. For given name, choose Required.
  9. Choose Save changes.
    With the following configuration, you will allow users to login with email or username:
  1. From the left navigation pane, choose Policies to specify the password policy. I recommend using the default configuration for this tutorial.
  2. From the left navigation pane, choose Message customizations. On this page, you can customize the messages that are sent to the users in your pool to deliver verification codes. I recommend using the default configuration for this tutorial.
  3. From the left navigation pane, choose App clients and then choose Add an app client. You can create multiple app clients for a user pool.
  4. For App name, type a name for your app. Ensure that the Generate client secret checkbox is cleared, and then choose Set attribute read and write permissions. Select the attributes that require write permissions. Required attributes always have to write permissions.
    Note: The Amazon Cognito JavaScript SDK does not use the app client secret. If you configure your user pool app client with an app client secret, the SDK will throw exceptions.
  5. Choose Create app and then Save changes.
  6. From the left navigation bar, choose Review and then choose Create pool.
  7. Note the pool ID and client ID. You can find the app client ID under App clients on the left navigation bar. You will need to have this information in your App!

You can find the complete step guide here.

2) Implementing Cognito

We will implement AWS Cognito using this library.

  1. First of all, you have to install the library: npm install — save amazon-cognito-identity-js
  2. Then, link the library: react-native link amazon-cognito-identity-js
  3. Add your ClientID and your UserPoolID to your project.
  4. Now you are ready! Import the features you want to use from the library!

TIP:

Most useful imports:

  • CognitoUserPool: this is the one you will use to locally create a user pool `new CognitoUserPool({ClientID,UserPoolID})`,
  • CognitoUser: here you can get your user information `new CognitoUser({ Username: username, Pool: cognitoUserPool });`
  • CognitoAccessToken: user access token,
  • CognitoIdToken: user id token,
  • CognitoRefreshToken: user refresh token,
  • CognitoUserSession: get the current user session

How do I add Social Media integration?

If you want to add social media integrations, you will have to do some additional steps.

1) Social Media configuration (Google example):

  1. Create a developer account with Google.
  2. Sign in with your Google credentials.
  3. Choose CONFIGURE A PROJECT.
  4. Type in a project name and choose NEXT.
  5. Type in your product name and choose NEXT.
  6. Choose Web browser from the Where are you calling from?
  7. Type your user pool domain into Authorized JavaScript origins. You can leave this empty if it is a mobile App. https://<your-user-pool-domain>
  8. Choose CREATE. You will not use the Client ID and Client Secret from this step.
  9. Choose DONE.
  10. Sign in to the Google Console.
  11. On the left navigation bar, choose Credentials.
  12. Create your OAuth 2.0 credentials by choosing OAuth client ID from the Create credentials drop-down list.
  13. Choose Web application.
  14. Type your user pool domain into Authorized JavaScript origins https://<your-user-pool-domain>
  15. Type your user pool domain with the /oauth2/idpresponse endpoint into Authorized Redirect URIs. https://<your-user-pool-domain>/oauth2/idpresponse
  16. Choose Create twice.
  17. Note the OAuth client ID and client secret. You will need them for the next section.
  18. Choose OK.
  19. In the OAuth consent screen, you have to add amazoncognito.com as an authorized domain.

2) Social Media Cognito configuration (Google example):

  1. Go to the Amazon Cognito console. You might be prompted for your AWS credentials.
  2. Choose Manage your User Pools.
  3. Choose an existing user pool from the list, or create a user pool.
  4. On the left navigation bar, choose Identity providers.
  5. Choose a social identity provider: Google in this case.
  6. Type the app client ID and app client secret that you received from the social identity provider in the previous section.
  7. Type the names of the scopes that you want to authorize. Scopes define which user attributes (such as name and email) you want to access with your app. For Google they should be separated by spaces. We used the default profile email openid.
  8. Your app user is asked to consent to provide these attributes to your app.
  9. Choose Enable for the social identity provider that you’re configuring.
  10. Choose App client settings from the navigation bar.
  11. Select your social identity provider as one of the Enabled Identity Providers for your user pool app.
  12. Type your callback URL into Callback URL(s) for your user pool app. This is the URL of the page where your user will be redirected after a successful sign-in. I recommend you to add http://localhost:3000. We will use it later!
  13. Choose Save changes.
  14. On the Attribute mapping tab, add mappings for at least the required attributes, typically email, as follows:
  15. Select the checkbox to choose the Google attribute name. You can also type the names of additional attributes that aren’t listed in the Amazon Cognito console.
  16. Choose the destination user pool attribute from the drop-down list.
  17. Choose Save changes.
  18. Choose Go to summary.

It should look like the following (I also added Facebook here):

You can find detailed steps in this link, also how to do it with Facebook.

Can I create users before finishing the integration?

Yes! In case the frontend is not finished and a backend developer or a tester wants to create a new user, they can do it! You only need to have Cognito configured.

Here we will use the http://localhost:3000 as callback URL we set in step 2.12. You will get a code when being redirected to this URL.

As you have already created a user pool in AWS Console, you will be able to access a URL like the following one

https://{YOUR_APP_URL}.auth.us-east-1.amazoncognito.com/login?response_type=code&client_id={YOUR_CLIENT_ID}&redirect_uri=http://localhost:3000&scope=email+phone+profile+aws.cognito.signin.user.admin+openid

You will see a screen like this:

e

After signing in, you will be redirected to the callback URL you provided. In this case, localhost:3000 (This URL doesn’t need to be a specific one, you just need to be redirected somewhere). In this new URL, you will have something like http://localhost:3000?code=[CODE].

After this, you will only need to POST this Code to Cognito’s /ouath2/token endpoint. The request should look as follows:

POST {YOUR_APP_URL}.auth.us-east-1.amazoncognito.com/oauth2/token
grant_type=authorization_code&amp
client_id={YOUR_CLIENT_ID}
code={Code obtained in previous step}
redirect_uri=http://localhost:3000


Now that you have read this guide, you know how to integrate Cognito and Social Media to your App. You can even add it to a website with this same steps!

I’d like to thank Ignacio Santise in Wolox for the AWS Cognito implementation and code source and Guido Princ for his review.

Please feel free to try it yourself and leave any comments or suggestions below.

Wolox

Wolox stands for innovation, engineering and working culture that transforms problems into solutions and ideas into products. www.wolox.com.ar

Mauro Mamani

Written by

Wolox

Wolox

Wolox stands for innovation, engineering and working culture that transforms problems into solutions and ideas into products. www.wolox.com.ar

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade