DEV Community

Ram nitharshan
Ram nitharshan

Posted on

Integrating Google and Facebook Auth into your Angular 2+ application

One of the most difficult conundrums that I’ve had to face recently was to include Google and Facebook authentication in an Angular application of mine.

Something that sounds so easy should be easy to implement as well, right? Well, there are a few frameworks out there that promise to simplify it for you. However, if you wanted to do it the regular way by getting the necessary libraries from Google and Facebook, that’s where things start getting tricky. Neither have an official version of their SDK’s for Typescript. So I thought I’ll make it easy for the next guy or girl out there trying to figure it out.

Before you get started, you will have to create yourself a Facebook developer account and get yourself an App ID.

To begin with integrating facebook login into your Angular app, run the following npm command,

npm install — save @types/facebook-js-sdk

In your index.html, insert the following code.

<script type="text/javascript" src="https://connect.facebook.net/en_US/sdk.js"></script>

In your src directory, create a TS file with the following code. Don’t forget to import this file in your main.ts file.

(<any>window).fbAsyncInit = () => {
FB.init({
appId : 'Your App ID',
xfbml : false,
version : 'v2.9'
});
FB.AppEvents.logPageView();
};

(function(d, s, id){
let js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
js.src = '//connect.facebook.net/en_US/sdk.js';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

Now in your login page, create a Facebook button to your liking and handle the click event as follows.

onFacebookButtonClicked() {
FB.getLoginStatus((response) => {
if (response.status === 'connected') {
this.getUserprofileDetails(response.authResponse.accessToken);
} else {
FB.login((loginResponse) => {
this.getUserprofileDetails(loginResponse.authResponse.accessToken);
}, {scope: 'email'});
}
});
}

getUserprofileDetails(token: any) {
FB.api('/v2.9/me', 'get', {access_token: token, fields: 'id,name,email'}, (res) => {
this.yourSuccessMethod(res.email, res.id, 'Facebook');
});
}

That’s pretty much it to get your Facebook integration working.

Also ensure that you transition your Angular application to https to keep it working always. Using http might not work the first time. Refresh your screen and try it again to get it working during development testing.
Lets get started on Google authentication. What left me confused was why Google didn’t have a Typescript library for this when they were the ones supporting the Angular framework and were vocal advocates of Typescript.

Start off by creating a project from here: https://developers.google.com/identity/sign-in/web/sign-in. By the end of it, you should have yourself a client ID.

<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="YourClientID.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>

I would prefer having your own Google SignIn button to have better control of the login flow.

<button id="googleBtn">
<img src="./../../assets/images/google_signin.png">
</button>
declare const gapi: any;
ngAfterViewInit() {
this.googleInit();
}

public googleInit() {
gapi.load('auth2', () => {
this.auth2 = gapi.auth2.init({
client_id: 'YourClientID.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
scope: 'profile email'
});
this.attachSignin(document.getElementById('googleBtn'));
});
}

public attachSignin(element) {
this.auth2.attachClickHandler(element, {},
(googleUser) => {
const profile = googleUser.getBasicProfile();
this.yourSuccessMethod(profile.getEmail(), profile.getId(), 'Google');
}, (error) => {
console.log(error);
});
}

Voila. Now you have Facebook and Google authenticated in your Angular application.

On login success, if you’re trying to navigate to the home page and you face an issue where none of your home page components have loaded, the only way to get around it is to refresh your page through a flag. Reach out to me in the comments section if you’ve got issues.

Top comments (0)