由于访问令牌在 1 小时内持续过期,我一直在尝试创建刷新令牌。
window.onload = function () {
google.accounts.id.initialize({
client_id: ,
callback: handleCredentialResponse,
});
google.accounts.id.renderButton(
document.getElementById("google-signin-button"),
{ theme: "outline", size: "large", shape: "circle" } // customization attributes
);
google.accounts.id.prompt(); // also display the One Tap dialog
};
在谷歌的这篇文档中,没有提到创建刷新令牌。 https://developers.google.com/identity/gsi/web/guides/overview
谁能帮帮我谢谢。
Sign-in
或身份验证是登录并返回 id 令牌和访问令牌,并识别机器背后的用户。
Oauth2
是授权并返回访问令牌和刷新令牌,授予您的应用程序访问用户数据的权限。
登录不会返回刷新令牌。
如果您在链接的页面上进一步阅读,您将被罚款标题为分离的身份验证和授权时刻
的部分要获取用于 Google API 的访问令牌,或加载一些用户数据,您需要调用 Google Identity Services 授权 API。它是一个独立的 JavaScript API,但与身份验证 API 打包在一起。
您的问题的解决方案是使用 Google Identity Services 授权 API 而不是使用 Oauth2 登录来授权用户。
你没有遵循很好的教程,我也花了很多时间才找到它
如果您想要刷新令牌,您需要使用服务器端方式。
https://developers.google.com/identity/protocols/oauth2/web-server#node.js
可能会帮助某人,如果您需要
refresh_token
那么您需要授权,而不是身份验证。进行服务器端调用,即使用 googleapis
lib 服务器端,使用适当的凭据加载它
import { google } from 'googleapis';
const oauth2Client = new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
process.env.GOOGLE_REDIRECT_URL // Ensure this is set correctly in your .env file
);
// Generate a secure random state value for CSRF protection
const state = crypto.randomBytes(32).toString('hex');
// Store state in cookies securely (for CSRF protection)
cookies().set('oauth_state', state, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
});
最后
oauth2Client.generateAuthUrl({
access_type: 'offline', // offline is important so it returns the refresh token, once you have it, save it in your db or any persistent storage.
scope: scope, // Use the selected scope
include_granted_scopes: true, // Include already granted scopes
state: state, // CSRF protection state
redirect_uri: process.env.GOOGLE_REDIRECT_URL, // Redirect back after consent
})
generateAuthUrl
将返回一个URL,将用户重定向到该URL,以便他们可以从谷歌访问同意屏幕,当他们批准访问时,谷歌将重定向到您的GOOGLE_REDIRECT_URL
,当在GOOGLE_REDIRECT_URL
路径上时,您将需要从url参数中捕获code
和state
,将oauth_state
cookie值与url参数中的state
进行比较以实现csrf保护。最后
const oauth2Client = new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
process.env.GOOGLE_REDIRECT_URL
);
const { tokens } = await oauth2Client.getToken(code);
const { refresh_token, scope, access_token, expiry_date, id_token } =
tokens;