【问题标题】:Importing Google OAuth2Client in Angular 4在 Angular 4 中导入 Google OAuth2Client
【发布时间】:2018-11-28 14:11:43
【问题描述】:

我正在尝试使用 Google 的示例来验证我的客户的 id 令牌。这是示例(https://developers.google.com/identity/sign-in/web/backend-auth):

const {OAuth2Client} = require('google-auth-library'); // <-- here's the error
const client = new OAuth2Client(CLIENT_ID);
async function verify() {
  const ticket = await client.verifyIdToken({
      idToken: token,
      audience: CLIENT_ID,  // Specify the CLIENT_ID of the app that accesses the backend
      // Or, if multiple clients access the backend:
      //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
  });
  const payload = ticket.getPayload();
  const userid = payload['sub'];
  // If request specified a G Suite domain:
  //const domain = payload['hd'];
}
verify().catch(console.error)

我的问题是第一行,我在其中导入了 Google Auth 库。如果我以这种方式导入库,则会收到 404(未找到)错误,因为路径被错误地解释为“localhost/(root)/google-auth-library”(root 是项目)。另一方面,如果我一直输入到“src”的整个相对路径,我会收到“语法错误:意外标记“

导入库的正确方法是什么? 请注意,这是一个 Angular 4 项目,我已经使用 npm 安装了该库,但不导入它,我仍然无法使用 OAuth2Client 类。

【问题讨论】:

    标签: angular typescript npm google-authentication


    【解决方案1】:

    这应该可以工作,抱歉,没有在角度测试它,但可以在节点打字稿项目中工作。

    import * as gApi from 'google-auth-library';
    const gClient = new gApi.OAuth2Client(YOUR_CLIENT_ID);
    /*Should wrap in try catch...
      Also needs to be in an async method to use await, otherwise use promise then, error 
    syntax
    */
    const payload = await gClient.verifyIdToken({ idToken: YOUR_TOKEN, audience: YOUR_CLIENT_ID });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-30
      • 1970-01-01
      • 2018-03-09
      • 2018-03-22
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 2018-04-23
      相关资源
      最近更新 更多