Authorization with Google and OAuth 2.0

Abstract

This article explains and demonstrates how to sign in to a web application with Google using OAuth 2.0. Google is used as authorization provider while the developer of the web application saves time and the user of the web app does not need to fill a registration form and does not have to remember another password for this app. This article was inspired by the article "Gottvertrauen - Benutzer von Web-Anwendungen mit Hilfe von OAuth 2.0 authentifizieren" by Oliver Lau published in the c't magazine (cf. sources).

Definition

"OAuth is an open standard for authorization. OAuth provides client applications a 'secure delegated access' to server resources on behalf of a resource owner. It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials."[1]

Objective

The objective of this demo is to use Google as authorization provider and retrieve an access token. This token is normally valid for 60 minutes (3600 seconds). After this period, the user either has to login with Google (confirm the consent screen) again or the application (client, i.e., JavaScript or the Server, i.e., ASP.NET) has to request a new access token. For server side operations the webserver can put another token into the session only allowing for requests from this client in order to prevent violation. The web server application can store the refresh token (token data) and exchange it to a new access token in order to overcome expiring access tokens. In this case, the user only has to confirm the consent screen once.

OAuth Roles

resource owner: An entity capable of granting access to a protected resource. When the resource owner is a person, it is referred to as an end-user.

resource server: The server hosting the protected resources, capable of accepting and responding to protected resource requests using access tokens.

client An application making protected resource requests on behalf of the resource owner and with its authorization. The term "client" does not imply any particular implementation characteristics (e.g., whether the application executes on a server, a desktop, or other devices).

authorization server The server issuing access tokens to the client after successfully authenticating the resource owner and obtaining authorization.[4]

Define a new project

The first step is to set up a new project in the Google Developer Console. Detailed instructions can found here (Step 1: Create a client ID and client secret).

Include a Login-Button

The sample code and detailed instructions for a Google login button can found here (Step 3 and 4).

<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>

<div id="signinButton">

    <span class="g-signin"

    data-scope="profile"

    data-clientid="YOUR_CLIENT_ID"

    data-redirecturi="postmessage"

    data-accesstype="offline"

    data-cookiepolicy="single_host_origin"

    data-callback="signInCallback">

    </span>

</div>

<div id="result"></div>

Please note: The Google sign in button can be customized, please review Google+ branding guidelines


Consent Screen:

A click on the Sign in with Google button will show the typical OAuth consent screen that has to be confirmed.


The data-callback procedure will run immediately and after the login returning the status signed_in when login was successful. The authResult returned looks like the following:

Object {state: "", access_token: "ya29.iwGcFJaq...", token_type: "Bearer", expires_in: "3600", code: "4/FPRNN-TtDM-1nOH-5BLfp..."…}

OAuth results:

A little script can hide the login button after successful login:

function signInCallback(authResult) {

    if (authResult.status.signed_in) {

        $('#signinButton').css('visibility', 'hidden');

    }

}

Account (Profile) Information (G+)

After successfully logged in, the following information is available:

Sign out

  The log out can be done with the following JavaScript code: Please note: The google account cookie is persistent in your browser. Reloading this page will automatically log you in again.

function signout() {

    gapi.auth.signOut();

}


Revoke access

The resource owner can revoke access for connected apps at any time.

You can revoke access in Apps connected to your account

Alternatively this can be done directly with a revoke access/disconnect user button.

function disconnectUser() {    

    $.ajax({

        url: 'https://accounts.google.com/o/oauth2/revoke?token=' + me.access_token,

        type: 'GET',

        async: false,

        contentType: 'application/json',

        dataType: 'jsonp',

    }).done(function (nullResponse) {

        alert('user disconnected');

    })

    return false;

}

Conclusion

OAuth 2.0 is a state-of-the-art authentication approach for the Web 2.0 applications. When using it simply to authenticate users, it can be quickly and easily integrated and it saves the user time and nerves for "yet another" registration form and the need to remember another password for the web application at hand.

The bearer token will expire after one hour. It can be exchanged to retrieve a refresh token, which allows the client to refresh the access token (i.e., retrieve a new one) before it will expire.

When the access key expired, the user will have to confirm the consent dialog once again after the access token has expired. A common approach is to store the refresh token for the user in a server-side database and to enable the server (still a client) in terms of OAuth to get access tokens with bothering the user to confirm the consent screen again.

JavaScript & Co.

The previous examples used the Google JavaScript API. There are some more client libraries, e.g., for .NET, available. This approach could do the communication with the Google Services on the server-side with a more powerful language like C# or Visual Basic.

With the bearer (holder, similar to owner) token, the client can perform action on behalf of the logged in user or the client can use the successful login information to perform action in your own web application.
For experienced developers there is a security issue: With the bearer token, a user can perform actions via REST/HTTP API. Therefor the user should be careful when granting access to a web application and on the other hand the developer should require only minimal access rights to perform the tasks needed.

HTTP Examples

https://www.googleapis.com/plus/v1/people/me?access_token=ya29.kQGIZ...


Dieter Neumann