我的网络应用程序已成功通过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或其他有效的身份验证凭据。请参阅{{ 3}}。“>
其他一些重要功能:
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)
请帮助我了解尝试获取用户信息时为什么我的凭据不起作用。我应该改变什么?
提前谢谢!
答案 0 :(得分:0)
您仅请求配置文件范围。要同时请求电子邮件地址,请添加范围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']