You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask会话变量用于OAuth CSRF防护时丢失导致验证失败的问题求助

Flask会话变量用于OAuth CSRF防护时丢失导致验证失败的问题求助

我正在尝试写一个简单的Python Flask应用,想用Google的people API获取用户的数字Google ID(这东西好像没别的办法拿到)。这需要用户通过Google的OAuth认证,我已经把基础功能弄好了,但Google的OAuth文档里提到:

The OAuth client must prevent CSRF as called out in the OAuth2 Specification . One way to achieve this is by using the state parameter to maintain state between your authorization request and the authorization server's response.

所以我跟着一个示例来做,把state存在会话变量里。我的代码是这样的:

@app.route('/auth')
def auth():
    auth_url, state = get_oauth_flow().authorization_url()
    app.logger.debug(f'Setting session state: {state}')
    flask.session['state'] = state
    return flask.redirect(auth_url)

@app.route('/oauth2callback')
def oauth2callback():
    session_state = flask.session.get('state')
    request_state = flask.request.args.get('state')
    app.logger.debug(f'Got session state: {session_state}')
    app.logger.debug(f'Got request state: {request_state}')
    if session_state is None or session_state != request_state:
        return 'Danger, Will Robinson!', 400
    del flask.session['state']
    flow = get_oauth_flow()
    flow.fetch_token(authorization_response=flask.request.url)
    flask.session['oauth_token'] = flow.credentials.token
    return flask.redirect('success')

但每次走登录流程的时候都会失败,我收到了"Danger, Will Robinson!"的提示。日志显示会话变量被清空了:

DEBUG in ging: Setting session state: ijV2BAyuZG8uSO4rpN77nczw5UDEJf
DEBUG in ging: Got session state: None
DEBUG in ging: Got request state: ijV2BAyuZG8uSO4rpN77nczw5UDEJf

我本身不是专业的Web开发者,现在完全摸不着头脑。有没有人能告诉我可能哪里错了,或者有其他解决办法?

备注:内容来源于stack exchange,提问作者Ian Pilcher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 16:19:34