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内置的用户认证
认证登陆 在进行用户登陆验证的时候,如果是自己写代码,就必须要先查询数据库,看用户输入的用户名是否存在于数据库中: 如果用户存在于数据库中,然后再验证用户输入的密码,这样一来就要自己编写大量的代码. ...
随机推荐
- docker 安装elasticSearch7.0.0
一.执行命令:docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-n ...
- Angular7.1.4+Typescript3.1框架学习(一)
起因:学习ionic4之前先学习下angular+ts 以win10为开发平台:当前最新版本为angular7;根据官网资料做如下总结: 1. angular安装 前提:Node.js 的 8.x 或 ...
- 在.net core web项目中生成二维码
1.添加QRCoder包引用 2. public IActionResult MakeQrCode() { string url="https://www.baidu.com& ...
- Linux下通过vi修改只读文件
打开一个只读文件 $ vi /etc/crontab 此时会进入crontab的编辑界面,通过按键 ESC 可以进入命令模式,按键 I 进入插入模式 但是!如果此时没有权限进行修改的话,虽然可以插入编 ...
- 从零开始学Python 一
一.安装 1.进入Python官网下载环境:https://www.python.org 2.根据自己的电脑选择安装版本,然后安装即可. 二.运行第一个程序 1.安装完Python,会自带一个编辑器, ...
- Python 安装包报错
以管理员身份运行cmd (requests为为所安装的包名) >>pip install reuqestsCollecting reuqests Could not find a vers ...
- mysql 自定义插件调试
# 创建表的stack frame #0: 0x000000011d11f58a ha_spartan.so`Spartan_data::create_table(this=0x00007f9fc13 ...
- 【重磅】Spring Boot 2.0权威发布
新版本特性 新版本值得关注的亮点有哪些: 基于 Java 8,支持 Java 9 也就是说Spring Boot2.0的最低版本要求为JDK8,据了解国内大部分的互联网公司系统都还跑在JDK1.6/7 ...
- python修炼第二天
第二天的课程还是塞得满满的,一天下来充实也疲惫.那天听出金星师傅嗓子有些沙哑,想必是讲课说话太多导致.啥也不说了.唯有努力练功方可回报! 1 序: 今天主要是详细学习了绝大部分的数据类型,字符编码,边 ...
- JS的全局变量与局部变量及变量的提升
遇到全局变量与局部变量的时候总是出一些或多或少的问题,于是专门花时间去认真研究了一下全局变量与局部变量. 这是在网上看到的一个关于全局变量与局部变量的代码,看了下作者的解析,自己也进行了研究. < ...