如何解决Flask使用OAuth验证来使用Google Drive API
我当前正在使用Oauth2.0登录我的Flask应用。我已经按预期工作了。现在,我想使用从登录时获得的相同凭据来向Google Drive API发送请求。我不太确定从哪里开始,文档很难遵循。
注意:我已经在开发者控制台中激活了Google Drive API。
这是登录回调的代码。
全局:
GOOGLE_CLIENT_ID = config['google_client_id']
GOOGLE_CLIENT_SECRET = config['google_client_secret']
GOOGLE_DISCOVERY_URL = (
"https://accounts.google.com/.well-known/openid-configuration"
)
client = WebApplicationClient(GOOGLE_CLIENT_ID)
查看功能:
@bp.route('/login/callback')
def callback():
# Get authorization code Google sent back to you
code = request.args.get("code")
# Find out what URL to hit to get tokens that allow you to ask for
# things on behalf of a user
google_provider_cfg = get_google_provider_cfg()
token_endpoint = google_provider_cfg["token_endpoint"]
token_url,headers,body = client.prepare_token_request(
token_endpoint,authorization_response=request.url,redirect_url=request.base_url,code=code
)
token_response = requests.post(
token_url,headers=headers,data=body,auth=(GOOGLE_CLIENT_ID,GOOGLE_CLIENT_SECRET),)
# Parse the tokens!
client.parse_request_body_response(json.dumps(token_response.json()))
# Now that you have tokens (yay) let's find and hit the URL
# from Google that gives you the user's profile information,# including their Google profile image and email
userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
uri,body = client.add_token(userinfo_endpoint)
userinfo_response = requests.get(uri,data=body)
# You want to make sure their email is verified.
# The user authenticated with Google,authorized your
# app,and now you've verified their email through Google!
if userinfo_response.json().get("email_verified"):
unique_id = userinfo_response.json()["sub"]
users_email = userinfo_response.json()["email"]
picture = userinfo_response.json()["picture"]
username = userinfo_response.json()["given_name"]
else:
return "User email not available or not verified by Google.",400
user = User.query.filter(User.google_sub==unique_id).first()
login_user(user)
def get_google_provider_cfg():
return requests.get(GOOGLE_DISCOVERY_URL).json()
我的想法也许是我必须设置一个Google Drive端点才能使用相同的令牌将api请求发送到?我不太确定。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。