//

AngularJS: Google+ Sign In Integration

8.6.2014 | 6 minutes of reading time

Google+ Platform now enables easy, efficient and powerful multi-platform integration of it’s services with almost everything you can imagine.

If you have a need to use Google authentication, over-the-air installs, profile & social graph access, develop your own “hangout” app, or use simple plug-ins like +1 button, Badge, Share and Follow button, provided API’s are going to come in very handy for you.

This article is going to be all about Google authentication for websites, or simply said: “How to integrate Google+ Sign In button into your website and use it for sign in”. Although, Google Documentation is very good and reading trough it will give you not only a clue, but good insights about the functionality of API with some nice examples, it does’t cover some specific details when it comes to AngularJS integration.

We will only cover the basics here, so this article is designed mostly to save your time, but if you wish to learn more, see Google’s PhotoHunt or check out it’s source code from GitHub.

The basics

Sign In Button

The Google Sign In Button which you have probably seen many times on different websites has the role of offering the user the ability to authenticate with Google services. For developer, it is of huge importance because it represents a starting point for communication with Google services.

For our needs we are going to place a in our HTML document with proper id and render it later “manually”.

1<span id="googleSignIn">
2    <span id="signInButton">
3    </span>
4</span>
5

AngularJS gives us a nice feature with ng-hide, which is a flag that hides given component when Boolean variable bound to it is true.

There is more to know about this magical button, and that is that you must add this script in order to render the sign in button:

1<script>// <![CDATA[
2    (function() {
3        var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
4        po.src = 'https://apis.google.com/js/client:plusone.js';
5        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
6    })();
7// ]]></script>
8

This script asynchronously loads plusone.js which is the Google+ JavaScript API (Google recommendation). Should be enough said for now, more detail will follow when we go trough the example part.

Sign In Dialog

After you have rendered the Google Sign In Button and user has clicked on it, the sign in dialog appears. In this dialog user can choose an existing Google account for sign in or create a new one. This dialog is by design just a smaller version of standard Google sign in form.

Next step that will be offered to user will be the permissions page, user must accept these permissions in order to authenticate. For more information about permissions, visit data scopes documentation.

User session state

User will be prompted for authentication first time he tries to sign in, after that he will be signed in automatically unless the user session manually terminated. Google track’s the users signed in state in a persistent cookie store in users domain.

Get your ClientID

