首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使Google oAuth2Client对象可重用Node.js应用程序?

如何使Google oAuth2Client对象可重用Node.js应用程序?
EN

Stack Overflow用户
提问于 2021-04-24 08:43:55
回答 1查看 194关注 0票数 0

我正在构建一个执行Google和Docs调用的Node.js CLI,这些调用是在函数中预先定义的。但是,由于每个API调用都必须得到授权,所以我创建了一个单独的文件和函数,它读取凭据,并应该返回要导出的授权oAuth2Client对象,并在需要作为参数传递的任何函数中重用。其思想是,readCredentials()函数调用将调用authorize()函数,如果存在token.json,则该函数将返回oAuth2Client对象。否则,它将提示用户使用getAccessToken()函数进行身份验证。

整个逻辑实际上只是稍微修改了一下Google文档中的quickstart示例,但是打算在应用程序中的任何函数中重用,而不仅仅是在当前的文件中。

但是由于某些原因,当我试图调用并将凭据存储在变量中,然后使用它们授权index.js中的API调用时,控制台中会返回API。

有人知道出了什么问题吗?

authorize.js

代码语言:javascript
复制
const fs = require("fs");
const readline = require("readline");
const { google } = require("googleapis");

const SCOPES = ["https://www.googleapis.com/auth/drive.file"];

const TOKEN_PATH = "token.json";

const readCredentials = () => {
  fs.readFile("credentials.json", (err, content) => {
    if (err) return console.log("Error loading client secret file:", err);
    authorize(JSON.parse(content));
  });
};

const authorize = (credentials) => {
  const { client_secret, client_id, redirect_uris } = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
    client_id,
    client_secret,
    redirect_uris[0]
  );

  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client);
    oAuth2Client.setCredentials(JSON.parse(token));
  });

  return oAuth2Client;
};

const getAccessToken = (oAuth2Client) => {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: "offline",
    scope: SCOPES,
  });
  console.log("Authorize this app by visiting this url:", authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question("Enter the code from that page here: ", (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error("Error retrieving access token", err);
      oAuth2Client.setCredentials(token);

      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log("Token stored to", TOKEN_PATH);
      });

      return oAuth2Client;
    });
  });
};

module.exports = { readCredentials };

index.js

代码语言:javascript
复制
const authorize = require("./authorize");
const drive = require("./drive");
...
let credentials = authorize.readCredentials();

drive.createFolder(credentials);
...
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-12 20:31:07

对于Node.js,您可以从使用passport.js开始。它将将用户信息存储在会话中,并且可以使用req.user进行访问。要使用API,您将需要用户的access_token,您可以通过refresh_token获得它。以下是passport.js网站的一个基本示例。

代码语言:javascript
复制
var GoogleStrategy = require( 'passport-google-oauth2' ).Strategy;

passport.use(new GoogleStrategy({
    clientID:     GOOGLE_CLIENT_ID,
    clientSecret: GOOGLE_CLIENT_SECRET,
    callbackURL: "http://yourdomain:3000/auth/google/callback",
    passReqToCallback   : true
  },
  function(request, accessToken, refreshToken, profile, done) {
    User.findOrCreate({ googleId: profile.id }, function (err, user) {
      return done(err, user);
    });
  }
));


app.get('/auth/google',
  passport.authenticate('google', { scope:
      [ 'email', 'profile' ] }
));

app.get( '/auth/google/callback',
    passport.authenticate( 'google', {
        successRedirect: '/auth/google/success',
        failureRedirect: '/auth/google/failure'
}));

我也建议将refresh_token添加到数据库中,这样您就可以随时获得access_token。在上面的例子中,它使用了Mongo数据库。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67240873

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档