【问题标题】:Error using google API and OAUTH2 in Python to get user info在 Python 中使用 google API 和 OAUTH2 获取用户信息时出错
【发布时间】:2019-10-18 13:47:49
【问题描述】:

我的网络应用程序已成功通过 google 推荐的流程来获取查询 Google Drive API 的凭据。这工作正常。但是,当我尝试使用已获得的相同凭据来获取用户的电子邮件和姓名时,我会收到错误消息。

我在这里检索凭据并查询 Google Drive 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

在那之后,我尝试使用 SAME CREDENTIALS 来获取用户信息,但现在它不起作用

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 返回“请求缺少所需的身份验证凭据。需要 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据。请参阅 @987654321 @.">

其他一些重要功能:

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)

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

提前致谢!!!

【问题讨论】:

    标签: google-api google-oauth google-api-python-client


    【解决方案1】:

    您只是请求配置文件范围。要同时请求电子邮件地址,请添加范围 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']
    

    【讨论】:

    • 谢谢。我更改了代码以添加电子邮件,但仍然收到完全相同的错误:googleapis.com/oauth2/v2/userinfo?alt=json returned "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See developers.google.com/identity/sign-in/web/devconsole-project.">
    • 1) 我看不到您在会话中存储凭据的位置。发布完整的代码而不是片段。 2)您的代码在哪里收到此错误? 3) 显示您对用户进行身份验证的页面和您处理重定向的页面。
    • 还有一点。更改代码中的范围后,您需要使旧会话无效。
    • 谢谢@JohnHanley !!!我真蠢。问题源于我没有使旧会话无效。一旦我纠正了这一点,程序就会完美运行。没有你的帮助,我不可能发现它!
    • @ClementBjelland - 欢迎您,很高兴为您提供帮助。不要忘记关闭这个问题。
    猜你喜欢
    • 2012-07-21
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2015-02-21
    • 2013-08-21
    相关资源
    最近更新 更多