一般情况下我们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用户认证的更多相关文章

  1. (30)auth模块(django自带的用户认证模块)

    Auth模块是Django自带的用户认证模块: 我们在开发一个网站的时候,无可避免的需要设计实现网站的用户系统.此时我们需要实现包括用户注册.用户登录.用户认证.注销.修改密码等功能,这还真是个麻烦的 ...

  2. Django之auth模块用户认证模块

    一.Auth模块 1)auth模块是什么.登录后台使用的账号密码,则就是使用的auth模块创建的表 Auth模块是Django自带的用户认证模块: 我们在开发一个网站的时候,无可避免的需要设计实现网站 ...

  3. Django自带的用户认证

    1. 创建超级用户   python manage.py createsuperuser   2. 认证  校验用户名和密码  obj = auth.authenticate(request,user ...

  4. Django框架 之 Auth用户认证

    Django框架 之 Auth用户认证 浏览目录 auth模块 user对象 一.auth模块 1 from django.contrib import auth django.contrib.aut ...

  5. 5分钟搞懂:基于token的用户认证

    https://www.qikegu.com/easy-understanding/880 用户认证 用户认证或者说用户登录是确认某人确实是某人的过程,生活中靠身份证,网络上就要靠账号和密码.用户提供 ...

  6. 6月29日学习总结 Django自带的用户认证

    Django自带的用户认证 我们在开发一个网站的时候,无可避免的要设计.实现网站的用户系统.此时我们需要实现包括但不限于用户注册.用户登录.用户认证.注销.修改密码等功能,这还真是个麻烦的事情呢. D ...

  7. 基于JWT标准的用户认证接口实现

    前面的话 实现用户登录认证的方式常见的有两种:一种是基于 cookie 的认证,另外一种是基于 token 的认证 .本文以基于cookie的认证为参照,详细介绍JWT标准,并实现基于该标签的用户认证 ...

  8. JWT token 跨域认证

    JSON Web Token(缩写 JWT),是目前最流行的跨域认证解决方案. session登录认证方案:用户从客户端传递用户名.密码等信息,服务端认证后将信息存储在session中,将sessio ...

  9. Django内置的用户认证

    认证登陆 在进行用户登陆验证的时候,如果是自己写代码,就必须要先查询数据库,看用户输入的用户名是否存在于数据库中: 如果用户存在于数据库中,然后再验证用户输入的密码,这样一来就要自己编写大量的代码. ...

随机推荐

  1. ajax提交不进入后台报415错误

    Unsupported Media Type错误 问题所在为后台缺包和xml配置文档缺配置或配置不正确: Jackson的依赖问题,spring3.x和spring4.x是不同的: spring3.x ...

  2. recyclerview 主活动里监听点击事件

    记性真的不行啊...贴上来有时间多复习复习 主活动 package com.example.com.webtext; import android.content.Intent; import and ...

  3. webapi put 404

    windows server 2016  IIS  webapi   404 error In IIS select your website and double-click Handler Map ...

  4. request.getParameter()在get和post方法中文乱码问题

    乱码原因:Http请求传输时将url以ISO-8859-1编码,服务器收到字节流后默认会以ISO-8859-1编码来解码成字符流(造成中文乱码) post请求: 假设提交请求的jsp页面是UTF-8编 ...

  5. learning makefile foreach

  6. math-2人博弈

    问题描述: 100根火柴,2人轮流取,每人每次只能取1-7根,取走最后一根火柴的人获胜.问有没有一种策略肯定能够获胜?该策略具体:先取or后取,怎么取? 思维过程: step1:题目问的很明显,所以肯 ...

  7. AVR 嵌入式单片机芯片的中断系统介绍

    body, table{font-family: 微软雅黑; font-size: 13.5pt} table{border-collapse: collapse; border: solid gra ...

  8. 部署你的CRM程序

    教你发布CRM   发布CRM你将使用以下软件 nginx uWSGI CentOS7 CRM项目文件 virtualenv supervisor WSGI.uWSGI python web服务器开发 ...

  9. [Leetcode 216]求给定和的数集合 Combination Sum III

    [题目] Find all possible combinations of k numbers that add up to a number n, given that only numbers ...

  10. JS案例六_1:添加城市

    使用的相关知识点:对子节点的添加:document.appendClild() 文本节点的创建:document.createTextNode() 元素节点的创建:document.createEle ...