google-api - Google 日历 API - 如何在不提示登录的情况下发出请求?
问题描述
我有一个简单的问题:
我正在开发一个需要完全授权才能向 Google 日历发出请求的网站。我设法使用来自网络服务器的 javascript 完成所有我需要的请求并且它可以工作,但我需要登录到我的谷歌帐户才能工作。这给使用我的网站的其他用户带来了问题,因为如果他们没有登录到我的谷歌帐户,请求将不起作用。
我明白为什么它不起作用,我的问题是如何才能让我的网站获得完全访问权限以使用谷歌日历而无需登录我的谷歌帐户,如果没有人必须登录谷歌帐户就更好了执行任务??
解决方案
您当前使用的登录形式称为 Oauth2。它要求用户验证访问权限。
您应该使用的是服务帐户。服务帐户是预先授权的。您需要与服务帐户共享您的个人日历,然后它才能访问它。
唯一的缺点是 JavaScript 不支持服务帐户身份验证,您需要切换到服务器端语言,例如 node.js。
'use strict';
const {google} = require('googleapis');
const path = require('path');
/**
* The JWT authorization is ideal for performing server-to-server
* communication without asking for user consent.
*
* Suggested reading for Admin SDK users using service accounts:
* https://developers.google.com/admin-sdk/directory/v1/guides/delegation
*
* See the defaultauth.js sample for an alternate way of fetching compute credentials.
*/
async function runSample () {
// Create a new JWT client using the key file downloaded from the Google Developer Console
const client = await google.auth.getClient({
keyFile: path.join(__dirname, 'jwt.keys.json'),
scopes: 'https://www.googleapis.com/auth/drive.readonly'
});
// Obtain a new drive client, making sure you pass along the auth client
const drive = google.drive({
version: 'v2',
auth: client
});
// Make an authorized request to list Drive files.
const res = await drive.files.list();
console.log(res.data);
return res.data;
}
if (module === require.main) {
runSample().catch(console.error);
}
// Exports for unit testing purposes
module.exports = { runSample };
从 smaples jwt中提取的代码
推荐阅读
- java - 为什么菜单没有添加到 Android 的工具栏?
- mqtt - Paho C 库中的 MQTT 数据包加密/解密 API
- java - 有没有办法拆分或减小我的字符串数组的大小?
- elm - Elm 中的通用模式匹配
- loops - 循环优化
- r - R - 按名称将多个 2 级元素附加到列表的每个 1 级元素
- python - Plotly 未在 PyCharm 上显示图形
- sql-server - 如何在 SQL SERVER 中将十进制值转换为十六进制
- excel - 填充和替换和公式的问题
- android - 无法解析外部依赖项 com.google.gms:google-services:4.2.0,因为没有定义存储库。安卓工作室 3.5