【问题标题】:python saving jwt token in SimpleCookiepython在SimpleCookie中保存jwt令牌
【发布时间】:2020-12-25 16:35:18
【问题描述】:

我的目标是创建一个 cookie 来存储 jwt 的 id 令牌并将其传递回客户端。此逻辑在 aws lambda 中运行:

def lambda_handler(event, context):
.....
.....
cookie_name="my_cookie"
cookie = gen_cookie(domain, expiration, cookie_name,jwt):
return {"statusCode": 302,
        "headers": {
            "Location": "different-url/logged-in",
            "Set-Cookie": cookie}
        }

def gen_cookie(domain, expiration, cookie_name,jwt):
    cookie = SimpleCookie()
    cookie[cookie_name] = "test"
    cookie[cookie_name]['httponly'] = "yes"
    cookie[cookie_name]['domain'] = domain
    cookie[cookie_name]['expires'] = expiration
    cookie[cookie_name]['path'] = "/"
    cookie[cookie_name]['id_token'] = jwt['id_token']
    print(cookie)
    return cookie

我收到一个异常,即 id_token 不是有效属性。

[ERROR] CookieError: Invalid attribute 'id_token'
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 41, in lambda_handler
    cookie[cookie_name]['id_token'] = response_content_dict['id_token']
  File "/var/lang/lib/python3.7/http/cookies.py", line 311, in __setitem__
    raise CookieError("Invalid attribute %r" % (K,))

我检查了一下,simpleCookie 中唯一有效的值是:

  _reserved = {
        "expires"  : "expires",
        "path"     : "Path",
        "comment"  : "Comment",
        "domain"   : "Domain",
        "max-age"  : "Max-Age",
        "secure"   : "Secure",
        "httponly" : "HttpOnly",
        "version"  : "Version",
    }

所以我的问题是,如何创建一个包含 jwt 的 cookie 并将其返回给客户端?

【问题讨论】:

    标签: python amazon-web-services cookies jwt


    【解决方案1】:

    我通过以下方式将 jwt 保存在 cookie 中:

    def gen_cookie(domain, expiration, cookie_name,jwt):
        cookie = SimpleCookie()
        cookie[cookie_name] = jwt['id_token']
        cookie[cookie_name]['httponly'] = "yes"
        cookie[cookie_name]['domain'] = domain
        cookie[cookie_name]['expires'] = expiration
        cookie[cookie_name]['path'] = "/"
        print(cookie)
        return cookie
    

    注意cookie的值是jwt的token。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 2018-11-12
      • 1970-01-01
      • 2019-02-01
      • 2020-05-17
      • 2015-09-15
      相关资源
      最近更新 更多