生成Flask中使用的签名会话cookie值 [英] Generating signed session cookie value used in Flask

查看:86
本文介绍了生成Flask中使用的签名会话cookie值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Flask服务器与另一个需要向会话中注入项目的Flask服务器进行代理。

I'm proxying a Flask server with another Flask server that needs to inject items into the session.

这两个服务器都具有相同的密钥,因此加密签名将是相同的。使用Flask和会话时,http响应包含带有 session = text 的Set-Cookie标头,其中text是使用您签名的会话对象的编码JSON字符串

Both servers have the same secret key so the cryptographic signature will be the same. When using Flask and a session, the http response contains a Set-Cookie header with session=text, where text is an encoded JSON string of your session object that is signed using you secret key.

从本质上讲,我需要能够重新创建此字符串,但是我找不到这样做的接口。

Essentially, I need to be able to re-create this string, but I can't find the interface to do so.

推荐答案

我找到烧瓶如何在源代码中完成。我很着急,所以没有时间更好地解释。

I ended up solving my own issue after finding how flask does this in the source. I was in a hurry at work so did not have time to better explain.

from flask import Flask, session
from flask.sessions import SecureCookieSessionInterface

app = Flask("example")
app.secret_key = "Tom Izzo 4 President"

# 1. this is what I was looking for
session_serializer = SecureCookieSessionInterface() \
                         .get_signing_serializer(app)

app.route("/")
def test():
    session["lst"] = ["a", "b", "c", "d"]

    # 2. and this is how I needed to use it
    session_cookie = session_serializer.dumps(dict(session))

变量 session_cookie上面的是使用给定secret_key的会话的有效cookie值。这样,我就可以将请求转发到另一个使用secret_key的烧瓶服务器。

The variable session_cookie above is a valid cookie value for a session using the given secret_key. With this I am able to forward a request to another flask server that uses the secret_key.

这篇关于生成Flask中使用的签名会话cookie值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