Google oauth2获取id_token

时间:2016-06-24 10:30:48

标签: javascript angularjs oauth-2.0 google-oauth

我在客户端angularjs.I工作我试图实现谷歌oauth2。我得到了accessstoken但我需要得到id_token。

我添加了app.js,controller.js和html part。

我遵循了本教程: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>

3 个答案:

答案 0 :(得分:2)

您需要使用 nonce 。添加它, id_token 将作为回应。

例如:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef SplittedString char[BUFSIZ]

int main()
{
   FILE *infile;
   char token_seperator[]={"\n"};
   SplittedString data;
   SplittedString myLines[50];   // you can modify this number to hold more lines
   int i=0;
   infile=fopen("example","r");

   while((fgets(data,BUFSIZ,infile)!=NULL) && i < 50){ //prevent array overflow
       printf("%s\n",data);
       strcpy(myLines[i], data);
       ++i;
   }
 }

对于隐式流程 nonce param是必需的。有关详细信息,请查看http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthRequest

答案 1 :(得分:0)

要触发OpenID Connect流,这是OAuth 2.0的扩展,您需要添加&#34; openid&#34;身份验证请求中的范围(以及urlencode中间的空格),所以:

var scope="openid%20email";

答案 2 :(得分:0)

要接收 id_token ,您需要将 response_type 参数更改为:

var response_type="id_token";

作为回复,您将获得 id_token 。如果您同时需要 id_token access_token ,则应添加&#34; 令牌&#34;到 response_type

var response_type="token id_token";

要了解详情,read OpenId article

您也可以使用Google Ouath Playground

测试身份验证流程
相关问题