AWS provides two possible ways of dealing with Cognito:
- "old one" via
amazon-cognito-identity-js
(and possiblyamazon-cognito-auth-js
) and - "new one" via
aws-amplify
(which inlcudes the above one)
After quite a bit of trouble and reverse engineering, I've successfully managed to sign in (receve back CognitoIdentityCredentials) using aws-amplify
locally as part of the development effort.
The steps where (bear with me, as these are important for the questions to follow, and also might help someone):
Setup
Create a User Pool in Cognito console
Create a User Pool App Client in Cognito console
Create Google Web App in Google Console
Configure Google Web App to point to http://localhost:8080 (my local dev server)
Configure User Pool to use Google as an Identity Provider, supplying it with the Google Web App Client ID and Client secret from Google Console
Create an Identity Pool in Congnito console and configure it to work with Google as an Identity Provider, supplying Google Web App Client ID there as well
Implementation
- Configure Amplify.Auth:
Amplify.configure({ Auth: { identityPoolId: , region: , userPoolId: , userPoolWebClientId: } });
- Inject Google API script:
const script = document.createElement('script'); script.src = 'https://apis.google.com/js/platform.js'; script.async = true; script.onload = this.initGapi; document.body.appendChild(script);
- Init Google API:
window.gapi.load('auth2', function() { window.gapi.auth2.init({ client_id: , scope: 'profile email openid' }); });
- Allow, on a button click, for a Google user to sing in:
const ga = window.gapi.auth2.getAuthInstance(); const googleUser = await ga.signIn(); const {id_token, expires_at} = googleUser.getAuthResponse(); const profile = googleUser.getBasicProfile();
- User the
profile
,id_token
,expires_at
above to create a Cognito credentials session:
const user = { email: profile.getEmail(), name: profile.getName() }; const credentials = await Auth.federatedSignIn( 'google', {token: id_token, expires_at}, user );
At this point a CognitoIdentityCredentials
object was returned, properly populated, with token and all...
Problem
Unfortunately, aws-amplify
adds a whopping 190K to my application webpack bundle (GZIPped, minified, optimized), which made me choke on my coffee.
Question 1
Can this somehow be reduced by a Babel plugin I'm missing (I'm guessing, no, since AWS is apparently still in 1995 and configures everything on a singleton Amplify
and Auth
objects).
Question 2
Have I made this unnecessarily complicated and there is a much more robust solution?
Question 3 (most important)
Can this be achieved using the "old way" amazon-cognito-identity-js
, which is MUCH MUCH smaller?
I couldn't find, among all the (use cases)[https://github.com/aws/aws-amplify/tree/master/packages/amazon-cognito-identity-js/] a use case for social/federated login.