RSKMR
RSKMR

Reputation: 1892

Google oauth2 get id_token

I am working in client side angularjs.I am try to implement google oauth2. I am getting accesstoken but i need to get id_token.

I added app.js , controller.js and html part.

I followed this tutorial: http://anandsekar.github.io/oauth2-with-angularjs/

app.js:

 angular
  .module('angularoauthexampleApp', [ ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/access_token=:accessToken', {
        template: '',
        controller: function ($location,$rootScope) {
          var hash = $location.path().substr(1);

          var splitted = hash.split('&');
          var params = {};

          for (var i = 0; i < splitted.length; i++) {
            var param  = splitted[i].split('=');
            var key    = param[0];
            var value  = param[1];
            params[key] = value;
            $rootScope.accesstoken=params;
          }
          $location.path("/about");
        }
      })
      .otherwise({
        redirectTo: '/'
      });
  });

controller.js

angular.module('angularoauthexampleApp')
  .controller('MainCtrl', function ($scope) {

    $scope.login=function() {
        var client_id="your client_id";
        var scope="email";
        var redirect_uri="http://localhost:9000";
        var response_type="token";
        var url="https://accounts.google.com/o/oauth2/auth?scope="+scope+"&client_id="+client_id+"&redirect_uri="+redirect_uri+
        "&response_type="+response_type;
        window.location.replace(url);
    };
  });

html:

<button class="btn btn-primary" ng-click="login()">Login</button>

Upvotes: 3

Views: 4864

Answers (3)

Timofey Lavrenyuk
Timofey Lavrenyuk

Reputation: 407

You need to use nonce. Add it and id_token will be in response.

For example:

let params = {
    'client_id': GOOGLE_API_CLIEND_ID,
    'redirect_uri': `${location.origin}/auth/google`,
    'response_type': 'id_token token',
    'scope': GOOGLE_API_SCOPES,
    'state': 'af0ifjsldkj',
    'nonce': 'n-0S6_WzA2Mj'
};

For implicit flow nonce param is required. For more information you can check http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthRequest

Upvotes: 5

Elias
Elias

Reputation: 812

To receive an id_token, you need to change your response_type param to:

var response_type="id_token";

as the response you will get an id_token. If you need both - the id_token and access_token, you should add "token" to response_type:

var response_type="token id_token";

To learn more, read OpenId article

Also you could test auth flow using Google Ouath Playground

Upvotes: 2

Hans Z.
Hans Z.

Reputation: 53958

To trigger an OpenID Connect flow, which is an extension of OAuth 2.0, you need to add the "openid" scope in the authentication request (and urlencode the space in between), so:

var scope="openid%20email";

Upvotes: 0

Related Questions