Django JWT Token RestfulAPI用户认证详解


Posted in Python onJanuary 23, 2019

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

创建用户项目

python manage.py startapp users

添加项目apps

settings.py

INSTALLED_APPS = [
 ...
 'users.apps.UsersConfig',

]
添加AUTH_USRE_MODEL 替换默认的user
AUTH_USER_MODEL = 'users.UserProfile'

如果说想用全局认证需要在配置文件中添加

# 全局认证from rest_framework.authentication import TokenAuthentication,BasicAuthentication,SessionAuthentication

REST_FRAMEWORK = {
 'DEFAULT_AUTHENTICATION_CLASSES': (
  # 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # 全局认证,开源jwt
  'rest_framework.authentication.BasicAuthentication',
  'rest_framework.authentication.SessionAuthentication',
  # 'rest_framework.authentication.TokenAuthentication', #全局认证drf 自带的

 )
}

编写model

扩展User model

from django.contrib.auth.models import AbstractUser
from django.db import models


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="邮箱")

 class Meta:
  verbose_name = "用户"
  verbose_name_plural = verbose_name

 def __str__(self):
  return self.username

编写serializers.py

from rest_framework import serializers
from users.models import VerifyCode

class VerifyCodeSerializer(serializers.ModelSerializer):
 class Meta:
  model = VerifyCode
  fields = "__all__"

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

views.py测试

from django.shortcuts import render
from rest_framework import mixins, viewsets
from rest_framework.views import APIView
from users.models import VerifyCode

from .serializers import VerifyCodeSerializer
# Create your views here.
from rest_framework.authentication import TokenAuthentication,BasicAuthentication,SessionAuthentication

from rest_framework_jwt.authentication import JSONWebTokenAuthentication
class VerifyCodeListViewSet(mixins.ListModelMixin,mixins.RetrieveModelMixin, viewsets.GenericViewSet):
 """
 验证码列表
 """
 queryset = VerifyCode.objects.all()
 serializer_class = VerifyCodeSerializer
 # authentication_classes = [TokenAuthentication, ]
 # authentication_classes = [JSONWebTokenAuthentication, ]
 # JWT 认证 加密,过期时间
 def get_authenticators(self):
  """
  Instantiates and returns the list of authenticators that this view can use.
  # 修改验证
  """
  # 动态认证
  print(self.authentication_classes)
  print([JSONWebTokenAuthentication, ])
  if self.action_map['get'] == "retrieve":
   self.authentication_classes = [BasicAuthentication,SessionAuthentication,]
  elif self.action_map['get'] == "list":
   self.authentication_classes = [JSONWebTokenAuthentication,]
  return [auth() for auth in self.authentication_classes]

 # DRF 自带的认证 不过期,易发生xss攻击
 # def get_authenticators(self):
 #  """
 #  Instantiates and returns the list of authenticators that this view can use.
 #  # 修改验证
 #  """
 #  print(self.authentication_classes)
 #  print([JSONWebTokenAuthentication, ])
 #  if self.action_map['get'] == "retrieve":
 #   self.authentication_classes = [BasicAuthentication,SessionAuthentication,]
 #  elif self.action_map['get'] == "list":
 #   self.authentication_classes = [JSONWebTokenAuthentication,]
 #  return [auth() for auth in self.authentication_classes]

 def get_queryset(self):

 # 取出认证信息
  print(self.request.auth)
  # print(self.action)
  return self.queryset
 # url

