在 Google Cloud Platform 控制台中将同意屏幕授权域添加为本地测试域。具体步骤如下:
示例代码:
from google.oauth2 import id_token
from google.auth.transport import requests
# The CLIENT_ID and CLIENT_SECRET in the following code come from
# the API Console Credentials page:
# https://console.developers.google.com/apis/credentials
CLIENT_ID = ''
CLIENT_SECRET = ''
# Use the following redirect URI when running the sample on your
# development server. After deploying your application to production,
# use your own URL.
REDIRECT_URI = 'http://localhost:8080/oauth'
# ...
auth_request = request('https://accounts.google.com/o/oauth2/auth', ...)
auth_response_text = auth_response.text
if 'accounts.google.com/o/oauth2/approval' in auth_response_text:
# Send an empty POST request to the approval URL:
approval_response = requests.post(auth_response.url, data={}, ...)
# ...
# ...
if self.request.get('code'):
# Exchange the authorization code for a refresh token and access token:
authorization_code = self.request.get('code')
credentials = flow.step2_exchange(authorization_code)
userid = credentials.id_token['sub']
# ...
其中,和需要替换为自己的客户端 ID 和 secret。= 'http://localhost:8080/oauth' 需要替换为自己的本地测试 URL。