我读到了一些与在本地存储中存储 jwt 令牌相关的问题,这就是我尝试将令牌存储在仅 http cookie 中的原因。我正在使用以下方法。
from rest_framework.views import APIView
from rest_framework.response import Response
import jwt
from django.conf import settings
from rest_framework import status
class LoginView(APIView):
def post(self, request, format=None):
email = request.data['email']
password = request.data['password']
# dummy user authentication
if email == 'email' and password == 'password':
encoded = jwt.encode(
{'email': email}, settings.SECRET_KEY, algorithm='HS256')
response = Response()
response.set_cookie(key='token', value=encoded, httponly=True)
response.data = {
'user': email,
}
return response
else:
return Response({'error': 'wrong credentials'}, status=status.HTTP_401_UNAUTHORIZED)
Run Code Online (Sandbox Code Playgroud)
问题 1:这是使用 django Rest 框架设置 …
python authentication django cookie-httponly django-rest-framework
在以不安全的方式使用djangorestframework-jwt一年后,我终于决定我希望以一种更安全的方式使其工作。
我到处都读到了在本地客户端(例如,本地存储)中保存JWT令牌的方法不好,最好的解决方案是使用HttpOnly cookie。
我知道HttpOnly cookie确实是一个cookie,可以保存但不能被浏览器读取。所以我认为它可以像下面这样使用:
我现在正尝试通过使用HttpOnly cookie来使用djangorestframework-jwt,而JWT_AUTH_COOKIE配置似乎是最合适的配置:
如果除了授权标头之外还想使用http cookie作为令牌的有效传输方式,则可以设置JWT_AUTH_COOKIE字符串。您在此处设置的字符串将用作在请求令牌时将在响应标头中设置的cookie名称。令牌验证过程还将调查此cookie(如果已设置)。如果请求中同时包含标头和cookie,则“授权”标头具有优先权。
默认值为“无”,创建令牌时不设置cookie,或在验证令牌时不接受。
将字符串值赋予JWT_AUTH_COOKIE之后,我收到了预期的httpOnly cookie。
问题:
当我调用refreshToken时,得到以下响应:
{"token":["This field is required."]}
Run Code Online (Sandbox Code Playgroud)
是的,我没有在请求的HEADER中发送任何令牌,这就是我想要的,因为客户端不应该将其保存在任何地方。
这就是我感到困惑的地方:
如果我从现在开始对客户端对服务器的每个请求都没错,则应将cookie添加到请求中。
看到标题中没有传递令牌后,服务器是否应该检查Cookie?如果不是这样,应该如何工作?