使用 google API 和 Python 中的 OAUTH2 获取用户信息时出错

Error using google API and OAUTH2 in Python to get user info

我的 Web 应用程序已成功通过 google 的推荐流程以获取凭据以查询 Google 驱动器 API。这很好用。但是,当我尝试使用已获得的相同凭据来获取用户的电子邮件和姓名时,出现错误。

我在这里检索凭据并查询 Google 驱动器 API。这工作得很好

def analyze():
 credentials = getCredentials() 
 drive_service = googleapiclient.discovery.build('drive', 'v3', credentials=credentials)
 theFiles = drive_service.files().list(pageSize=1000,q="trashed=false", fields="files(id,name,modifiedTime, size)").execute() #THIS WORKS

紧接着,我尝试使用相同的凭证来获取用户信息,但现在它不起作用

oauth2_client = googleapiclient.discovery.build('oauth2','v2',credentials=credentials)
 user_info= oauth2_client.userinfo().get().execute() #THIS FAILS
givenName = user_info['given_name']

错误:https://www.googleapis.com/oauth2/v2/userinfo?alt=json 返回 "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.">

其他一些重要功能:

def getCredentials():
 *Loads credentials from the session.*
 sc = session['credentials'] 
 credentials = google.oauth2.credentials.Credentials(token=sc.get('token'),
 client_id=sc.get('client_id'),
 refresh_token=sc.get('refresh_token'),
 token_uri=sc.get('token_uri'),
 client_secret=sc.get('client_secret'),
 scopes=sc.get('scopes'))

回调页面获取凭证:

@app.route('/OAcallback')
def OAcallback():
   flow =google_auth_oauthlib.flow.Flow.from_client_secrets_file('client_id.json', scopes=['https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/userinfo.profile'])
  flow.redirect_uri = return_uri
  authorization_response = request.url
  flow.fetch_token(authorization_response=authorization_response)
  credentials = flow.credentials 
  * Store the credentials in the session.*
  credentials_to_dict(credentials)

请帮助我理解为什么我的凭据在尝试获取用户信息时不起作用。我应该改变什么?

提前致谢!!!

您只是请求配置文件范围。要同时请求电子邮件地址,请添加范围 email.

将这部分代码更改为:

scopes=['https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/userinfo.profile']

至:

scopes=['https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/userinfo.profile' 'email']