我想验证 gapi 客户端库,这样我就可以代表另一个用户创建电子表格,即 oauth。
此代码用于工作:
gapi.load('client:auth2', function() {
gapi.auth2.init({
clientId: 'CLIENT_ID',
scope: 'https://www.googleapis.com/auth/spreadsheets',
}).then(function() {
return gapi.auth2.getAuthInstance().signIn();
}).then(function() {
console.log('Signed in!');
}, function(error) {
console.error(error);
});
});
但是现在有人说 gapi.auth2 已被弃用,所以我尝试执行以下操作
google.accounts.id.initialize({
client_id: 'CLIENT_ID',
callback: handleCredentialResponse
});
google.accounts.id.prompt();
function handleCredentialResponse(response) {
gapi.client.setToken(response.credential)
}
然后
function createSpreadsheet() {
gapi.client.sheets.spreadsheets
.create({
properties: {
title: "My New Spreadsheet",
},
})
.then((response) => {
// The spreadsheet is created successfully
console.log("Spreadsheet created:", response.result.spreadsheetUrl);
})
.catch((err) => {
console.error("Failed to create spreadsheet", err);
});
}
这给了我“缺少凭据错误”
我也试过像这样设置凭据:
gapi.auth.setToken({ access_token: token })
同样的错误。
我错过了什么?
一段时间后,我弄明白了,并且能够验证 gapi 以使用电子表格 API。
ID token 和 Authorization token 让我很困惑,那是两个不同的东西。事不宜迟,这是工作示例:
var token;
function initGoogle() {
// init client
const client = google.accounts.oauth2.initTokenClient({
client_id: "YOUR_CLIENT_ID",
callback: handleCredentialResponse,
scope: "https://www.googleapis.com/auth/spreadsheets",
});
// send authorize request
// this prompts user to grant access
client.requestAccessToken();
}
// this thing is needed to load spreadsheet client library JSON dicovery document
async function fetchDiscoveryDoc() {
const resp = await fetch(
"https://sheets.googleapis.com/$discovery/rest?version=v4"
);
return resp.json();
}
async function handleCredentialResponse(response) {
console.log("loading client library");
await new Promise((resolve) => {
gapi.load("client", () => {
resolve();
});
});
const discoDoc = await fetchDiscoveryDoc();
console.log("Loading spreadsheets");
// loading spreadsheet library using discovery document
await new Promise((resolve, reject) => {
gapi.client.load(discoDoc).then(() => {
console.log("Spreadsheets loaded");
resolve();
});
});
console.log("Setting authorization token");
gapi.client.setToken(response);
console.log("All set. Client is ready to make authorized API calls. Creating spreadsheet");
await gapi.client.sheets.spreadsheets.create({
properties: {
title: "My New Spreadsheet",
},
});
}
注意,这是隐式授权流程,安全性较低,但不涉及后端。在这里阅读更多:https://developers.google.com/identity/oauth2/web/guides/use-token-model