Google OAuth2.0如何在电子应用程序中刷新访问令牌?

问题描述

我使用此api为我的电子应用程序提供google登录功能

https://github.com/googleapis/google-auth-library-nodejs

我的访问令牌在3600秒后过期

我不希望我的用户在3600秒后再次登录

如何使令牌自动刷新?

我尝试在我的应用程序上使用文档示例代码

但这似乎不起作用

如何获取新的access_token

我尝试下面的代码来获取新的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 (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...