无法从Google API获取OAuth2令牌信息

问题描述

我可以使用以下代码从Google api获取访问oauth2令牌:

<html><head></head><body>
<script>
  var YOUR_CLIENT_ID =
'568020407566-s1tdctjbjeocf5nt20l64midfo1atu4h.apps.googleusercontent.com';
  var YOUR_REDIRECT_URI =
'https://us-central1-hyperledger-poc.cloudfunctions.net/oauthjax';
  var fragmentString = location.hash.substring(1);

  // Parse query string to see if page request is coming from OAuth 2.0 server.
  var params = {};
  var regex = /([^&=]+)=([^&]*)/g,m;
  while (m = regex.exec(fragmentString)) {
    params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
  }
  if (Object.keys(params).length > 0) {
    localStorage.setItem('oauth2-test-params',JSON.stringify(params) );
    if (params['state'] && params['state'] == 'try_sample_request') {
      trySampleRequest();
    }
  }

  // If there's an access token,try an API request.
  // Otherwise,start OAuth 2.0 flow.
  function trySampleRequest() {
    var params = JSON.parse(localStorage.getItem('oauth2-test-params'));
    if (params && params['access_token']) {
      var xhr = new XMLHttpRequest();
      xhr.open('GET','https://www.googleapis.com' +
          'access_token=' + params['access_token']);
      xhr.onreadystatechange = function (e) {
        if (xhr.readyState === 4 && xhr.status === 200) {
          console.log(xhr.response);
        } else if (xhr.readyState === 4 && xhr.status === 401) {
          // Token invalid,so prompt for user permission.
          oauth2SignIn();
        }
      };
      xhr.send(null);
    } else {
      oauth2SignIn();
    }
  }

  /*
   * Create form to request access token from Google's OAuth 2.0 server.
   */
  function oauth2SignIn() {
    // Google's OAuth 2.0 endpoint for requesting an access token
    var oauth2Endpoint = 'https://accounts.google.com/o/oauth2/v2/auth';

    // Create element to open OAuth 2.0 endpoint in new window.
    var form = document.createElement('form');
    form.setAttribute('method','GET'); // Send as a GET request.
    form.setAttribute('action',oauth2Endpoint);

    // Parameters to pass to OAuth 2.0 endpoint.
    var params = {'client_id': YOUR_CLIENT_ID,'redirect_uri': YOUR_REDIRECT_URI,'scope': 'https://www.googleapis.com/auth/userinfo.email','state': 'try_sample_request','include_granted_scopes': 'true','response_type': 'token'};

    // Add form parameters as hidden input values.
    for (var p in params) {
      var input = document.createElement('input');
      input.setAttribute('type','hidden');
      input.setAttribute('name',p);
      input.setAttribute('value',params[p]);
      form.appendChild(input);
    }

    // Add form to page and submit it to open the OAuth 2.0 endpoint.
    document.body.appendChild(form);
    form.submit();
  }
</script>

<button onclick="trySampleRequest();">Try sample request</button>
</body></html>

我正在尝试使用https://oauth2.googleapis.com/tokeninfo?id_token=XYZ123 mentioned in below google document

获取令牌信息

https://developers.google.com/identity/protocols/oauth2/openid-connect#validatinganidtoken

我得到以下错误作为响应:

{
  "error_description": "Invalid Value"
}

但是,如果我使用相同的令牌来获取用户信息,则通过使用以下代码和响应也可以正常工作

我尝试过的代码:

const token = req.body.access_token;
 var options = {
    host: 'www.googleapis.com',port: 443,//path: '/oauth2/v3/userinfo',path: '/oauth2/v3/tokeninfo?id_token='+token,method: 'GET',headers: {'Authorization': 'Bearer '+ token}
  }
  // making the https get call
  let data;
  var getReq = await https.request(options,function(response) {
    response.on('data',(chunk) => {
      data += chunk;
    });
    response.on('end',function() {
      // Data reception is done,do whatever with it!
      console.log("line 52");
     // var parsed = JSON.parse(data);
            console.log("line 54"+data);
      res.send(data);
     // console.log('data',parsed);
   //   console.log('endSTATUS: ' + parsed);

    });
  });
  //  console.log("response",recievedJSON);
  /*getReq.on('end',function(){
   res.send(valid);
  });*/
  getReq.end();
  getReq.on('error',function(err) {
    console.log('Error: ',err);
  });

回复:

{
      "sub": "1070944556782450037456","picture": "https://lh6.googleusercontent.com/-b32hSj9vONg/AAAAAAAAAAI/AAAAAAAAAAA/tasdfsadfBfIQ/photo.jpg","email": "xxxxxxxxx@gmail.com","email_verified": true
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...