Adding AWS Cognito Federated Login With Google Using AWS Amplify | Task

Ole Ersoy
Feb - 04  -  4 min

Scenario

We want a Google Social Login button in our Angular app.

Approach

First Configure the Amplify CLI.

Generate an Angular Project and Install Dependencies

Will also be using Angular Material for our button:

ng new amplify-google-login-test
ng add @angular/material
npm install aws-amplify

Implement the Auth Service

import { Injectable } from '@angular/core'
import Auth, { CognitoHostedUIIdentityProvider } from '@aws-amplify/auth'
import { Hub, ICredentials } from '@aws-amplify/core'
import { Subject, Observable } from 'rxjs'
import { CognitoUser } from 'amazon-cognito-identity-js'

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  
  public loggedIn: boolean;

  private _authState: Subject<CognitoUser|any> = new Subject<CognitoUser|any>();
  authState: Observable<CognitoUser|any> = this._authState.asObservable();

  public static SIGN_IN = 'signIn';
  public static SIGN_OUT = 'signOut'; 

  constructor() { 
    Hub.listen('auth',(data) => {
      const { channel, payload } = data;
      if (channel === 'auth') {
        this._authState.next(payload.event);
      }
    });
  }
  
  signOut(): Promise<any> {
    return Auth.signOut()
      .then(() => this.loggedIn = false)
  }

  googleSocialSignIn():Promise<ICredentials> {
    return Auth.federatedSignIn({
      'provider': CognitoHostedUIIdentityProvider.Google
    });
  }
}

Now when the AuthService loads we check whether the user is signed in via Hub and if so we emit a CognitoUser via _authState.

Import the Material Button Module

In app.module.ts:

import { MatButtonModule } from '@angular/material/button';
imports: [
...
    MatButtonModule
]

Implement Signin

Inject the AuthService service and implement the signInWithGoogle function in app.component.ts:

import { Component } from '@angular/core';
import { AuthService } from '../auth.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'amplify-google-login-test';
  constructor(private auth: AuthService) {
  }

  async signInWithGoogle() {
    const socialResult = 
    await this.auth.googleSocialSignIn();
    console.log('google Result:', socialResult);
  }
}

Create the Login Button

Create a Login with Google button in app.component.html:

<button  mat-flat-button color="accent"   
         (click)="signInWithGoogle()">
    Login with Google
</button>

Add Amplify

amplify init

Hit Enter for all the suggestions. Then Complete the Google Social Provider Setup.

Add Auth

amplify add auth

Select Default configuration with Social Provider (Federation).

Select Email for How do you want users to sign in.

Select No I'm done.

Hit enter for the question What domain name prefix you want us to create for you?

For the redirect signin and signout URI use http://localhost:4200/

When asked to Select the social providers you want to configure for your user pool choose Google.

Enter the Google clientid and Client Secret setup in the Google Developer Console.

Run amplify push.

AWS Cognito is now ready. You may want to log into the AWS Developer Console, go to Cognito, select your pool, and perform user attribute mapping in order to capture all Google user attributes of users logging in to your application.

Follow this link for instructions on how to completely the scaffoldling for Angular.

Final Step

Complete the Google Signin Instructions.

Once this step is done go back to the developer console.

Select the client created when obtaining the Google client id and client secret.

Open src/aws-exports.js and look for domain :

"oauth": {
   "domain": "googlelogin-a1963b82-dev.auth.us-east-1.amazoncognito.com"
}

Put that in authorized javascript origins . The value should be:

https://googlelogin-a1963b82-dev.auth.us-east-1.amazoncognito.com

For authorized redirect URIs append /oauth2/idpresponse to the user pool domain resulting in:

https://googlelogin-a1963b82-dev.auth.us-east-1.amazoncognito.com/oauth2/idpresponse

The setup is now complete and you should be able to login with the button.