node.js - NodeJS : Google Sign-In for server-side apps

标签 node.js google-api

关注此documentation我成功地为服务器端应用程序执行 Google 登录,并可以在服务器端使用 Python 访问用户的 GoogleCalendar。我无法使用 NodeJS 做到这一点。

简而言之 - 在 Python 中,我使用了从浏览器发送的 auth_code 并获得了如下凭证:

from oauth2client import client

credentials = client.credentials_from_clientsecrets_and_code(
    CLIENT_SECRET_FILE,
    ['https://www.googleapis.com/auth/drive.appdata', 'profile', 'email'],
    auth_code)

然后我可以在数据库中存储以下值:

gc_credentials_json = credentials.to_json()

并生成凭据(是的,它在需要时单独使用刷新 token ):

client.Credentials.new_from_json(gc_credentials_json)

所以我想使用 NodeJS 做同样的事情:

  1. 仅使用以下内容即可轻松生成凭据:CLIENT_SECRET_FILEscopesauth_code(就像我使用 Python 所做的那样)

  2. 使用以前的凭据值接收凭据,而不分析访问 token 是否过期 - 我更喜欢现成的(经过社区充分测试)解决方案

提前谢谢您!

最佳答案

我已经使用 google-auth-library 包实现了它。

这是检索 gcClient 的函数:

const performAuth = async () => {
    const tokens = await parseTokenFromDB();
    const auth = new OAuth2Client(
        downloadedCredentialsJson.web.client_id,
        downloadedCredentialsJson.web.client_secret
    );
    auth.on('tokens', async (newTokens) => {
        updateDBWithNewTokens(newTokens);
    });
    await auth.setCredentials(tokens);
    const gcClient = google.calendar({version: 'v3', auth});
    return gcClient;
};

这是 parseTokenFromCurrentDB 函数的模板,只是为了给出其输出的想法:

const parseTokenFromCurrentDB = async () => {
    // Put here your code to retrieve from DB the values below 
    return {
        access_token,
        token_type,
        refresh_token,
        expiry_date,
    };
};

因此,使用此实现可以获得gcClient:

const gcClient = await gc.getGcClient(org);

并使用它的方法,例如:

const gcInfo = await gc.getInfo(gcClient);
const events = await gc.getEvents(gcClient, calcPeriodInGcFormat());

关于node.js - NodeJS : Google Sign-In for server-side apps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51450853/

相关文章:

javascript - MiniCssExtractPlugin 没有创建 css 文件

javascript - node.js 请求编码(谷歌翻译)

c# - 如何以编程方式从 Google 云端硬盘中的 "share with me"中删除文件

javascript - 谷歌网络服务按位置获取时间?

api - 如何使用带有 Java 的 Google QPX API 进行航类搜索?

javascript - 如何获取 google webmasters api (Node.js) 的访问 token

mysql - 错误:Cannot enqueue Query after invoking quit in MySQL with NodeJS

mysql - (NodeJS、MySQL、AngularJS、Express 4.0)不阻止用户的 api/路由有风险吗?

node.js - 为什么 jsonwebtoken 会抛出 "invalid signature"错误?

node.js - 我怎样才能使用 googleapis 来 react native ?