DRF框架的认证组件

核心代码:       self.perform_authentication(request) 

框架自带模块:    from rest_framework import authentication

认证组件的返回值:request.user

自定义的认证组件的钩子方法authenticator.authenticate(self) ;返回值是元组(user,auth)

from rest_framework import authentication

from rest_framework import authentication

class BaseAuthentication(object):
def authenticate(self, request):
# 必须重写该方法,返回元组(user,auth)
return (user_obj,token) class BasicAuthentication(BaseAuthentication): class SessionAuthentication(BaseAuthentication): class TokenAuthentication(BaseAuthentication): class RemoteUserAuthentication(BaseAuthentication):

基于BaseAuthentication类的认证
# myauth.py

from rest_framework import authentication
from AuthDemo.models import UserTable
from rest_framework.exceptions import AuthenticationFailed # 用于抛出异常 # 基于BaseAuthentication类的认证
class AuthoDemo(authentication.BaseAuthentication):
'''验证GET请求是否携带Token'''
def authenticate(self, request):
# 通过/user/test/?token="xxx" 获取token
token = request.query_params.get("token","")
# 如果token不存在
if not token:
# 抛出异常
raise AuthenticationFailed("token不存在") # token存在,验证token
user_obj = UserTable.objects.filter(token=token).first()
if user_obj:
# 验证通过,必须返回元组,(user,token)
return (user_obj,token)
# 认证不通过抛出异常
raise AuthenticationFailed("token错误")
# views.py

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import UserTable
import uuid
from utils.myauth import AuthoDemo
from rest_framework import authentication # Create your views here. # 注册视图
class RegisterView(APIView):
def post(self,request):
# 获取提交的用户名和密码
username = request.data.get('username')
password = request.data.get('password') # 创建对象
UserTable.objects.create(username=username,password=password) # 返回结果
return Response("注册成功!") # 登陆视图
class LoginView(APIView):
def post(self,request):
# 获取提交的用户名和密码
username = request.data.get('username')
password = request.data.get('password')
# 验证用户名密码是否正确
user_obj = UserTable.objects.filter(username=username,password=password).first()
if user_obj:
# 验证通过,写入Token并保存
token = uuid.uuid4()
user_obj.token = token # 为对象的token字段写入随机字符串
user_obj.save()
# 返回token
return Response(token)
else:
return Response("用户名密码不正确") # 认证的测试视图
class TestView(APIView):
authentication_classes = [AuthoDemo,]
def get(self,request):
print(request.user) # 获取用户对象
print(request.auth) # 获取token
print(request.user.username) # 获取用户对象的名字
return Response("认证测试接口")

源码流程

# 1、封装request对象
def dispatch(self, request, *args, **kwargs):
request = self.initialize_request(request, *args, **kwargs) # 1.1
def initialize_request(self, request, *args, **kwargs):
parser_context = self.get_parser_context(request)
return Request(
request,
parsers=self.get_parsers(),
# 返回认证类的实例化对象列表:[auth() for auth in self.authentication_classes]
authenticators=self.get_authenticators(),
negotiator=self.get_content_negotiator(),
parser_context=parser_context
) # 1.2
class APIView(View):
authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES from rest_framework import authentication # 查看自带的认证类 class ApiView(View):
# 2、认证组件
self.perform_authentication(request)
# 权限组件
self.check_permissions(request)
# 节流组件
self.check_throttles(request) # 2.1、开始认证
def perform_authentication(self, request):
request.user # 2.2、调用Request.user
class Request(object):
def __init__(self, request, authenticators=None):
self.authenticators = authenticators or () @property
def user(self):
if not hasattr(self, '_user'):
with wrap_attributeerrors():
# 2.3、
self._authenticate()
return self._user # 2.3、读取认证对象列表
def _authenticate(self):
for authenticator in self.authenticators:
try:
# 对每个进行验证,异常则全部终止,若返回None,则继续循环
user_auth_tuple = authenticator.authenticate(self) except exceptions.APIException:
self._not_authenticated()
raise if user_auth_tuple is not None:
# 给request赋值user
self._authenticator = authenticator
self.user, self.auth = user_auth_tuple
# 通过直接退出循环
return # 全都没有通过则设置匿名用户
self._not_authenticated() # 认证类实例
class BasicAuthentication(BaseAuthentication):
def authenticate(self, request):
"""
Returns a `User` if a correct username and password have been supplied
using HTTP Basic authentication. Otherwise returns `None`.
"""
pass
return self.authenticate_credentials(userid, password, request) def authenticate_credentials(self, userid, password, request=None):
"""
Authenticate the userid and password against username and password
with optional request for context.
"""
user = authenticate(request=request, **credentials) if user is None:
raise exceptions.AuthenticationFailed(_('Invalid username/password.')) if not user.is_active:
raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) return (user, None)
												

