node.js - NodeJS:用于服务器端应用程序的 Google 登录
问题描述
按照本文档,我成功地为服务器端应用程序执行 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)
然后我可以在 DB 中存储以下值:
gc_credentials_json = credentials.to_json()
并生成凭据(是的,它在需要时单独使用 refresh_token):
client.Credentials.new_from_json(gc_credentials_json)
所以我想用 NodeJS 做同样的事情:
CLIENT_SECRET_FILE
使用 just :scopes
和auth_code
(就像我使用 Python 一样)轻松生成凭据使用以前的凭据值接收凭据,而不分析访问令牌是否已过期 - 我更喜欢现成的(经过社区测试的)解决方案
先感谢您!
解决方案
我已经使用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());
推荐阅读
- mysql - 用于修剪 char 字段的 SQL Server 全局设置
- html - 为什么我的“onclick()”事件在 Angular 中不起作用?
- java - 域服务与应用程序服务的示例
- javascript - 使用 vba 在 Internet Explorer 上单击带有部分 href 的超链接
- javascript - 重定向到同一目录中的页面 - Javascript
- excel - Excel vba,从 Outlook 检索联系人信息,无法检索位置列
- django - 在 Manjaro OS 上安装 psycopg2 以在 django 中使用 postgresql 时出错
- azure-cognitive-search - Azure 搜索即服务是否会被弃用
- ruby - 如何在 Rspec 测试中允许对模块常量的非限定访问?
- c++ - 类专业化中的clang / gcc不一致