如何在 node.js 中使用 OAuth2 [英] How to use OAuth2 with node.js

查看:36
本文介绍了如何在 node.js 中使用 OAuth2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用@google-cloud 客户端库将数据插入到 BigQuery.
由于我有多个客户并且每个客户都有不同的 IAM 角色,因此我无法使用这样的服务帐户:

I would like to use @google-cloud client lib to insert data to BigQuery.
Since I have multiple clients and each has different IAM role I can't use a service account like this:

const bigquery = new BigQuery({
                projectId: `myProject`,
                keyFilename: '/Users/services/ssh/myProject-111.json'
            });

我宁愿像这样使用特定于客户端的 oauth2:

rather I would like to use client-specific oauth2 like this:

const bigquery = new BigQuery({
                projectId: `mydata-1470162410749`,
                token: clientOauth2Token
            });

我收到此错误

过程中出错:请求的身份验证凭据无效.预期的 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据.请参阅 https://developers.google.com/identity/sign-in/web/devconsole-project.- 无效的凭据

Error in the process: Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project. - Invalid Credentials

这是我使用的完整 mocha 测试代码:

This is the full mocha test code I'm using:

import BigQuery from '@google-cloud/bigquery';
import {GoogApi} from "../apiManager" //Private code to get Token from client DB

if (!global._babelPolyfill) {
    var a = require("babel-polyfill")
}

describe('Check routing', async () => {

    it('Test stack  ', async (done) => {

        //Fetch client Auth from local Database
        let apiManager = new GoogApi({query: {integrationTest: 'on'}}, {}, (err, httpResults) => {});
        let clientAuth = await apiManager.getGoogleTokensByUserId(`user@company.con`);

        //Replace the 2 value below with real values
        const tableName = "myTest";
        const dataset = "EVALUEX_DEV";

        try {
            const bigquery = new BigQuery({
                projectId: `myProject`,
                token: clientAuth.credentials.access_token
            });
            await bigquery.createDataset(dataset)
                .then(
                    args => {
                        console.log(`Create dataset, result is: ${args}`)
                    })
                .catch(err => {
                    console.log(`Error in the process: ${err.message}`)
                })
        } catch (err) {
            console.log("err", err)
        }
    })
})

这是我检查令牌时的样子

This is how my Token looks like when I Inspect it

{
  "domain": null,
  "_events": {},
  "_eventsCount": 0,
  "transporter": {},
  "credentials": {
    "access_token": "My Token",
    "refresh_token": "my Refresh Token"
  },
  "certificateExpiry": null,
  "refreshTokenPromises": [],
  "_clientId": "my Client Id",
  "_clientSecret": "My client secret",
  "redirectUri": "https://s1dg0yjhih.execute-api.us-east-1.amazonaws.com/stage1/goog/saveToken",
  "eagerRefreshThresholdMillis": 300000
}

推荐答案

您共享的 JSON 对象不是 OAuth 令牌,它看起来像来自@google-auth-library 的 OAuth2Client 对象.

The JSON object you shared is not an OAuth token, it looks like a OAuth2Client object from @google-auth-library.

实际的 OAuth 令牌只是一个字符串,例如ya29.ABC123ABC123_cG123ABCDETCETCETC".

An actual OAuth token is simply a string, like "ya29.ABC123ABC123_cG123ABCDETCETCETC".

那个令牌"实际上是一个 OAuth2Client 然后你可以使用 getAccessToken 方法获取令牌.如果它只是一个普通的 JSON 对象,那么你可以得到 credentials.access_token 字段,就是实际的访问令牌.

That "token" is actually an OAuth2Client then you can fetch the token with the getAccessToken method. If it is just a plain JSON object, then you can get the credentials.access_token field, is the actual access token.

请注意,访问令牌会过期.getAccessToken 会在必要时获取一个新的,但仅从对象中获取 access_token 不会,并且会在过期后导致 403s.

Note that access tokens expire. getAccessToken will get a new one if necessary, but just getting the access_token from the object will not, and can result in 403s after it expires.

这篇关于如何在 node.js 中使用 OAuth2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