简体   繁体   English

Django RESTful Framework如何从HTTP标头中的令牌获取用户模型?

[英]How does Django RESTful Framework get user model from token from HTTP header?

I'm building my Django RESTful Framework to retrieve and post data for Mobile. 我正在构建Django RESTful框架来检索和发布Mobile数据。 I'm using Django-rest-auth (which is just all-auth with RESTful functionality; more info : http://django-rest-auth.readthedocs.io/en/latest/ ). 我正在使用Django-rest-auth(这是具有RESTful功能的全部认证;更多信息: http : //django-rest-auth.readthedocs.io/en/latest/ )。

How does Django RESTful Framework (or Django) finds user's model when mobile sends user's token in HTTP header? 当移动设备在HTTP标头中发送用户令牌时,Django RESTful Framework(或Django)如何查找用户模型?

For instance: 例如:

HTTP METHOD: POST
headers : Authorization eyl3of9iskjfpjowpefjsopeff (This is token and random string) 
body : {
    post_title: "This is my first post"
    post_content: "This is the content" 
}

This is my setting: 这是我的设置:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
        # 'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

This is where I want to find a user model : 这是我要查找用户模型的地方:

class CreatePost(generics.CreateAPIView):
    def get_queryset(self, **kwargs):
        owner = User.objects.filter(user= ##) # right here!
        post_title =
        post_content = 

Or any other approach suggested? 还是建议其他方法?

Usually, your Token is simply a Django model , which is stored in your database. 通常, Token只是一个Django模型 ,它存储在数据库中。

It has a OneToOne relation to your User model and that's simply how they are related (in rest_framework.authtoken ). 它与您的User模型具有OneToOne关系,而这正是它们之间的关系(在rest_framework.authtoken )。 You can see it in DRF source . 您可以在DRF源中看到它。

A direct examle: 直接示例:

from rest_framework import generics
from rest_framework import status
from rest_framework.authtoken.models import Token
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# You can directly import your Token model for usage

from .serializers import UserLoginSerializer


class UserLogin(generics.CreateAPIView):
    serializer_class = UserLoginSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        user = serializer.validated_data['user']
        token, _ = Token.objects.get_or_create(user=user)
        # Here you either get a Token if it exists in your db
        # Or generate it if it is not created yet

        # See that you directly get the token with your user:
        # Token.objects.get_or_create(user=user)

        # You can also access it vice-versa: token.user <-> user.token
        # Because it is a OneToOne relation

        response_data = {
            'id': user.id,
            'token': token.key
        }

        headers = self.get_success_headers(serializer.data)

        return Response(response_data, status=status.HTTP_200_OK, headers=headers)

Note : If you are using JWT , have a look at how a token is linked with the user . 注意 :如果使用的是JWT ,请查看令牌与用户的链接方式

In your case: 在您的情况下:

class CreatePost(generics.CreateAPIView):
    def get_queryset(self, **kwargs):
        owner = self.request.user
        # Are you sure you don't want to get the current request user?
        # Why you should filter with token?

        post_title = ...
        post_content = ...

Your authentication classes (in your case, JSONWebTokenAuthentication , it automatically sets request.user to the correct one and you can access it in your views). 身份验证类(在您的情况下为JSONWebTokenAuthentication ,它将自动将request.user设置为正确的类,您可以在视图中访问它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM