【发布时间】: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,以便我可以在前端进行身份验证和全局保护。
感谢您的帮助。
【问题讨论】: