bio photo

Twitter Github

This example shows how to integrate with Googles OAuth 2.0 for client side javascript using AngularJS. The flow for the authentication is as shown below

Flow

The flow starts by redirecting the browser to the google servers for authentication.

 1 angular.module('angularoauthexampleApp')
 2   .controller('MainCtrl', function ($scope) {
 3     $scope.login=function() {
 4     	var client_id="your client id";
 5     	var scope="email";
 6     	var redirect_uri="http://localhost:9000";
 7     	var response_type="token";
 8     	var url="https://accounts.google.com/o/oauth2/auth?scope="+scope+"&client_id="+client_id+"&redirect_uri="+redirect_uri+
 9     	"&response_type="+response_type;
10     	window.location.replace(url);
11     };
12   });

The most important parameters in the url are

  1. client_id - This is the client id of the application that will identify itself to google
  2. scope - this is the scope of permissions that you are requesting the user to grant
  3. redirect_url - This is the url which google will call back after the authentication is sucessful
  4. response_type - Use token for client side javascript. This will return the token in the query parameters of the redirect url
  5. state - optional state that would be received on the callback. Useful for passing state information and for security validation

Use the window.location object to setup the redirect

1 window.location.replace(url);

When the authentication is sucessful, we need to now configure the routes in angular to parse out the token.

 1 angular
 2   .module('angularoauthexampleApp', [
 3   ])
 4   .config(function ($routeProvider) {
 5     $routeProvider
 6       .when('/access_token=:accessToken', {
 7         template: '',
 8         controller: function ($location,$rootScope) {
 9           var hash = $location.path().substr(1);
10           
11           var splitted = hash.split('&');
12           var params = {};
13 
14           for (var i = 0; i < splitted.length; i++) {
15             var param  = splitted[i].split('=');
16             var key    = param[0];
17             var value  = param[1];
18             params[key] = value;
19             $rootScope.accesstoken=params;
20           }
21           $location.path("/about");
22         }
23       })
24   });

The redirect url will look like http://localhost:4000#access_token=….

As the redirect url contains the # it works well with angular only if the redirect url does not contain a path, and it would get routed to the given controller. All that remains is to parse the access token from the redirect url.

It is also possible to use the html5 mode in the location provider to disable the hashbang mode and work properly with regular urls.

Fork the example code at GitHub