DEV Community

Cover image for How to Create a Login for your WebApp with AWS Cognito Using OAuth 2.0
Franco Cerutti
Franco Cerutti

Posted on

How to Create a Login for your WebApp with AWS Cognito Using OAuth 2.0

What is AWS Cognito

Amazon Cognito is an identity platform for web and mobile apps. It’s a user directory, an authentication server, and an authorization service for OAuth 2.0 access tokens and AWS credentials.

You can authenticate and authorize users from the built-in user directory, from your enterprise directory, and from consumer identity providers like Google and Facebook.

Context

The application is going to be a webApplication where needs a login/SignUP feature, and the scope of this is to integrate the cognito user pools with Google federated Identities from Infrastructure as Code using Pulumi

Step to integrate AWS Cognito

AWS Cognito User Pool Diagram

Define the User Pool

Create a user pool when you want to authenticate and authorize users to your app or API. User pools are a user directory with both self-service and administrator-driven user creation, management, and authentication



 const userPool = new aws.cognito.UserPool(
    `${appShortName}-user-pool-${NODE_ENV}`,
    {
      autoVerifiedAttributes: ['email'],
      emailConfiguration: {
        replyToEmailAddress: process.env.REPLY_EMAIL_ADDRESS,
        emailSendingAccount: 'COGNITO_DEFAULT',
      },
      mfaConfiguration: 'OPTIONAL',
      softwareTokenMfaConfiguration: {
        enabled: true,
      },
      accountRecoverySetting: {
        recoveryMechanisms: [
          {
            name: 'verified_email',
            priority: 1,
          },
          {
            name: 'verified_phone_number',
            priority: 2,
          },
        ],
      },
      adminCreateUserConfig: {
        allowAdminCreateUserOnly: true,
      },
    }
  );


Enter fullscreen mode Exit fullscreen mode

Create Federated Identities Provider

In this case we're going to create a Goggle Identity, and we defined the provider configuration

Before continuing with the Infrastructure in Pulumi we need to go to GCP Console and make the next config.

GCP Config

Once you're in the Console, go to API & Services, Credentials, create a Oauth Client, declare mocked URL and continue. This you will need to modify once you have your Cognito DNS.



  const googleCredentials = {
    clientId: process.env.GOOGLE_CREDENTIALS_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CREDENTIALS_CLIENT_SECRET,
  };

  const googleProvider = new aws.cognito.IdentityProvider(
    `${appShortName}-identity-google-provider-${NODE_ENV}`,
    {
      providerName: 'Google',
      userPoolId: userPool.id,
      providerType: 'Google',
      providerDetails: {
        client_id: googleCredentials.clientId,
        client_secret: googleCredentials.clientSecret,
        authorize_scopes: 'email profile openid',
      },
      attributeMapping: {
        email: 'email',
        username: 'sub',
      },
    }
  );


Enter fullscreen mode Exit fullscreen mode

Create the Client App for the User Pool



  const userPoolClient = new aws.cognito.UserPoolClient(
    `${appShortName}-user-pool-client-${NODE_ENV}`,
    {
      userPoolId: userPool.id,
      callbackUrls: [process.env.CALLBACK_WEB_APP_URL],
      logoutUrls: [process.env.LOGOUT_WEB_APP_URL],
      explicitAuthFlows: [
        'ALLOW_USER_SRP_AUTH',
        'ALLOW_REFRESH_TOKEN_AUTH',
        'ALLOW_CUSTOM_AUTH',
      ],
      allowedOauthFlowsUserPoolClient: true,
      allowedOauthScopes: ['profile', 'openid', 'email'],
      allowedOauthFlows: ['code'],
      supportedIdentityProviders: ['COGNITO', googleProvider.providerName],
    }
  );


Enter fullscreen mode Exit fullscreen mode

Here you have declared the OauthFlows, Scopes and Providers that your Cognito IDP will support.

Deploy

Deploy the infrastructure to AWS



pulumi up


Enter fullscreen mode Exit fullscreen mode

AWS Config

Go to the AWS Cognito, in the AWS Console, fetch the one created recently.

Navigate to the App integration tab for your user pool.

Next to Domain, choose Actions and select Create custom domain or Create Amazon Cognito domain. If you have already configured a user pool domain, choose Delete Amazon Cognito domain or Delete custom domain before creating your new custom domain.

Enter an available domain prefix to use with a Amazon Cognito domain

Choose Create.

Verify DNS

Verify that the sign-in page is available from your Amazon Cognito hosted domain.



https://<your_domain>/login?response_type=code&client_id=<your_app_client_id>&redirect_uri=<your_callback_url>


Enter fullscreen mode Exit fullscreen mode

Your domain is shown on the Domain name page of the Amazon Cognito console. Your app client ID and callback URL are shown on the App client settings page.

Summary

With that being done, you will have a functional Authorization & Authentication with Google Federated Identities using OAuth 2.0 from Infrastructure as Code.

This is a guide from and for the community

Hope you like it!

Top comments (2)

Collapse
 
hectorfernandezdev profile image
Hector Fernandez CloudparaTodo

Great summary! it is 100% better to use any SDK or IaaC instead of cliks.

Collapse
 
cheru94 profile image
Franco Cerutti

Totaly agree, and you can build this in less than an hour, the Hosted UI is very open to make customization from the CSS but nothing too crazy

Remainings are:
Lambda Actions to make sync with DB, API Gateway Authorizer or Auth Middleware and WebApp Routing/Token Config