【问题标题】:Redirect after oauth authentication never happens with flask-oauthoauth 身份验证后重定向永远不会发生在烧瓶-oauth 中
【发布时间】:2015-08-12 19:00:29
【问题描述】:

我正在使用 Flask-Oauth 插件来向 Twitter 进行身份验证。我基本上使用的是文档中的确切代码,但返回索引的重定向似乎永远不会发生。或者,如果发生这种情况,可能是一些奇怪的浏览器缓存正在进行中。

我的主页基本上是这样的:

@app.route('/', methods=['GET'])
def home():
    form = SadForm()
    if not g.user:
        needs_login = True
    else:
        # get some user stuff to display

    return render_template(...)

该页面上有一个按钮可以转到与文档匹配的登录视图:

@app.route('/login')
def login():
    return twitter.authorize(callback=url_for('oauth_authorized',
        next=request.args.get('next') or request.referrer or None))

此视图中涵盖了回调:

@app.route('/oauth-authorized')
@twitter.authorized_handler
def oauth_authorized(response):
    next_url = request.args.get('next') or url_for('home')
    if response is None:
        flash(u'You denied the request to sign in.')
        return redirect(next_url)

    session['user_id'] = response['screen_name']
    current_user = g.db.users.find_one({'user_id': response['screen_name']})
    if current_user:
        user = current_user
    else:
        user = {}
    user['user_id'] = response['screen_name']
    user['twitter_token'] = response['oauth_token']
    user['twitter_secret'] = response['oauth_token_secret']
    g.user = user.copy()
    g.db.users.save(user)
    flash('You were signed in.')
    return redirect(next_url)

这个方法结束时的重定向似乎应该“刷新”home 的视图,因为我们已经设置了g.user,所以将显示用户的内容。但是,在实际操作中,主页认为没有人登录,但如果我使用浏览器按钮刷新页面,它就知道我已登录并呈现正确的数据。

服务器日志如下所示:

21:39:36     INFO werkzeug - 127.0.0.1 - - [28/Dec/2012 21:39:36] "GET / HTTP/1.1" 200 -
21:39:45     INFO werkzeug - 127.0.0.1 - - [28/Dec/2012 21:39:45] "GET /login HTTP/1.1" 302 -
21:39:47     INFO werkzeug - 127.0.0.1 - - [28/Dec/2012 21:39:47] "GET /oauth-authorized?oauth_token=nope&oauth_verifier=beep HTTP/1.1" 302 -

请注意,在 oauth-authorized 的 302 之后,“GET /”没有 200。不应该有吗?

【问题讨论】:

  • 线程本地 g 对象不会在请求之间持续存在,除非您在 before_request 视图或类似的视图中引导它。如果您不这样做,用户对象将不会附加到g。但是你说你在刷新时看到了正确的信息?所以我假设上述情况正在适当地发生。但我还是有点困惑,浏览器是否重定向?您应该会看到对索引的请求,是的。

标签: python oauth flask


【解决方案1】:

原来这是一个简单的缓存问题。在我用@app.after_request 装饰的add_header 方法中,我做了这个更改:

- response.headers['Cache-Control'] = 'public, max-age=600' 
+ response.headers['Cache-Control'] = 'public, max-age=0'

所以,现在浏览器知道每次都重新获取索引视图。最终,对于更大规模的网站,我会改变这种模式,以便有效地使用缓存。

【讨论】:

    猜你喜欢
    • 2020-03-13
    • 2015-02-25
    • 1970-01-01
    • 2015-02-02
    • 2018-07-10
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多