"""untitled URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
 https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
 1. Add an import: from my_app import views
 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
 1. Add an import: from other_app.views import Home
 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
 1. Import the include() function: from django.conf.urls import url, include
 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from rest_framework.authtoken import views
from rest_framework_jwt.views import obtain_jwt_token

from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from users.views import VerifyCodeListViewSet

router = routers.DefaultRouter()
router.register(r'codes', VerifyCodeListViewSet, 'codes')

urlpatterns = [
 url(r'^admin/', admin.site.urls),
 url(r'^api-auth/', include('rest_framework.urls'))

]
urlpatterns += [
 # drf 自带的
 url(r'^api-token-auth/', views.obtain_auth_token),
 # jwt 认证
 url(r'^jwt_auth/', obtain_jwt_token),
]
urlpatterns += router.urls

1. debug模式启动

Django JWT Token RestfulAPI用户认证详解

2. 使用postmain测试

Django JWT Token RestfulAPI用户认证详解

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

Django JWT Token RestfulAPI用户认证详解

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

Django JWT Token RestfulAPI用户认证详解

调试结束后可以看到结果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
pymssql ntext字段调用问题解决方法
Dec 17 Python
详解Django框架中的视图级缓存
Jul 23 Python
详解Python的collections模块中的deque双端队列结构
Jul 07 Python
Python 通过pip安装Django详细介绍
Apr 28 Python
无法使用pip命令安装python第三方库的原因及解决方法
Jun 12 Python
pandas 数据结构之Series的使用方法
Jun 21 Python
Pandas库之DataFrame使用的学习笔记
Jun 21 Python
Python作用域与名字空间原理详解
Mar 21 Python
sklearn和keras的数据切分与交叉验证的实例详解
Jun 19 Python
PyCharm2020.1.1与Python3.7.7的安装教程图文详解
Aug 07 Python
彻底搞懂python 迭代器和生成器
Sep 07 Python
python如何爬取动态网站
Sep 09 Python
python实现QQ邮箱/163邮箱的邮件发送
Jan 22 #Python
python实现年会抽奖程序
Jan 22 #Python
在python中实现强制关闭线程的示例
Jan 22 #Python
Python实现简单石头剪刀布游戏
Jan 20 #Python
python石头剪刀布小游戏(三局两胜制)
Jan 20 #Python
python 对类的成员函数开启线程的方法
Jan 22 #Python
python实现石头剪刀布小游戏
Jan 20 #Python
You might like
PHP对字符串的递增运算分析
2010/08/08 PHP
php curl常见错误:SSL错误、bool(false)
2011/12/28 PHP
PHP的autoload机制的实现解析
2012/09/15 PHP
深入PHP运行环境配置的详解
2013/06/04 PHP
php使用for语句输出三角形的方法
2015/06/09 PHP
用PHP去掉文件头的Unicode签名(BOM)方法
2017/06/22 PHP
PHP自定义错误处理的方法分析
2018/12/19 PHP
js实现的网页颜色代码表全集
2007/07/17 Javascript
一步一步教你写一个jQuery的插件教程(Plugin)
2009/09/03 Javascript
jQuery 学习入门篇附实例代码
2010/03/16 Javascript
JS弹出层遮罩,隐藏背景页面滚动条细节优化分析
2016/04/29 Javascript
js实现div在页面拖动效果
2016/05/04 Javascript
浅析jQuery中使用$所引发的问题
2016/05/29 Javascript
详解用vue.js和laravel实现微信支付
2017/06/23 Javascript
基于vue 动态加载图片src的解决方法
2018/02/05 Javascript
基于node搭建服务器,写接口,调接口,跨域的实例
2018/05/13 Javascript
JavaScript多种图形实现代码实例
2020/06/28 Javascript
JavaScript 实现轮播图特效的示例
2020/11/05 Javascript
Python random模块常用方法
2014/11/03 Python
Python使用cx_Oracle模块将oracle中数据导出到csv文件的方法
2015/05/16 Python
通过Python来使用七牛云存储的方法详解
2015/08/07 Python
Python基础之getpass模块详细介绍
2017/08/10 Python
python 文件操作删除某行的实例
2017/09/04 Python
Python遍历文件夹 处理json文件的方法
2019/01/22 Python
Python_查看sqlite3表结构,查询语句的示例代码
2019/07/17 Python
python实现银行实战系统
2020/02/26 Python
Python3 shelve对象持久存储原理详解
2020/03/23 Python
Python项目跨域问题解决方案
2020/06/22 Python
Keras 在fit_generator训练方式中加入图像random_crop操作
2020/07/03 Python
Python中过滤字符串列表的方法
2020/12/22 Python
CSS3属性box-shadow使用指南
2014/12/09 HTML / CSS
巴西体育用品商店:Lojão dos Esportes
2018/07/21 全球购物
如何用Java判断一个文件或目录是否存在
2012/11/19 面试题
2014年学生会生活部工作总结
2014/11/07 职场文书
2014年企业工会工作总结
2014/11/12 职场文书
一年级数学上册复习计划
2015/01/17 职场文书