首页 > 解决方案 > 使用 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)
    })
},

奇怪的是它似乎存在于响应标头中:

在此处输入图像描述

虽然在其他类似的帖子中,问题是“如何”,但这里是“为什么它不起作用?”

在此先感谢您的帮助。

标签: djangodjango-rest-frameworksetcookie

解决方案


推荐阅读