如何配置Google Script OAuth实现一次授权后无需每次token过期重新登录
解决方案
你遇到的OAuth授权过期后需要重新登录的问题,核心原因是当前代码没有请求离线访问权限,无法获取刷新令牌来自动刷新过期的AccessToken,按以下方案修改即可实现一次授权长期有效:
核心修改点
- 在OAuth服务配置中添加
access_type=offline参数,请求谷歌返回刷新令牌,OAuth2库会自动存储刷新令牌,在AccessToken过期时自动调用接口刷新,无需用户二次授权 - 添加
prompt=consent参数,确保首次授权时强制弹出授权确认页,避免因历史授权记录无法拿到刷新令牌 - 补全Gmail函数中服务实例的获取逻辑
修改后的完整代码
function Gmail() { // 补全服务实例获取逻辑 var service = getServiceGmail(); if (service.hasAccess()) { var toolKeyFinal = service.getAccessToken(); //*******request would run with token here******** } else { var authorizationUrl = service.getAuthorizationUrl(); var toolName = "Gmail工具"; // 替换为你自定义的工具名称 var string = toolName + " Authorization (then try formula again 👍)," + authorizationUrl; return string.split(",") } } function getServiceGmail() { return OAuth2.createService('Gmail') .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth') .setTokenUrl('https://accounts.google.com/o/oauth2/token') .setClientId('CLIENT-ID') // 替换为你自己的客户端ID .setClientSecret('CLIENT-SECRET') // 替换为你自己的客户端密钥 .setCallbackFunction('authCallback') .setPropertyStore(PropertiesService.getDocumentProperties()) .setScope('https://mail.google.com/') // 新增以下两行配置 .setParam('access_type', 'offline') .setParam('prompt', 'consent'); }; /** * Handles the OAuth callback. */ function authCallback(request) { var service = getServiceGmail(); var authorized = service.handleCallback(request); if (authorized) { return HtmlService.createHtmlOutput( "<script>window.top.location.href='https://REDIRECT.com';</script>" ); //return HtmlService.createHtmlOutput('PowerSheet authorization successful for your Google Sheet! You can close this tab.'); } else { return HtmlService.createHtmlOutput('You did not provide authorization. Please close this tab and try again.'); } }
注意事项
- 修改后需要先清除之前的授权记录,重新走一次授权流程,才能拿到刷新令牌
- 刷新令牌默认长期有效,除非用户手动在谷歌账号的授权管理中取消对你的应用授权,否则不需要重新授权
- 确保你的谷歌云API控制台中配置的OAuth同意屏幕已经发布为正式版本,否则测试版本的刷新令牌7天就会过期
内容的提问来源于stack exchange,提问作者Chris Lally
相关产品推荐
相关产品推荐

