django - 使用 Django Rest Framework TokenAuthentication 将令牌存储在 cookie 中
问题描述
我正在准备我的应用程序的身份验证(使用 TokenAuthentication)过程,出于安全目的,我想将令牌存储到 HttpOnly cookie 中。
为此,我创建了自己的视图来获取令牌。实际上,我正在覆盖默认值rest_framework.authtoken.views.ObtainAuthToken
,如下所示:
from django.conf import settings
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.response import Response
class ObtainCookieAuthToken(ObtainAuthToken):
"""
Override default ObtainAuthToken view from rest_framework to set the token into a
HttpOnly cookie.
The 'secure' option will depend on the settings.DEBUG value.
"""
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
response = Response({
'user': "user is %s" % user.full_name,
'other': "some other info here"
})
response.set_cookie(
"auth-token",
token,
httponly=True,
secure=settings.DEBUG,
)
return response
在我的网址中:
from django.urls import include, path, re_path
from .base.authentication.obtain_cookie_auth_token import ObtainCookieAuthToken
urlpatterns = [
# ...
path('api/api-token-auth/', ObtainCookieAuthToken.as_view()),
# ...
]
之后,在将覆盖默认值的自定义类中,rest_framework.authentication.TokenAuthentication
我将检查该 cookie 以从中检索令牌。
ObtainCookieAuthToken
问题是在 my被有效调用时没有创建 cookie 。我错过了什么吗?我不明白为什么不创建cookie...我认为set_cookie
这样response
做可以解决问题。
顺便说一句,这是我如何调用这个 APi 端点,我的login()
方法来自我的 Vuejs 前端:
login () {
this.axios
.post('api-token-auth/', {
username: this.form.username || this.lastLoggedInUser.username,
password: this.form.password
})
.then(response => {
this.$router.push({ name: 'Home' })
})
.catch(error => {
console.log("error : ", error)
})
},
奇怪的是它似乎存在于响应标头中:
虽然在其他类似的帖子中,问题是“如何”,但这里是“为什么它不起作用?”
在此先感谢您的帮助。
解决方案
推荐阅读
- laravel - 上传文件后如何设置路径下载到我的电脑
- kubernetes - CSI 驱动程序的 ClusterRole
- c# - 如何使用 DateTime 向 Microsoft SQL Server 发送查询?
- python - 什么是 pymongo 中的等效查询,并给出语法错误
- paypal - 连接沙盒账户 Paypal 时的错误
- c# - 列表中的每个项目组合
- excel - 如何从 SAP GUI Grid View 复制值并粘贴到 Excel
- flutter - 防止用户点击“。” 在颤动的文本字段中已经存在小数点后,在数字键盘中
- python - 从存储桶复制到另一个存储桶时,Amazon S3 是否会检查完整性?
- azure-data-factory-2 - 无法使用 Azure Datafactory 读取 xml 标签