Django JWT Token RestfulAPI用户认证
一般情况下我们Django默认的用户系统是满足不了我们的需求的,那么我们会对他做一定的扩展
创建用户项目
python manage.py startapp users
添加项目apps
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 自带的 )
}
settings.py
编写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
扩展User model
编写serializers.py
from rest_framework import serializers
from users.models import VerifyCode class VerifyCodeSerializer(serializers.ModelSerializer):
class Meta:
model = VerifyCode
fields = "__all__"
serializers.py
编写views 动态验证不同的请求使用不同的验证
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
views.py
测试
1. debug模式启动

2. 使用postmain测试

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

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

调试结束后可以看到结果
Django JWT Token RestfulAPI用户认证的更多相关文章
- (30)auth模块(django自带的用户认证模块)
Auth模块是Django自带的用户认证模块: 我们在开发一个网站的时候,无可避免的需要设计实现网站的用户系统.此时我们需要实现包括用户注册.用户登录.用户认证.注销.修改密码等功能,这还真是个麻烦的 ...
- Django之auth模块用户认证模块
一.Auth模块 1)auth模块是什么.登录后台使用的账号密码,则就是使用的auth模块创建的表 Auth模块是Django自带的用户认证模块: 我们在开发一个网站的时候,无可避免的需要设计实现网站 ...
- Django自带的用户认证
1. 创建超级用户 python manage.py createsuperuser 2. 认证 校验用户名和密码 obj = auth.authenticate(request,user ...
- Django框架 之 Auth用户认证
Django框架 之 Auth用户认证 浏览目录 auth模块 user对象 一.auth模块 1 from django.contrib import auth django.contrib.aut ...
- 5分钟搞懂:基于token的用户认证
https://www.qikegu.com/easy-understanding/880 用户认证 用户认证或者说用户登录是确认某人确实是某人的过程,生活中靠身份证,网络上就要靠账号和密码.用户提供 ...
- 6月29日学习总结 Django自带的用户认证
Django自带的用户认证 我们在开发一个网站的时候,无可避免的要设计.实现网站的用户系统.此时我们需要实现包括但不限于用户注册.用户登录.用户认证.注销.修改密码等功能,这还真是个麻烦的事情呢. D ...
- 基于JWT标准的用户认证接口实现
前面的话 实现用户登录认证的方式常见的有两种:一种是基于 cookie 的认证,另外一种是基于 token 的认证 .本文以基于cookie的认证为参照,详细介绍JWT标准,并实现基于该标签的用户认证 ...
- JWT token 跨域认证
JSON Web Token(缩写 JWT),是目前最流行的跨域认证解决方案. session登录认证方案:用户从客户端传递用户名.密码等信息,服务端认证后将信息存储在session中,将sessio ...
- Django内置的用户认证
认证登陆 在进行用户登陆验证的时候,如果是自己写代码,就必须要先查询数据库,看用户输入的用户名是否存在于数据库中: 如果用户存在于数据库中,然后再验证用户输入的密码,这样一来就要自己编写大量的代码. ...
随机推荐
- Curl实现ElasticSearch的增删改查
一.添加数据(laravel必须安装Curl扩展) $data = [ 'username'=>"张三", 'sex'=>"女", 'age'=&g ...
- C# 3.0 / C# 3.5 对象集合初始化器、匿名类
对象集合初始化器 在 .NET 2.0 中构造一个对象的方法一是提供一个重载的构造函数,二是用默认的构造函数生成一个对象,然后对其属性进行赋值. 在 .NET 3.5/C# 3.0 中,我们有一种更好 ...
- javascript高级程序设计第3版——第8章 BOM(浏览器对象模型)
第八章,浏览器对象模型 主要介绍了window的几个对象以及框架,窗口的关系,各个浏览器对象的属性以及方法:
- centos 7安装myslq
# wget http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm # rpm -ivh mysql-community- ...
- php使用gearman进行任务分发
一.安装gearman 下载gearman源码包 1 https://launchpad.net/gearmand/+download 如: gearmand-1.1.12.tar.gz 下载php的 ...
- 二叉树的简单操作(Binary Tree)
树形结构应该是贯穿整个数据结构的一个比较重要的一种结构,它的重要性不言而喻! 讲到树!一般都是讨论二叉树,而关于二叉树的定义以及概念这里不做陈诉,可自行搜索. 在C语言里面需要实现一个二叉树,我们需要 ...
- csla框架__使用Factory方式实现Csla.BusinessBase对象数据处理
环境:.net4.6+csla4.6 实现:对象的数据库访问及数据库执行使用Factory方式进行封闭. 正文: 以前在使用csla框架完成业务对象的定义时所有的数据处理都在对象内部实现,也不能说不好 ...
- python操作samba
最近在部署完xxl-job后,陆续将一些日常性执行的python脚本迁移到上面去:其中部分脚本涉及到对samaba的操作,先后尝试了pysmb.fs.smbfs.pysmbclient pysmb 安 ...
- 高通sdm845_la2.0源码编译及使用QFIL刷机
一.下载源码 高通芯片代码下载地址:https://chipcode.qti.qualcomm.com/ . *_amss_standard_oem : 高通私有源码(*为sdm845-la--. * ...
- WordCount优化版测试小程序实现
Github地址:https://github.com/hcy6668/wordCountPro.git PSP表格: PSP PSP阶段 预估耗时(小时) 实际耗时(小时) Planning ...