【发布时间】:2015-09-16 20:35:51
【问题描述】:
我正在使用Flask 构建一个RESTful API,目前有两个页面(一个login 页面和一个index 页面)。
index 页面只能在用户登录后才能访问。
目前我有:
@app.route('/venue/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
venue_owner_email = request.form['username']
venue_owner_password = request.form['password']
with contextlib.closing(DBSession()) as session:
try:
venue = session.query(Venue).filter_by(venue_owner_email=venue_owner_email).first()
if not venue or not pwd_context.verify(venue_owner_password, venue.venue_owner_password):
error = 'Invalid Credentials. Please try again.'
else:
return redirect(url_for('index'))
except exc.SQLAlchemyError, error:
session.rollback()
raise_database_error(error)
return render_template('login.html', error=error)
@app.route('/', methods = ['GET'])
def index():
return render_template('index.html')
目前index.html 可以通过/ 访问,但我只想通过/venue/login 访问它,而不是直接从浏览器访问。
如果我使用装饰器@auth.login_required,当redirect 出现时,user 必须重新输入他们的凭据。 redirecting时有没有办法发送HTTP Authorisation Header?
我还认为,与其使用redirect,不如直接使用render_template,但我不知道这是否是正确的做法。
任何有关如何正确执行此操作的帮助将不胜感激。
【问题讨论】:
-
检查会话是否存在于('/')中,如果没有,使用304代码重定向登录
-
@Sidmeister 当我试图遵循
REST原则时,我应该将sessions存储在服务器上吗? -
会话未存储在服务器中。设置会话,您基本上将值存储在客户端的 cookie 中。为登录用户存储一些凭据并执行必要的检查。为了更安全,我建议在每个请求中替换随机字符串。或者您可以采用自定义策略来阻止伪造。
-
只是想澄清一下:我不应该用
HTTP Auth Headers保护路由?另外,我如何防止直接通过@app.route('/', methods = ['GET'])访问该页面?
标签: python nginx flask restful-authentication