【问题标题】:Flask to only allow access to page internallyFlask 只允许在内部访问页面
【发布时间】: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


【解决方案1】:

您可以向index.html 添加一个装饰器,以检查引荐网址。如果引用 url 是 /venue/login 你应该提供页面,否则返回错误。

if request.referrer == <venue login url>:
    # continue
 else:
    # return error message

【讨论】:

    猜你喜欢
    • 2011-07-31
    • 2014-08-11
    • 1970-01-01
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 2016-12-01
    • 1970-01-01
    相关资源
    最近更新 更多