In order to use Google+ API and authentication, you must first enable Google+ API and register a new OAuth 2.0  credential. You can achieve this by going to Google Developer Console , and follow these two steps:

  1. Create a new project – Under Projects create a new project, name it as you wish.
  2. Enable Google+ API – Under APIs & auth and after that APIs find Google+ API  and enable it.
  3. Register for credentials – Under APIs & auth and after that Credentials click on “CREATE NEW CLIENT ID“, choose website option and after that insert the URL of your hosted website into “Javascript Origins” text field (i.e. http://localhost:8080). It won’t work if you do not enter your website’s URL properly!

Most important thing after registering your credentials is the “CLIENT ID” you will receive, you will need it when call for authentication is being done.

NOTE: User permissions accepted for a given Google account will remain permanently and do not have anything to do with user session state.

Example

Someone once said, a good example can replace a thousand words, so here we go by defining a simple HTML document.

1<!-- Define controller for body. In this example we use only one controller for the scope of entire body. --><!-- Place a span that is going to act as a container for button rendering through script code. -->
2        <span id="googleSignIn">
3            <span id="signInButton">
4            </span>
5        </span>
6 
7        <!-- Don't forget to place the script that does the asynchronous loading of Google+ JavaScript API.
8             Because it is loaded asynchronously, it might take some time to load. 
9             Place some loading notification, so user won't get confused. 
10             You can use ng-show and ng-hide to show or hide your notification and accomplish best user experience. --><script>// <![CDATA[
11            (function() {
12                var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
13                po.src = 'https://apis.google.com/js/client:plusone.js';
14                var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
15            })();
16 
17// ]]></script><!-- Second script needed for accessing Google API (gapi.*) . It's usage will be described in controller. --><script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
18

If you are confused at this point, please don’t get worried, after we go trough some controller code things will become much more clear:

1function SignInController($scope) {
2    // This flag we use to show or hide the button in our HTML.
3    $scope.signedIn = false;
4 
5    // Here we do the authentication processing and error handling.
6    // Note that authResult is a JSON object.
7    $scope.processAuth = function(authResult) {
8        // Do a check if authentication has been successful.
9        if(authResult['access_token']) {
10            // Successful sign in.
11            $scope.signedIn = true;
12 
13            //     ...
14            // Do some work [1].
15            //     ...
16        } else if(authResult['error']) {
17            // Error while signing in.
18            $scope.signedIn = false;
19 
20            // Report error.
21        }
22    };
23 
24    // When callback is received, we need to process authentication.
25    $scope.signInCallback = function(authResult) {
26        $scope.$apply(function() {
27            $scope.processAuth(authResult);
28        });
29    };
30 
31    // Render the sign in button.
32    $scope.renderSignInButton = function() {
33        gapi.signin.render('signInButton',
34            {
35                'callback': $scope.signInCallback, // Function handling the callback.
36                'clientid': '[CLIENT_ID from Google developer console]', // CLIENT_ID from developer console which has been explained earlier.
37                'requestvisibleactions': 'http://schemas.google.com/AddActivity', // Visible actions, scope and cookie policy wont be described now,
38                                                                                  // as their explanation is available in Google+ API Documentation.
39                'scope': 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email',
40                'cookiepolicy': 'single_host_origin'
41            }
42        );
43    }
44 
45    // Start function in this example only renders the sign in button.
46    $scope.start = function() {
47        $scope.renderSignInButton();
48    };
49 
50    // Call start function on load.
51    $scope.start();
52}
53

Retrieve additional user info

After successful authentication that has been explained in the example, you can retrieve some additional information from signed in user account. Google+ API follows a RESTfull API design, so a call like this:

1GET https://www.googleapis.com/plus/v1/people/{userId}
2

would give us some additional information about given user.

Here is a neat example that shows how to retrieve users domain and e-mail address. Replace “Do some work in previous example with $scope.getUserInfo(); before proceeding.

1// Process user info.
2// userInfo is a JSON object.
3$scope.processUserInfo = function(userInfo) {
4    // You can check user info for domain.
5    if(userInfo['domain'] == 'mycompanydomain.com') {
6        // Hello colleague!
7    }
8 
9    // Or use his email address to send e-mails to his primary e-mail address.
10    sendEMail(userInfo['emails'][0]['value']);
11}
12 
13// When callback is received, process user info.
14$scope.userInfoCallback = function(userInfo) {
15    $scope.$apply(function() {
16        $scope.processUserInfo(userInfo);
17    });
18};
19 
20// Request user info.
21$scope.getUserInfo = function() {
22    gapi.client.request(
23        {
24            'path':'/plus/v1/people/me',
25            'method':'GET',
26            'callback': $scope.userInfoCallback
27        }
28    );
29};
30

Sign out

Google+ API also provides a easy way to terminate user session. Is also done by calling their API, and this is all you need to do:

1gapi.auth.signOut();
2

IMPORTANT: This functionality won’t work if you host your website in localhost for some reason.

share post

Likes

0

//

More articles in this subject area\n

Discover exciting further topics and let the codecentric world inspire you.

//

Gemeinsam bessere Projekte umsetzen

Wir helfen Deinem Unternehmen

Du stehst vor einer großen IT-Herausforderung? Wir sorgen für eine maßgeschneiderte Unterstützung. Informiere dich jetzt.

Hilf uns, noch besser zu werden.

Wir sind immer auf der Suche nach neuen Talenten. Auch für dich ist die passende Stelle dabei.