【DRF框架】认证组件的更多相关文章

  1. 第三章、drf框架 - 序列化组件 | Serializer

    目录 第三章.drf框架 - 序列化组件 | Serializer 序列化组件 知识点:Serializer(偏底层).ModelSerializer(重点).ListModelSerializer( ...

  2. Django框架深入了解_03(DRF之认证组件、权限组件、频率组件、token)

    一.认证组件 使用方法: ①写一个认证类,新建文件:my_examine.py # 导入需要继承的基类BaseAuthentication from rest_framework.authentica ...

  3. DRF 之 认证组件

    1.认证的作用? 我们知道,当我们在网站上登陆之后,就会有自己的个人中心,之类的可以对自己的信息进行修改.但是http请求又是无状态的,所以导致我们每次请求都是一个新的请求,服务端每次都需要对请求进行 ...

  4. drf框架 - 过滤组件 | 分页组件 | 过滤器插件

    drf框架 接口过滤条件 群查接口各种筛选组件数据准备 models.py class Car(models.Model): name = models.CharField(max_length=16 ...

  5. drf框架 - 序列化组件 | ModelSerializer (查,增,删,改)

    ModelSerializer 序列化准备: 配置 settings.py # 注册rest_framework框架 INSTALLED_APPS = [ ... 'rest_framework' ] ...

  6. DRF之认证组件源码解析

    认证组件  认证的几种方法:cookie,session,token几种.但是session会使服务器的压力增大,所以我们经常使用的是token.获取唯一的随机字符串: 登陆携带token值的处理: ...

  7. DRF之认证组件、权限组件、频率组件使用方法总结

    认证组件格式: from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions ...

  8. drf框架 - 序列化组件 | Serializer

    序列化组件 知识点:Serializer(偏底层).ModelSerializer(重点).ListModelSerializer(辅助群改) 序列化与反序列化 序列化: 将对象序列化成字符串用户传输 ...

  9. Django rest-framework框架-认证组件的简单实例

    第一版 : 自己写函数实现用户认证 #models from django.db import models #用户表 class UserInfo(models.Model): user_type_ ...

  10. DRF框架之认证组件用法(第四天)

    1. 什么是drf 框架的认证组件: auth 就等于是jango中的Auth模块,Auth是自带session信息,但是 drf的认证组件可以自定义token携带过去,去判断用的 2.如何实现认证呢 ...

随机推荐

  1. python 把带小数的浮点型字符串转换为整数的解决方案

    以下内容在python中完全可以接受: 将整数的字符串表示形式传递给 int 将float的字符串表示形式传递给 float 但是,如果你将float型的字符串传递给int将会得到错误. >&g ...

  2. 相位展开(phase unwrapping)算法研究与实践

    1. 什么是相位展开? 相位展开(Phase Unwrapping)是一个经典的信号处理问题,它指的是从值区间中恢复原始相位值(原因在于:计算相位时,运用反正切函数,则相位图中提取的相位都是包裹在一个 ...

  3. iptables的statistic模块配置rr

    网上搜的是这样的 : iptables -A PREROUTING -t nat -d 172.17.64.8 -m statistic --mode nth --every 2 --packet 0 ...

  4. Java高级面试题整理(附答案)

    这是我收集的10道高级Java面试问题列表.这些问题主要来自 Java 核心部分 ,不涉及 Java EE 相关问题.你可能知道这些棘手的 Java 问题的答案,或者觉得这些不足以挑战你的 Java ...

  5. VS2010 C#添加水晶报表及设计

    添加并设计水晶报表. [1]在VS中添加水晶报表 右击项目-->添加-->组件-->Crystal Report,输入文件名称“CrystallistReport”,如下图所示: 此 ...

  6. PHP设计模式 - 桥接模式

    将抽象部分与它的实现部分分离,使他们都可以独立的变抽象与它的实现分离,即抽象类和它的派生类用来实现自己的对象 桥接与适配器模式的关系(适配器模式上面已讲解): 桥接属于聚合关系,两者关联 但不继承 适 ...

  7. Mysql数据库索引IS NUll ,IS NOT NUll ,!= 是否走索引

    声明在前面 总结就是 不能单纯说 走和不走,需要看数据库版本,数据量等 ,希望不要引起大家的误会,也不要被标题党误导了. 1 数据库版本: 2 建表语句 CREATE TABLE s1 ( id IN ...

  8. 08 Spring框架的概念、优势、体系结构、耦合性和IOC(反转控制)

    1.spring介绍 Spring 是分层的 Java SE/EE 应用 full-stack 轻量级开源框架,以 IoC(Inverse Of Control: 反转控制)和 AOP(Aspect ...

  9. PHP提取中英文首字母的方法(首字母索引)

    function Getzimu($str) { $str= iconv("UTF-8","gb2312", $str);//如果程序是gbk的,此行就要注释掉 ...

  10. linux系统调整磁盘分区

    xfs分区格式调整分区大小 调整前备份: mkdir /tmp/home cp -r /home/* /tmp/home/ umount /home 卸载时报错有占用 fuser -m -v -i - ...