簡體   English   中英

使用 Firebase 函數的 Google oAuth2 回調問題

[英]Issue with Google oAuth2 callback using Firebase functions

我想使用 Firebase 函數來使用 Google Developer API。 使用此 API 需要進行身份驗證。

我按照文檔: https : //github.com/googleapis/google-api-nodejs-client

我在回調 url 中獲取授權碼時遇到了一些麻煩。

var {google} = require('googleapis');
google.options({ auth: oauth2Client });

var oauth2Client = new google.auth.OAuth2(
  'XXXX.apps.googleusercontent.com',
  'XXXX',
  'https://us-central1-XXXX.cloudfunctions.net/oauth2callback'
);

function generateAuthenticationUrl() {

  return oauth2Client.generateAuthUrl({
    access_type: 'offline',
    prompt: 'consent',
    scope: 'https://www.googleapis.com/auth/androidpublisher'
  });
}

exports.oauth2Callback = functions.https.onRequest((req, res) => {
  console.log(req.query.code);
  const code = req.query.code;
  //do something
  return null;
});


exports.hello = functions.https.onRequest((req, res) => {
  var url = generateAuthenticationUrl();
  console.log(url);

  //-> url print in the console is : https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&prompt=consent&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fandroidpublisher&response_type=code&client_id=XXXXX-XXX.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fus-central1-XXX.cloudfunctions.net%2Foauth2callback

  res.redirect(url);
});

重定向 url 在 Google Console Developer 中設置:

OAuth 2.0 客戶端 ID

當我調用 url https://us-central1-XXX.cloudfunctions.net/hello ,我在 Firebase 日志中收到“錯誤:無法處理請求”和“已完成狀態:‘超時’”。

怎么了?

我找到了解決方案。 使用 JWT 進行身份驗證的完整代碼,然后獲取應用程序的評論列表:

const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase);

var {google} = require('googleapis');
const serviceAccount = require('./client_secret.json');
const { JWT } = require('google-auth-library');


const getAuthorizedClient = () => new JWT({
    email: serviceAccount.client_email,
    key: serviceAccount.private_key,
    scopes: ['https://www.googleapis.com/auth/androidpublisher']
});

const getAndroidpublisher = () => google.androidpublisher({
    version: 'v3',
    auth: getAuthorizedClient()
});



const requestProductValidation = () => new Promise((resolve, reject) => {

    getAndroidpublisher().reviews.list({
            packageName: "com.my.packagename"
        }, (err, response) => {

        if (err) {
            console.log(`The API returned an error: ${err}`);
            resolve({status: "Error"});
        } else {

           return resolve(response);

        }
    });
});


exports.hello = functions.https.onRequest((req, res) => {   
      return requestProductValidation();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM