NodeJS:用于服务器端应用程序的谷歌登录



根据本文档,我成功地为服务器端应用程序执行了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做同样的事情:

  1. 只需使用CLIENT_SECRET_FILEscopesauth_code即可轻松生成凭据(就像我对Python所做的那样(

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

提前谢谢!

我已经使用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());

最新更新