美文网首页
Django REST framework 的JWT Token

Django REST framework 的JWT Token

作者: whong736 | 来源:发表于2019-01-11 23:07 被阅读91次

    接口需求:用户登录成功后,返回Django REST framework 的JWT Token, Token不存储敏感信息,只有用户名,前端请求拦截中向后台发送token 返回用户的信息,前端通过读取用户信息中的角色来显示对应的值。

    JS 前端API

    export function getInfo(token) {
      return request({
        url: '/user/info',
        method: 'get',
        params: { token }
      })
    }
    

    要求后端返回的数据

    {
        "data": {
            "id": 4,
            "username": "test1",
            "name": null,
            "role": "员工",
            "avatar": "https://upload.jianshu.io/users/upload_avatars/7294431/fc4cbf7e-d772-45d3-b909-0588a50ecc49.jpg"
        },
        "code": 20000,
        "message": "请求成功"
    }
    

    思路:发送token,获取token,解码token,查询用户信息,返回数据

    1.Model设计,扩展Django自带的用户字段

    
    from django.db import models
    #引入系统用户的分类
    from django.contrib.auth.models import AbstractUser
    
    # Create your models here.
    
    #userProfile继承AbstractUser分类,进行拓展
    class UserProfile(AbstractUser):
        """
        用户类拓展
        """
        name = models.CharField(max_length=30, null=True, blank=True, verbose_name="姓名" )
        avatar = models.CharField(max_length=100, null=True, blank=True, verbose_name="头像")
        role = models.CharField(max_length=10, default="员工", verbose_name="角色")
    
    
        class Meta:
            verbose_name = "用户"
            verbose_name_plural = verbose_name
    
        def __str__(self):
            return self.username
    
    
    

    2.setting设置

    #将拓展的User替换系统默认的auth_user 模型
    AUTH_USER_MODEL = "users.UserProfile"
    
    image.png

    3.运行,然后信息用户

    makemigrations
    migrate
    

    4.编写序列化文件serializers,新建serializers.py

    
    # -*- coding: UTF-8 -*-
    from django.contrib.auth import get_user_model
    
    from rest_framework import serializers
    
    from rest_framework.validators import UniqueValidator
    
    
    User = get_user_model()
    
    class UserRegisterSerializer(serializers.ModelSerializer):
        # 利用drf中的validators验证username是否唯一
        username = serializers.CharField(required=True, allow_blank=False, validators=[UniqueValidator(queryset=User.objects.all(),
                                                                                            message='用户已经存在')])
        print(username)
        password = serializers.CharField(
             style={"input_type": "password"},help_text="密码", label="密码", write_only=True,
         )
        print(password, "password")
    
        def create(self, validated_data):
             user = super(UserRegisterSerializer, self).create(validated_data= validated_data)
             user.set_password(validated_data["password"])
             user.save()
             return user
        class Meta:
             model = User
             fields = ( "username", "password", "role", "avatar")
    
    
    
    class UserDetailSerializer(serializers.ModelSerializer):
        """
        用户详情序列表类
        """
        class Meta:
            model = User
            fields = ("id", "username", "name", "role", "avatar")
    
    image.png

    5.View编写

    from django.http import HttpResponse,JsonResponse
    from rest_framework_jwt.utils import jwt_decode_handler
    from django.contrib.auth import get_user_model
    from users.serializers import UserDetailSerializer
    
    def get_user_info(request):
    
        User = get_user_model()
        if request.method=='GET':
            #获取请求参数token的值
            token=request.GET.get('token')
            #顶一个空数组来接收token解析后的值
            toke_user = []
            toke_user = jwt_decode_handler(token)
            #获得user_id
            user_id = toke_user["user_id"]
            #通过user_id查询用户信息
            user_info = User.objects.get(pk= user_id)
            serializer = UserDetailSerializer(user_info)
            data = {
    
                "data": serializer.data,
                "code": 20000,
                "message": "请求成功"
            }
    
            return JsonResponse(data)
    
    image.png

    URL配置

    from django.conf.urls import url, include
    from apps import users
    from django.contrib import admin
    from django.urls import path, re_path
    from rest_framework_jwt.views import obtain_jwt_token
    from apps.users.views import UserViewset
    from rest_framework.routers import DefaultRouter
    from rest_framework.documentation import include_docs_urls
    from rest_framework_swagger.views import get_swagger_view
    from users import views
    from users import base_views
    
    router = DefaultRouter()
    router.register(r'api/users', UserViewset, base_name="users")
    schema_view = get_swagger_view(title='ShopVue API文档 ')
    
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('api/user/login', obtain_jwt_token),
        url(r'^', include(router.urls)),
        path('apidoc/', schema_view),
        path('docs/', include_docs_urls(title='ShopVue 文档')),
        re_path('api/user/info/$', base_views.get_user_info),
    ]
    
    
    Postman请求结果

    相关文章

      网友评论

          本文标题:Django REST framework 的JWT Token

          本文链接:https://www.haomeiwen.com/subject/dgbxdqtx.html