【问题标题】:How to use same backend (django) api cookie to frontend(vuejs)?如何将相同的后端(django)api cookie 用于前端(vuejs)?
【发布时间】:2021-09-01 20:50:02
【问题描述】:

我在处理前端和后端的 cookie 时感到困惑。

我在后端生成了一个 cookie

class JWTAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.COOKIES.get('jwt')

        if not token:
            return None
        try:
            payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
        except jwt.ExpiredSignatureError:
            raise exceptions.AuthenticationFailed('unauthenticated')
        user = get_user_model().objects.filter(id=payload['id']).first()
        if user is None:
            raise exceptions.AuthenticationFailed("Unauthenticated")
        return (user, None)

当我在前端 vuejs 中使用登录时,通过 api 生成一个 cookie,该 cookie 也是由前端添加并标记为 httpOnly 的。 我想使用相同的 cookie 而不在前端创建新的。

在前端当我 console.log document.cookie 生成的 cookie 不可用,虽然它显示 cookie 已生成,但同时在后端当我访问 api 并看到 console.log(document.cookie) 它在那里可用。

我如何在前端通过 vuejs/javascript 通过 document.cookie 访问该 cookie,以便我可以在前端进行身份验证和全局保护。

感谢您的帮助。

【问题讨论】:

    标签: django vue.js cookies jwt


    【解决方案1】:

    我想我已经找到了答案。 为了启用与后端相同的 cookie 到前端,我必须在后端设置 cookie 并将响应设置为 httpOnly False 时查看 views.py。

    response.set_cookie(key='jwt', value=token, httponly=False)
    

    现在,我也可以在前端使用 document.cookie 了。

    【讨论】:

      猜你喜欢
      • 2018-03-19
      • 2018-05-13
      • 2019-09-29
      • 2020-03-05
      • 2020-06-13
      • 2023-03-22
      • 2020-12-05
      • 2022-11-14
      • 1970-01-01
      相关资源
      最近更新 更多