如何在注册时使django-rest-framework-jwt返回令牌? [英] How can i make django-rest-framework-jwt return token on registration?

查看:291
本文介绍了如何在注册时使django-rest-framework-jwt返回令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的django rest服务,

I have a basic django rest service, which

  1. 注册一个人并
  2. 更新他的密码.

我想在其顶部添加jwt身份验证.如果我按照教程进行操作,则需要在项目的urls.py中添加一个名为"api-token-auth"的新URL.但是,我不想添加这个新的URL,也不想让我的注册调用发送令牌作为响应.

I want to add jwt authentication on top of it. If I follow the tutorial I would need to add a new url named "api-token-auth" in project's urls.py. But, I don't want to add this new url and want my register call to send a token in response.

这是我的代码:

serializers.py

serializers.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
    def create(self, validated_data):
        user = User(
            username=validated_data['username']
        )
        user.set_password(validated_data['password'])
        user.save()
        return user

    def update(self, instance, validated_data):
        instance.set_password(validated_data['password'])
        instance.save()
        return instance

    class Meta:
        model = User
        fields = ('url', 'username', 'password')
        lookup_field = 'username'
        write_only_fields = ('password',)

views.py

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.exclude(is_superuser=1)
    serializer_class = UserSerializer
    lookup_field = 'username'

  1. 应该怎么做才能做到这一点?我应该在序列化程序的create方法中调用api-auth-token吗?
  2. django-rest-framework-jwt如何处理多个身份验证令牌并正确识别哪个令牌属于哪个用户?尤其是当它不在数据库中存储令牌时.
  3. 如何使用这种身份验证机制来限制我的用户仅查看/更新/删除其用户?
  4. 我一般如何使用此身份验证机制来执行任何操作.例如,如果用户想将他的名字写到/tmp/abcd.txt.如何确保只有经过身份验证的用户才能这样做?
  5. 这种方法是否存在潜在的漏洞.如果我的应用程序要存储大量机密数据,我应该使用相同的代码吗?

推荐答案

问题1:要创建可与django-rest-framework-jwt一起使用的令牌,可以使用如下函数:

Question 1: To create a token that would work with django-rest-framework-jwt you can use a function that looks like:

import jwt
from rest_framework_jwt.utils import jwt_payload_handler

def create_token(user):
    payload = jwt_payload_handler(user)
    token = jwt.encode(payload, settings.SECRET_KEY)
    return token.decode('unicode_escape')

您可以将该功能添加到视图中,并在注册用户后创建令牌.

you can add this function to the view and create the token once the user has been registered.

问题2:不需要将JWT令牌存储在数据库中,您可以在 http://上了解有关JWT的工作原理的信息. jwt.io/

Question 2: JWT tokens do not need to be stored int the database you can read me about how JWT works at http://jwt.io/

问题3和问题4:要使用令牌来限制对特定视图(尤其是APIView或其子类之一)或Django Rest框架提供的视图的访问,您需要指定

Question 3 and 4: To use tokens to limit access to a specific view especially an APIView or one of its subclasses or a view provided by Django Rest framework you need to specify the permission classes for example

from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

class ExampleView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, format=None):
        content = {
            'status': 'request was permitted'
        }
        return Response(content)

问题5:使用Django Rest Framework时可能出现的漏洞是您从应用程序设置中设置的默认权限,例如,如果您在设置中允许allowAll,则它将使所有视图均可公开访问,除非您专门重写了权限类别.

Question 5: One potential loop holes while working with Django Rest Framework is the default permissions that you setup from the settings of your application , if for example you allowAll in the settings it make all the views publicly accessible unless you specifically override the permission classes.

这篇关于如何在注册时使django-rest-framework-jwt返回令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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