Gmail API 使用 OAuth 2.0 协议进行身份验证和授权。OAuth 2.0 令牌分为两种类型:访问令牌(Access Token)和刷新令牌(Refresh Token)。访问令牌用于访问资源,但有较短的有效期。刷新令牌用于在访问令牌过期后获取新的访问令牌。
当你需要长期访问用户的 Gmail 数据时,使用刷新令牌可以确保你的应用在访问令牌过期后仍然能够获取新的访问令牌,从而持续访问 Gmail API。
以下是使用授权码流程刷新令牌的步骤:
以下是一个使用 Python 和 Google API 客户端库刷新令牌的示例:
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# 你的客户端 ID 和客户端密钥
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
# 作用域
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
def refresh_token():
creds = None
# 检查是否有存储的凭据
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# 如果没有凭据或凭据无效,获取新的凭据
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# 保存凭据以便下次使用
with open('token.json', 'w') as token:
token.write(creds.to_json())
return creds
# 刷新令牌并获取新的访问令牌
creds = refresh_token()
print(f'New Access Token: {creds.token}')
通过以上步骤和示例代码,你可以实现以编程方式刷新 Gmail API 的令牌。
领取专属 10元无门槛券
手把手带您无忧上云