django-rest-knox饼干 [英] django-rest-knox with cookies

查看:75
本文介绍了django-rest-knox饼干的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用django-rest-knox进行身份验证有疑问。
我想使用cookie存储,而不是客户端上的localStorage。所以我要像下面这样实现

I have a question about authentication using django-rest-knox. I want to use cookie storage, not localStorage on client side. So I'm going to implement like below


class LoginView(GenericAPIView):
    serializer_class = LoginSerializer
    permission_classes = (AllowAny,)

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data
        token = AuthToken.objects.create(user)
        response = Response({
            'user': UserSerializer(user, context=self.get_serializer_context()).data,
            'token': token
        })
        response.set_cookie('token',
                            token,
                            httponly=True)
        return response

使用django-休息诺克斯?还是我需要使用localStorage?我不想使用JWT,因为在这里看到了很多负面意见。

Is it correct way to use django-rest-knox? or Do I need to use localStorage? I don't want to use JWT because I saw many negative opinions here.

推荐答案

首先,感谢您发布此问题。我有一个类似的要求,即不使用本地存储,并且您的工作将被指向正确的方向。

First, thanks for posting this question. I had a similar requirement to not use local storage, and your work got be pointed in the right direction.

看看Knox的 LoginView 实现(此处),似乎您的版本中有很多逻辑未复制(例如,令牌计数限制)。

Looking at Knox's LoginView implementation (here), it looks like there's a fair amount of logic that isn't replicated in your version (e.g., token count limits).

我采用了扩展了Knox的 LoginView 。我调用默认的 post 方法以使用Knox的实现,然后删除我不想在客户端上的JS上获取的信息。

I took the approach of extending Knox's LoginView. I call the default post method to use Knox's implementation, then strip out the information I don't want to be made available to JS on the client.

from django.contrib.auth import login
from rest_framework import permissions
from rest_framework.authtoken.serializers import AuthTokenSerializer
from knox.views import LoginView as KnoxLoginView


class LoginView(KnoxLoginView):
    permission_classes = (permissions.AllowAny,)

    def post(self, request, format=None):
        serializer = AuthTokenSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        login(request, user)
        response = super(LoginView, self).post(request, format=None)

        token = response.data['token']
        del response.data['token']

        response.set_cookie(
            'auth_token',
            token,
            httponly=True,
            samesite='strict'
        )

        return response

这篇关于django-rest-knox饼干的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