Adding AWS Cognito Federated Login With Google Using AWS Amplify
Updated Version
There’s an updated version of this article here:
Scenario
We want a Google Social Login button in our Angular app.
Prerequisites
Configure the Amplify CLI
Generate an Angular Project and Install Dependencies
ng new amplify-google-login-test
ng add @angular/material
npm install aws-amplify
Implement the Auth Service
Create src/app/services/auth-service.ts
:
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
]
Inject the AuthService
service and implement the signInWithGoogle
function in app.component.ts
:
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.
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.
Complete Angular Scaffolding
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.