zoukankan      html  css  js  c++  java
  • Django JWT Token RestfulAPI用户认证

    一般情况下我们Django默认的用户系统是满足不了我们的需求的,那么我们会对他做一定的扩展

    创建用户项目

    python manage.py startapp users
    

     添加项目apps

     1 INSTALLED_APPS = [
     2     ...
     3     'users.apps.UsersConfig',
     4 
     5 ]
     6 添加AUTH_USRE_MODEL 替换默认的user
     7 AUTH_USER_MODEL = 'users.UserProfile'
     8 
     9 如果说想用全局认证需要在配置文件中添加
    10 
    11 # 全局认证from rest_framework.authentication import TokenAuthentication,BasicAuthentication,SessionAuthentication
    12 
    13 REST_FRAMEWORK = {
    14     'DEFAULT_AUTHENTICATION_CLASSES': (
    15         # 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # 全局认证,开源jwt
    16         'rest_framework.authentication.BasicAuthentication',
    17         'rest_framework.authentication.SessionAuthentication',
    18         # 'rest_framework.authentication.TokenAuthentication', #全局认证drf 自带的
    19 
    20     )
    21 }
    settings.py

    编写model

     1 from django.contrib.auth.models import AbstractUser
     2 from django.db import models
     3 
     4 
     5 class UserProfile(AbstractUser):
     6     """
     7     用户
     8     """
     9     name = models.CharField(max_length=30, null=True, blank=True, verbose_name="姓名")
    10     birthday = models.DateField(null=True, blank=True, verbose_name="出生年月")
    11     gender = models.CharField(max_length=6, choices=(("male", u""), ("female", "")), default="female", verbose_name="性别")
    12     mobile = models.CharField(null=True, blank=True, max_length=11, verbose_name="电话")
    13     email = models.EmailField(max_length=100, null=True, blank=True, verbose_name="邮箱")
    14 
    15     class Meta:
    16         verbose_name = "用户"
    17         verbose_name_plural = verbose_name
    18 
    19     def __str__(self):
    20         return self.username
    扩展User model

    编写serializers.py

    1 from rest_framework import serializers
    2 from users.models import VerifyCode
    3 
    4 class VerifyCodeSerializer(serializers.ModelSerializer):
    5     class Meta:
    6         model = VerifyCode
    7         fields = "__all__"
    serializers.py

     编写views 动态验证不同的请求使用不同的验证

     1 from django.shortcuts import render
     2 from rest_framework import mixins, viewsets
     3 from rest_framework.views import APIView
     4 from users.models import VerifyCode
     5 
     6 from .serializers import VerifyCodeSerializer
     7 # Create your views here.
     8 from rest_framework.authentication import TokenAuthentication,BasicAuthentication,SessionAuthentication
     9 
    10 from rest_framework_jwt.authentication import JSONWebTokenAuthentication
    11 class VerifyCodeListViewSet(mixins.ListModelMixin,mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    12     """
    13     验证码列表
    14     """
    15     queryset = VerifyCode.objects.all()
    16     serializer_class = VerifyCodeSerializer
    17     # authentication_classes = [TokenAuthentication, ]
    18     # authentication_classes = [JSONWebTokenAuthentication, ]
    19     # JWT 认证 加密,过期时间
    20     def get_authenticators(self):
    21         """
    22         Instantiates and returns the list of authenticators that this view can use.
    23         # 修改验证
    24         """
    25         # 动态认证
    26         print(self.authentication_classes)
    27         print([JSONWebTokenAuthentication, ])
    28         if self.action_map['get'] == "retrieve":
    29             self.authentication_classes = [BasicAuthentication,SessionAuthentication,]
    30         elif self.action_map['get'] == "list":
    31             self.authentication_classes = [JSONWebTokenAuthentication,]
    32         return [auth() for auth in self.authentication_classes]
    33 
    34     # DRF 自带的认证 不过期,易发生xss攻击
    35     # def get_authenticators(self):
    36     #     """
    37     #     Instantiates and returns the list of authenticators that this view can use.
    38     #     # 修改验证
    39     #     """
    40     #     print(self.authentication_classes)
    41     #     print([JSONWebTokenAuthentication, ])
    42     #     if self.action_map['get'] == "retrieve":
    43     #         self.authentication_classes = [BasicAuthentication,SessionAuthentication,]
    44     #     elif self.action_map['get'] == "list":
    45     #         self.authentication_classes = [JSONWebTokenAuthentication,]
    46     #     return [auth() for auth in self.authentication_classes]
    47 
    48     def get_queryset(self):
    49      # 取出认证信息
    50         print(self.request.auth)
    51         # print(self.action)
    52         return self.queryset
    53  # url
    54 
    55 """untitled URL Configuration
    56 
    57 The `urlpatterns` list routes URLs to views. For more information please see:
    58     https://docs.djangoproject.com/en/1.10/topics/http/urls/
    59 Examples:
    60 Function views
    61     1. Add an import:  from my_app import views
    62     2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
    63 Class-based views
    64     1. Add an import:  from other_app.views import Home
    65     2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
    66 Including another URLconf
    67     1. Import the include() function: from django.conf.urls import url, include
    68     2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
    69 """
    70 from rest_framework.authtoken import views
    71 from rest_framework_jwt.views import obtain_jwt_token
    72 
    73 from django.conf.urls import url, include
    74 from django.contrib import admin
    75 from rest_framework import routers
    76 from users.views import VerifyCodeListViewSet
    77 
    78 router   = routers.DefaultRouter()
    79 router.register(r'codes', VerifyCodeListViewSet, 'codes')
    80 
    81 urlpatterns = [
    82     url(r'^admin/', admin.site.urls),
    83     url(r'^api-auth/', include('rest_framework.urls'))
    84 
    85 ]
    86 urlpatterns += [
    87     # drf 自带的
    88     url(r'^api-token-auth/', views.obtain_auth_token),
    89     # jwt 认证
    90     url(r'^jwt_auth/', obtain_jwt_token),
    91 ]
    92 urlpatterns += router.urls
    views.py

     测试

    1. debug模式启动

    2. 使用postmain测试

    粘贴jwt token 到header中法功请求获取codes列表数据

    查看request 中的user可以看到用户代表成功request.auth 可以获得token

    调试结束后可以看到结果

  • 相关阅读:
    注册以及密码验证
    轮播图,渐显,可以左右点击
    节点移动
    数据持久化
    Objective-C Autorelease Pool 的实现原理(转)
    iOS应用架构谈 view层的组织和调用方案(转)
    iOS 开源项目
    iOS开发系列--无限循环的图片浏览器
    富文本常用封装(NSAttributedString浅析)(转)
    OS开发UI篇—ios应用数据存储方式(XML属性列表-plist)(转)
  • 原文地址:https://www.cnblogs.com/lize3379/p/8509946.html
Copyright © 2011-2022 走看看