如何在oauth2回调时恢复flask.session对象

时间:2012-05-11 12:33:47

标签: python oauth-2.0 flask

我正在通过oauth2编写新浪微博客户端,以便为已经使用我自己网站帐户的当前用户添加身份验证,因为OAuth2使用了重定向回调机制,似乎在此例程之后,并且在回调视图中处理程序,flask.session完全是一个新对象。因此我失去了当前用户的登录状态。

但是在同一浏览器(如Firefox)中添加新标签并访问我网站的主页(www.funfunsay.com),会话对象仍然存在!

所以在同一个浏览器实例中有两个flask.session ???

我写了一个非常简单的模块,它与新浪微博相得益彰,但我失去了旧会话。

# -*- coding: utf-8 -*-

from flask import (Flask, render_template, current_app, request,
                   flash, url_for, redirect, session, g, abort)


# For import *
__all__ = ['create_app']

app = Flask(__name__)
app.config['DEBUG'] = True
app.secret_key = 'secret key'

@app.before_request
def before_request():
    print "before request:", session
    #<1st output>for first visit www.funfunsay.com, the output is: before request: <SecureCookieSession {}>
    #<3rd output>for callback from sina, the output is the same

@app.after_request
def after(response):
    print "after request:", session
    #<2nd output>for first visit www.funfunsay.com, the output is: after request: <SecureCookieSession {'testinfo': 'abc'}*>
    return response


@app.route('/')
def hello_world():
    print "request:", request
    login_uri = 'https://api.weibo.com/oauth2/authorize?redirect_uri=http%3A//funfunsay.com/connect/sina/callback&response_type=code&client_id=3921006605&display=default'

    session['testinfo'] = 'abc' #a key-value for test

    return redirect(login_uri)

@app.route("/connect/sina/callback")
def connect_sina_callback():
    print "connect_sina_callback: ", session
    #<4th output>will output: connect_sina_callback:  <SecureCookieSession {}>
    return 'Callback success!'

if __name__ == '__main__':
    app.run('0.0.0.0', 80)

PS:出于测试目的,我在主机文件中添加“127.0.0.1 www.funfunsay.com”。

2 个答案:

答案 0 :(得分:2)

保持域名的一致性。如果用户输入“my-web-site.com”,我的解决方案始终使用“www.my-web-site.com”,将其重定向到“www.my-web-site.com”。现在一切都好!

答案 1 :(得分:0)

Flask为来自不同原点的每个请求分配一个新会话 - 因此,即使地址解析为相同的IP,来自不同起点的每个请求也将被分配不同的会话。例如。从http://localhost:5000开始的浏览器窗口将从同一浏览器窗口中的选项卡分配不同的会话,该窗口定向到http://127.0.0.1:5000 ...即使这两个会议解析到同一位置。

这可能令人沮丧,因为一个会话中的数据将无法用于同一浏览器中的其他选项卡,正如您所期望的那样......而一个会话可能会在您浏览网站时愉快地存储所有数据,另一个标签将有一个空的session变量。

我在使用OAuth回调时发现这一点非常棘手,当我需要确保回调网址(在您发送请求的服务器上定义,例如当您使用数据提供程序定义OAuth应用程序时) )匹配我发起请求的网站。例如,如果Github API Developer页面中的OAuth应用程序设置将回调URL列为http://localhost:5000/callback,则无法将浏览器指向http://127.0.0.1:5000,因为回调将在新会话中启动,并且会话空数据为空。

幸运的是,这很容易调试(至少在localhost开发中):确保使用与在数据提供程序中定义回调URL相同的主机格式来测试您的站点。 OAuth应用程序设置(在Facebook,Twitter或Github OAuth API面板中定义应用程序时)。