如何解决Google OAuth2.0如何在电子应用程序中刷新访问令牌?
https://github.com/googleapis/google-auth-library-nodejs
我的访问令牌在3600秒后过期
如何使令牌自动刷新?
我尝试在我的应用程序上使用文档示例代码
但这似乎不起作用
如何获取新的access_token
但是什么也没发生
const { app,browserWindow,screen } = require('electron');
const fs = require('fs');
const { google } = require('googleapis'); // auth node js
googleOAuth2Login();
function googleOAuth2Login() {
const ScopES = ['https://www.googleapis.com/auth/drive'];
const TOKEN_PATH = 'token.json';
fs.readFile('credentials.json',(err,content) => {
if (err) return console.log('Error loading client secret file:',err);
authorize(JSON.parse(content),showAccesstoken);
});
function authorize(credentials,callback) {
const { client_secret,client_id,redirect_uris } = credentials.installed;
const oauth2client = new google.auth.OAuth2(
client_id,client_secret,redirect_uris[0]
);
// Check if we have prevIoUsly stored a token.
fs.readFile(TOKEN_PATH,content) => {
if (err) return getAccesstoken(oauth2client,callback);
oauth2client.setCredentials(JSON.parse(content));
callback(JSON.parse(content))
oauth2client.on('tokens',(tokens) => {
//this handle not work
if (tokens.refresh_token) {
// store the refresh_token in my database!
console.log(tokens.refresh_token);
}
console.log(tokens.access_token);
});
});
}
/**
* This method opens a new window to let users log-in the OAuth provider service,* grant permissions to OAuth client service (this application),* and returns OAuth code which can be exchanged for the real API access keys.
*
* @param {*} interactionWindow a window in which the user will have interaction with OAuth provider service.
* @param {*} authPageURL an URL of OAuth provider service,which will ask the user grants permission to us.
* @returns {Promise<string>}
*/
function getoAuthCodeByInteraction(interactionWindow,authPageURL) {
interactionWindow.loadURL(authPageURL,{ userAgent: 'Chrome' });
return new Promise((resolve,reject) => {
const onclosed = () => {
reject('Interaction ended intentionally ;(');
};
interactionWindow.on('closed',onclosed);
interactionWindow.on('page-title-updated',(ev) => {
const url = new URL(ev.sender.getURL());
// console.log(url.searchParams)
if (url.searchParams.get('approvalCode')) {
console.log('allow')
interactionWindow.removeListener('closed',onclosed);
interactionWindow.close();
return resolve(url.searchParams.get('approvalCode'));
}
if ((url.searchParams.get('response') || '').startsWith('error=')) {
console.log('reject')
interactionWindow.removeListener('closed',onclosed);
interactionWindow.close();
return reject(url.searchParams.get('response'));
}
});
});
};
function executeAuthWindow(authWindow,authUrl) {
authWindow.setMenu(null);
authWindow.show();
return new Promise((resolve,reject) => {
getoAuthCodeByInteraction(authWindow,authUrl)
.then((res) => {
if (res != 'Interaction ended intentionally ;(') {
return resolve(res);
}
if (res == 'Interaction ended intentionally ;(') {
return reject('Fail:Authorization window colose');
}
}).catch((err) => {
if (err = 'error=access_denied') {
return reject('Fail: error=access_denied');
}
});
})
}
function getAccesstoken(oauth2client,callback) {
const authUrl = oauth2client.generateAuthUrl({
access_type: 'offline',scope: ScopES
});
const authWindow = new browserWindow({
width: 600,height: 800,show: false,'node-integration': false,'web-security': false
});
executeAuthWindow(authWindow,authUrl)
.then((code) => {
//access_token: and refresh_token:
oauth2client.getToken(code,token) => {
if (err) return console.error('Error retrieving access token',err);
console.log('getToken')
console.log(token)
oauth2client.setCredentials(token);
console.log(oauth2client)
fs.writeFile(TOKEN_PATH,JSON.stringify(token),(err) => {
if (err) return console.error(err);
console.log('Token stored to',TOKEN_PATH);
});
});
}).catch((err) => {
console.log(err)
})
}
// initOAuthClient
function showAccesstoken(token) {
console.log(token)
}
}
凭证文件
{
"installed": {
"client_id": "*******17079-*********gjlh6g2nnndhqotn3ij509k.apps.googleusercontent.com","project_id": "quickstart-**********","auth_uri": "https://accounts.google.com/o/oauth2/auth","token_uri": "https://oauth2.googleapis.com/token","auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs","client_secret": "*********dNz3Gceo9F","redirect_uris": [
"urn:ietf:wg:oauth:2.0:oob","http://localhost"
]
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。