通常狀況下咱們Django默認的用戶系統是知足不了咱們的需求的,那麼咱們會對他作必定的擴展python
python manage.py startapp users
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 }
編寫modeldjango
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
編寫serializers.pyapi
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__"
編寫views 動態驗證不一樣的請求使用不一樣的驗證bash
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
1. debug模式啓動app
2. 使用postmain測試xss
粘貼jwt token 到header中法功請求獲取codes列表數據ide
查看request 中的user能夠看到用戶表明成功request.auth 能夠得到tokenpost
調試結束後能夠看到結果測試