Abh*_*mar 6 python authentication django cookie-httponly django-rest-framework
我读到了一些与在本地存储中存储 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 框架设置 httponly cookie 的正确方法吗?
response = Response()
response.set_cookie(key='token', value=encoded, httponly=True)
response.data = {
'user': email,
}
return response
Run Code Online (Sandbox Code Playgroud)
此后,每次当我收到客户端的请求(使用 React 和 axios)时,我都可以request.COOKIES['token']在 django 视图中访问 cookie。使用这个我可以编写自己的身份验证函数,但我不认为这是一个完美的方法,因为通常,我们在授权标头中传递令牌,该标头根据request.user令牌设置,如果我使用这种方法,我将无法使用用于测试的邮递员和 django 休息框架IsAuthenticated类也寻找request.user and request.user.is_authenticated真正的价值。
问题 2:如果令牌存储在 httponly cookie 中,如何将令牌作为授权标头从客户端传递?
请帮我。我对纯 http cookie 的工作流程有点困惑,因为通常我习惯将令牌存储在本地存储中,并且更容易检索令牌并从前端传递它。
答案1:
是的,这是设置httponly标志 cookie 的好方法,因为
httpOnlycookie 无法被JavaScript. 如果没有httponly标记 cookie,它很容易受到CSRF攻击。
虽然localStorage可通过javascript(与 cookie 相对HttpOnly)访问,但使其容易受到XSS攻击。所以我认为即使在 TokenAuthentication 中使用httponly cookies+CSRF也是最安全的方式来在客户端存储令牌。DRF然而,我看过的其他流行库并没有很好地支持这一点。
答案2:
不可以,因为你无法从客户端httponly使用cookie来检索cookie。这是cookie的一大优势。所以这个cookie只能通过请求访问。确保双方都适用。javascripthttponlyhttp(s)withCredentialsTrue
我个人使用djangorestframework-simplejwt包在cookie中设置(access token+CSRF令牌)httponly并通过使用CustomAuthentication类来获取。 检查这个
| 归档时间: |
|
| 查看次数: |
3722 次 |
| 最近记录: |