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 (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...