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 相关文章推荐
shelve  用来持久化任意的Python对象实例代码
Oct 12 Python
python 通过xml获取测试节点和属性的实例
Mar 31 Python
python 字典中取值的两种方法小结
Aug 02 Python
python3 中文乱码与默认编码格式设定方法
Oct 31 Python
对pandas的算术运算和数据对齐实例详解
Dec 22 Python
PyTorch基本数据类型(一)
May 22 Python
PyQt5图形界面播放音乐的实例
Jun 17 Python
python可视化爬虫界面之天气查询
Jul 03 Python
python3中eval函数用法使用简介
Aug 02 Python
python 匿名函数与三元运算学习笔记
Oct 23 Python
详解Python Celery和RabbitMQ实战教程
Jan 20 Python
浅谈Python数学建模之整数规划
Jun 23 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
人族 Terran 魔法与科技
2020/03/14 星际争霸
PHP的AES加密算法完整实例
2016/07/20 PHP
php中青蛙跳台阶的问题解决方法
2018/10/14 PHP
模拟用户操作Input元素,不会触发相应事件
2007/05/11 Javascript
JavaScript入门学习书籍推荐
2008/06/12 Javascript
javascript 出生日期和身份证判断大全
2008/11/13 Javascript
输入密码检测大写是否锁定js实现代码
2012/12/03 Javascript
关于javaScript注册click事件传递参数的不成功问题
2014/07/18 Javascript
jquery.fastLiveFilter.js实现输入自动过滤的方法
2015/08/11 Javascript
基于jQuery实现淡入淡出效果轮播图
2020/07/31 Javascript
Vue过滤器的用法和自定义过滤器使用
2017/02/08 Javascript
Angular 4依赖注入学习教程之FactoryProvider配置依赖对象(五)
2017/06/04 Javascript
js replace替换字符串同时替换多个方法
2018/11/27 Javascript
通过JavaScript下载文件到本地的方法(单文件)
2019/03/17 Javascript
基于JavaScript实现表格隔行换色
2020/05/08 Javascript
jQuery实现查看图片功能
2020/12/01 jQuery
[02:00]最后,我终于出了辉耀
2018/03/27 DOTA
Python运行报错UnicodeDecodeError的解决方法
2016/06/07 Python
python批量实现Word文件转换为PDF文件
2018/03/15 Python
在CMD命令行中运行python脚本的方法
2018/05/12 Python
Python PyInstaller库基本使用方法分析
2019/12/12 Python
翻转数列python实现,求前n项和,并能输出整个数列的案例
2020/05/03 Python
Jupyter notebook如何修改平台字体
2020/05/13 Python
自我介绍演讲稿
2014/01/15 职场文书
年度考核自我评价
2014/01/25 职场文书
《会变的花树叶》教学反思
2014/02/10 职场文书
党员创先争优承诺书
2014/03/26 职场文书
2014银行领导班子群众路线对照检查材料思想汇报
2014/09/17 职场文书
征用土地赔偿协议书
2014/09/26 职场文书
2014年保卫工作总结
2014/12/05 职场文书
代理词怎么写
2015/05/25 职场文书
十七岁的单车观后感
2015/06/12 职场文书
学习师德师风的心得体会(2篇)
2019/10/08 职场文书
浅谈Python数学建模之线性规划
2021/06/23 Python
MySQL 如何限制一张表的记录数
2021/09/14 MySQL
Java工作中实用的代码优化技巧分享
2022/04/21 Java/Android