Cookie在Web程序中发挥了很大的作用,其中最重要的功能是存储用户的认证信息。

session通过秘钥对数据进行签名以加密数据,因此,我们得先设置一个秘钥。这里的密钥就是一个具有一定复杂度和随机性的字符串。

程序的秘钥可以通过Flask.secret_key属性或配置变量SECRET_KEY设置,比如:

app.secret_key = 'secret string'

更安全的做法是把密钥写进系统环境变量(在命令行中使用export或set命令),或是保存在.env文件中:

SECRET_KEY = secret string

然后在程序脚本中使用os模块提供的getenv()方法获取:

import os
#...
app.secret_key = os.getenv('SECRET_KEY', 'secret string')

我们可以在getenv()方法中添加第二个参数,作为没有获取到对应环境变量时使用的默认值。

这里的密钥只是示例。在生产环境中,为了安全考虑,必须使用随机生成的密钥。

模拟用户认证,使用session模拟用户的认证功能。

@app.route('/login')
def login():
    session['logged_in'] = True # 写入session
    return redirect(url_for('cookie'))

@app.route('/cookie')
def cookie():
    name = request.args.get('name')
    if name is None:
        name = request.cookies.get('name', 'Human')
        response = '<h1>Hello, %s!</h1>' % name
        # 根据用户认证状态返回不同的内容
        if 'logged_in' in session:
            response += '[Authenticated]'
        else:
            response += '[Not Authenticated]'
        return response

# 退出登录
@app.route('/logout')
def logout():
    if 'logged_in' in session:
        session.pop('logged_in')
    return redirect(url_for('index'))

默认情况下,session cookie会在用户关闭浏览器时删除。通过将 session.permanent属性设为True可以将session的有效期延长为 Flask.permanent_session_lifetime属性值对应的datetime.timedelta对象,也 可通过配置变量PERMANENT_SESSION_LIFETIME设置,默认为31 天。

尽管session对象会对Cookie进行签名并加密,但这种方式仅能够确 保session的内容不会被篡改,加密后的数据借助工具仍然可以轻易读取 (即使不知道密钥)。因此,绝对不能在session中存储敏感信息,比如 用户密码。


0 Comments latest

No comments.