gpt4 book ai didi

javascript - (仍未解决)授权 Web App 访问客户端和服务器端的用户 Google Calendar? (使用 Firebase 和 Google API)

转载 作者:数据小太阳 更新时间:2023-10-29 04:48:53 26 4
gpt4 key购买 nike

我有一个 Firebase 网络应用
并希望任何用户可以登录并授权我的网络应用客户端访问他的谷歌日历(读/写) strong> 和 Server 端(在用户在线和离线时管理日历)。


客户端
google developers console 上创建 API key OAuth 2.0 客户端 ID(Web 应用程序) 后,我已经实现了这段代码:

首先,通过Firebase Authentication登录Google

firebase.initializeApp({apiKey: 'MY_WEB_APP_API_KEY'})
var provider = new firebase.auth.GoogleAuthProvider()
provider.addScope('https://www.googleapis.com/auth/calendar')
firebase.auth().signInWithPopup(provider)

然后,请求授权我的 Web 应用程序 可以使用 Google Api JS client 访问用户的 Google 日历

// https://apis.google.com/js/api.js
gapi.load('client:auth2', () => {
gapi.auth2.authorize({
scope: 'https://www.googleapis.com/auth/calendar',
client_id: 'MY_WEB_APPL_CLIENT_ID',
prompt: 'none',
access_type: 'offline',
include_granted_scopes: true
}, () => {
gapi.client.init({
discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest']
}).then(() => {
return gapi.client.calendar.events.list({
calendarId: 'ANY_USER_CALENDAR_ID' // example: 123456789@group.calendar.google.com
})
}).then((resolve, reject) => {
// IT WORKS ON CLIENT SIDE (RETURNS EVENTS LIST AS EXCEPTED)
})
})
})

在这里,客户端一切正常(读取和写入连接的用户 Google Calendar)。


但是现在,在服务器端
google developers console 上创建了一个 .json Service Account Key (App Engine default service account) 之后,我在 Firebase Cloud Functions 上实现了 google-api-nodejs-client,使用此代码:

const privatekey = require("./MY_WEB_APP_SERVICE_ACCOUNT_KEY.json")
const {google} = require('googleapis')
const jwtClient = new google.auth.JWT(
privatekey.client_email,
null,
privatekey.private_key,
['https://www.googleapis.com/auth/calendar']
)
jwtClient.authorize()
const calendar = google.calendar('v3')

calendar.events.list({
auth: jwtClient,
calendarId: 'ANY_USER_CALENDAR_ID' // (in this case, the same previously used on client side: 123456789@group.calendar.google.com)
}).then((resolve, reject) => {
// IT DOESNT WORKS ON SERVER SIDE (RETURNS 'Not Found' ERROR...)
})

这里身份验证有效
但是 calendar.events.list() 返回了一个'Not Found' 错误(这不是真的有帮助...)。


如果用户之前允许我的网络应用访问他的日历,
通过服务帐户读取或写入这些日历应该可行吗?

所以我不明白我错过或误解了什么?并且需要明确的代码才能继续。

希望我的解释足够清楚。

感谢您的帮助!

最佳答案

当用户授予您的应用程序权限(使用客户端 ID)时,您的应用程序将能够访问用户的信息,在本例中为日历。

但是,这不是通过服务帐户完成的,而是通过客户端 ID 完成的。

在您的服务器端代码(云功能)中,您似乎正在使用服务帐户对 Google 日历进行身份验证,这意味着您正在访问服务帐户的日历而不是不是在 webapp 中经过身份验证的用户(类似于常规帐户,服务帐户可以访问 Drive 或 Calendar 等服务)。

您的服务帐户将无权访问用户的日历,除非用户向服务帐户提供/共享日历(类似于将日历共享给其他 gmail 帐户)。

如果您想在服务器端访问该用户的日历,您需要将客户端上的 Google 身份验证返回的访问 token 和刷新 token 传递到您的服务器端。然后,您可以使用访问 token 代表用户调用日历。

关于javascript - (仍未解决)授权 Web App 访问客户端和服务器端的用户 Google Calendar? (使用 Firebase 和 Google API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50070443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com