如何使用相同的后端(django)api cookie 到前端(vuejs)?
How to use same backend (django) api cookie to frontend(vuejs)?
我在前端和后端处理 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 而无需在前端创建新的 cookie。
在前端当我 console.log document.cookie
生成的 cookie 不可用,虽然它显示生成的 cookie,但同时在后端当我访问 api 并看到 console.log(document.cookie)
那里有。
即使在前端,我如何通过 vuejs/javascript 通过 document.cookie
访问该 cookie,以便我可以在前端进行身份验证和全局保护。
感谢您的帮助。
我想我找到了答案。
为了启用与后端到前端相同的 cookie,我必须在后端设置 cookie 时查看 views.py 并将响应设置为 httpOnly False。
response.set_cookie(key='jwt', value=token, httponly=False)
现在,我也可以在前端使用 document.cookie。
我在前端和后端处理 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 而无需在前端创建新的 cookie。
在前端当我 console.log document.cookie
生成的 cookie 不可用,虽然它显示生成的 cookie,但同时在后端当我访问 api 并看到 console.log(document.cookie)
那里有。
即使在前端,我如何通过 vuejs/javascript 通过 document.cookie
访问该 cookie,以便我可以在前端进行身份验证和全局保护。
感谢您的帮助。
我想我找到了答案。 为了启用与后端到前端相同的 cookie,我必须在后端设置 cookie 时查看 views.py 并将响应设置为 httpOnly False。
response.set_cookie(key='jwt', value=token, httponly=False)
现在,我也可以在前端使用 document.cookie。