简体   繁体   English

使用jwt调用google api以对原始端点进行服务到服务的调用的工作节点示例?

[英]Working node example of calling google api with jwt for service-to-service call to raw endpoint?

I've been putzing with trying to call the jobs.Insert bigquery rest api endpoint with node (the jobs.Insert method does not seem to be exposed in the bigquery node library). 我一直试图尝试调用jobs.insert bigquery rest api端点与节点(Jobs.Insert方法似乎未在bigquery节点库中公开)。

I've got the Service-to-Service stuff set up so that I can successfully call the methods that the bigquery node library has (create the json file that has the private key, etc. in it for service-to-service calls). 我已经设置了服务到服务的内容,以便可以成功调用bigquery节点库具有的方法(创建包含私钥的json文件等,用于服务到服务的调用) 。

As far as I can tell, I should be able to do call the rest api directly with a signed jwt as the bearer token without having to go through a two-step OAuth process. 据我所知,我应该能够直接使用签名的jwt作为承载令牌来调用rest api,而不必经过两步的OAuth过程。

I've got stuff to sign a jwt but still getting authentication errors trying to call the raw api just with curl (as a first step) via something like 我有一些东西可以签署一个jwt,但仍然尝试通过curl调用curl(作为第一步)尝试调用原始api时出现身份验证错误

curl -H "Authorization: Bearer my_signed_jwt" https://www.googleapis.com/bigquery/v2/projects/my_project_id/datasets

("Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential." (“请求具有无效的身份验证凭据。预期的OAuth 2访问令牌,登录cookie或其他有效的身份验证凭据。”

Does anyone have an example of doing this? 有人有这样做的例子吗? Might be missing just a simple thing that a working example would make obvious. 可能遗漏了一个简单的事情,一个可行的例子就很明显了。

thanks 谢谢

You can use this working example which does 您可以使用该工作示例

  1. Init query object 初始化query对象
  2. Init oAuth2 object 初始化oAuth2对象
  3. Call bigQuery.Jobs.insert 呼叫bigQuery.Jobs.insert

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

import {google} from 'googleapis'

let bigQuery = google.bigquery("v2")

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

    it('Test query', async () => {
        let result = await test('panada')

    })

    async function test(p1) {
        try {
            let query = `SELECT url FROM \`publicdata.samples.github_nested\`
                WHERE repository.owner = 'panada'`

            let auth = getBasicAuthObj()
            auth.setCredentials({
                access_token: "myAccessToken",
                refresh_token: "myRefreshToken"
            })

            let request = {
                "projectId": "myProject",
                auth,
                "resource": {
                    "projectId": "myProject",
                    "configuration": {
                        "query": {
                            query,
                            "useLegacySql": false
                        },
                        "dryRun": false
                    }
                }
            }

            console.log(`query is: ${query}`)

            let result = await callBQ(request) //Check JOB status to make sure it's done
            console.log(`result is: ${JSON.stringify(result.data)}`)

            result.forEach((row, index) => {
                console.log(`row number ${index}, url is: ${row.url}`)
            })
        } catch (err) {
            console.log("err", err)
        }
    }

    /**
     * Call BigQuery jobs.insert
     * @param request
     * @returns {Promise}
     */
    async function callBQ(request) {
        debugger
        console.log("request", request)
        try {
            let result = await bigQuery.jobs.insert(request, request)//, (err, results) => {
            console.log(`All good.....`)

            return result
        } catch (e) {
            console.log(`Failed to run query: ${e}`)
        }

    }


    /**
     * Create oAuth object
     * @returns {OAuth2Client}
     */
    function getBasicAuthObj() {
        let clientId = 'myClientId'
        let clientSecret = 'mySecret'
        let redirectUrl = 'url'

        return new google.auth.OAuth2(
            clientId,
            clientSecret,
            redirectUrl
        )
    }
})

note: You need to add this line to your package.json 注意:您需要将此行添加到package.json

"googleapis": "34.0.0"

ok - the trick as to my original question had to do with getting an access token for use in the api call. 好的-关于我的原始问题的技巧与获取用于api调用的访问令牌有关。

const { JWT } = require('google-auth-library');
function getJWTResultWithAccessAndRefreshToken(jsonObjectFromGoogleKeyEtcFile,
                                                callbackWithErrAndResult) {

var scopes = [
              "https://www.googleapis.com/auth/bigquery",
              "https://www.googleapis.com/auth/cloud-platform",
              "https://www.googleapis.com/auth/devstorage.full_control",
              "https://www.googleapis.com/auth/devstorage.read_only",
              "https://www.googleapis.com/auth/devstorage.read_write"
            ];

var jwt = new JWT(
    jsonObjectFromGoogleKeyEtcFile.client_email,
    null,
    jsonObjectFromGoogleKeyEtcFile.private_key,
    scopes);

jwt.authorize(function (err, result) {
    callbackWithErrAndResult(err, result.access_token, result.refresh_token);
});

} }

Here, jsonObjectFromGoogleKeyEtcFile is the json object from the json file you get when you generate "Service account keys"/Credentials in the Google Cloud Platform APIs & Services page. 在这里,jsonObjectFromGoogleKeyEtcFile是在Google Cloud Platform APIs and Services页面中生成“服务帐户密钥” /凭据时所获得的json文件中的json对象。

The access_token generated can be used to make a call like below - which worked - where I used the access_token from the function above, and got the projectId from the project_id property of jsonObjectFromGoogleKeyEtcFile: 生成的access_token可用于进行如下调用(在我使用了上面函数的access_token的情况下有效),并从jsonObjectFromGoogleKeyEtcFile的project_id属性获取projectId:

curl -H "Authorization: Bearer generated_via_jwt_access_token" \                    
          https://www.googleapis.com/bigquery/v2/projects/projectId/datasets

Interestingly, you get a refresh_token, too, but it has value "jwt-placeholder" 有趣的是,您也会获得一个refresh_token,但它的值是“ jwt-placeholder”

Whew. 呼。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM