【发布时间】:2020-08-18 00:35:20
【问题描述】:
我目前有一个应用程序需要我从客户端和服务器调用 google drive api。现在,我已经在前端使用 auth 2.0 对用户进行了身份验证,我可以正常上传文件了。
本节的大部分代码,我从文档和各种博客文章中搜集而来。
async function uploadDocGoogle() {
// get file
const fileChooser = document.getElementById('config-file-upload');
const file = fileChooser.files[0];
console.log("file", file);
const fileMetaData = {
'name': file.name,
'mimeType': file.type
};
var accessToken = gapi.auth.getToken().access_token; // Here gapi is used for retrieving the access token.
await setGoogleAPIToken(accessToken);
console.log(accessToken);
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(fileMetaData)], {type: 'application/json'}));
form.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open('post', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id');
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'json';
xhr.onload = () => {
console.log(xhr.response.id); // Retrieve uploaded file ID.
console.log(xhr);
};
xhr.send(form);
}
var SCOPES = 'https://www.googleapis.com/auth/drive';
var authorizeButton = document.getElementById('config-google-test');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
//authorizeButton.onclick = handleAuthClick;
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
console.log("Logged In");
} else {
console.log("Logged Out");
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
现在我需要从用 NodesJS 编写的后端调用 api。但是,我想使用我已经从前端获得的内容来授权这些调用。在前端为调用生成的身份验证令牌似乎只是临时的,所以我认为我不能将其发送到后端来授权调用。我想知道是否有人知道另一种方法?我想知道是否有人也知道如何初始化 google api 以使用该令牌进行调用。
【问题讨论】:
-
@DaImTo 你是说如果我使用这个刷新令牌来做所有事情,我将无法从客户端上传?我必须将文件发送到服务器并从那里上传?有没有办法使用刷新令牌在客户端授权请求?
标签: node.js oauth-2.0 google-drive-api google-oauth google-api-nodejs-client