djangorestframework-jwt user authentication token

1. 项目app01
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.

class UserProfile(AbstractUser):
    """
    用户
    """
    name = models.CharField(max_length=30, null=True, blank=True, verbose_name="姓名")
    birthday = models.DateField(null=True, blank=True, verbose_name="出生年月")
    gender = models.CharField(max_length=6, choices=(("male", u"男"), ("female", "女")), default="female",
                              verbose_name="性别")
    mobile = models.CharField(null=True, blank=True, max_length=11, verbose_name="电话")
    email = models.EmailField(max_length=100, null=True, blank=True, verbose_name="邮箱") 
        verbose_name = "user"

    Class Meta:
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username
        
serializers.py 序列化文件
# -*- coding: utf-8 -*-
__author__ = 'hyh'

from django.contrib.auth import get_user_model
from rest_framework import serializers
User = get_user_model()

class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"


2.安装djangorestframework-jwt
pip install djangorestframework-jwt

配置settings文件
添加如下配置
import datetime
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        #'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # 全局设置
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
}
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
    'JWT_AUTH_HEADER_PREFIX': 'JWT',
}
AUTH_USER_MODEL = 'app01.UserProfile' # 自定义用户表
AUTHENTICATION_BACKENDS = (
     # 将backends添加进setting
     'app01.views.CustomBackend',
)

view.py
from django.shortcuts import render
from django.contrib.auth.backends import ModelBackend
from rest_framework import viewsets
from rest_framework import mixins
from rest_framework import authentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.serializers import jwt_encode_handler, jwt_payload_handler
from django.contrib.auth import get_user_model
from .serializers import UserProfileSerializer
from django.db.models import Q
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import UserProfile
from django.http import JsonResponse
from rest_framework.permissions import IsAuthenticated
from rest_framework import permissions
from app01.utils.permissions import IsOwnerOrReadOnly
# Create your views here.

User = get_user_model()


class CustomBackend(ModelBackend):
    """
    自定义用户验证
    """
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username)|Q(mobile=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


class UserViewset(mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin,mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = UserProfileSerializer
    queryset = UserProfile.objects.all()
    #permission_classes = (IsAuthenticated, IsOwnerOrReadOnly) # 权限和认证必须同时使用,否则认证不生效
    authentication_classes = (JSONWebTokenAuthentication,authentication.SessionAuthentication)

    def get_serializer_class(self):
        if self.action == "retrieve":
            return UserProfileSerializer
        elif self.action == "create":
            return UserProfileSerializer

        return UserProfileSerializer

    # permission_classes = (permissions.IsAuthenticated, )
    def get_permissions(self):
        if self.action == "retrieve":
            return [permissions.IsAuthenticated()]
        elif self.action == "create":
            return []

        return []

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)

        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict["token"] = jwt_encode_handler(payload)
        re_dict["name"] = user.name if user.name else user.username

        headers = self.get_success_headers(serializer.data)
        return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)

    def get_object(self):
        return self.request.user

    def perform_create(self, serializer):
        return serializer.save()


class Index(APIView):
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication,)
    def get(self,request):
        return JsonResponse({"index":"ok"})
            
 3.urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include
from rest_framework.routers import SimpleRouter,DefaultRouter
from rest_framework.documentation import include_docs_urls
from app01.views import UserViewset,Index
from rest_framework_jwt.views import obtain_jwt_token
router = SimpleRouter()
router.register('user',UserViewset,base_name='useruinfo') 
Urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'docs/', include_docs_urls(title="user信息")),
    url(r'^login/',obtain_jwt_token),
    url(r'^index/',Index.as_view()),
]

urlpatterns += router.urls
        
        
 4. 在app01下创建utils目录,存放permissions.py文件
 permissions.py文件内容
 # -*- coding: utf-8 -*-
__author__ = 'hyh'
from rest_framework import permissions


class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    Object-level permission to only allow owners of an object to edit it.
    Assumes the model instance has an `owner` attribute.
    """

    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.
        if request.method in permissions.SAFE_METHODS:
            return True

        # Instance must have an attribute named `owner`.
        return obj.user == request.user
 4.测试
 获取token

image.png


Copy the token

image.png


Return result success

Guess you like

Origin blog.51cto.com/haoyonghui/2425999