四 .Django---framework框架 认证组件 自定义Token认证

一 .认证组件

https://www.cnblogs.com/pythonywy/p/11492877.html     drf框架中认证与权限工作原理及设置

from rest_framework.views import APIView  源码中    
self.perform_authentication(request) # 认证组件 必须是



def authenticate
():
pass

https://www.cnblogs.com/shi-qi/articles/9629399.html    认证实例

https://www.cnblogs.com/dong-/p/9980260.html       DRF版本和认证认证流程

https://www.cnblogs.com/liwenzhou/p/9410737.html     认证组件

 https://www.cnblogs.com/pythonywy/p/11492877.html     drf框架中认证与权限工作原理及设置

https://www.cnblogs.com/big-handsome-guy/p/8485330.html    源码流程

REST framework 提供了一些开箱即用的身份验证方案,并且还允许你实现自定义方案

# 认证 下面不一定是[],也可以()就是需要在数组当中,多个类用,隔开
# 局部取消认证组件:authentication_classes = []
# 区别启用认证组件:authentication_classes = [认证类们] 
# 填写的参数BasicAuthentication,SessionAuthentication

1. 局部视图认证(自定义Token认证)

model类


# Create your models here.
from django.db import models
# Create your models here.
class Book(models.Model):
    title=models.CharField(max_length=32)
    price=models.IntegerField()
    # pub_date=models.DateField(auto_now=True)
    publish=models.ForeignKey("Publish",on_delete=models.CASCADE)      # ForeignKey一对多
    authors=models.ManyToManyField("Author")        # ManyToManyField  多对多
    def __str__(self):
        return self.title

class Publish(models.Model):
    name=models.CharField(max_length=32)
    email=models.EmailField()
    def __str__(self):
        return self.name

class Author(models.Model):
    name=models.CharField(max_length=32)
    age=models.IntegerField()
    def __str__(self):
        return self.name


class User(models.Model):
    name=models.CharField(max_length=32)
    pwd=models.CharField(max_length=32)


class Token(models.Model):
    user=models.OneToOneField("User",on_delete=models.CASCADE)
    token = models.CharField(max_length=128)
    def __str__(self):
        return self.token
viwes

from rest_framework import mixins
from rest_framework import generics
from .models import *
from rest_framework import serializers
from django.core import serializers
import  json
from rest_framework.response import Response
from rest_framework.views import APIView
from django.views import View




from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication
# 局部视图认证 自定义认证类 class TokenAuth(BaseAuthentication): def authenticate(self,request): token = request.GET.get("token") token_obj = Token.objects.filter(token=token).first() if not token_obj: raise exceptions.AuthenticationFailed("验证失败123!") else: return token_obj.user.name,token_obj.token
"""class TokenAuth2(object): def authenticate(self,request): token = request.GET.get("token") token_obj = Token.objects.filter(token=token).first() if not token_obj: raise exceptions.AuthenticationFailed("验证失败123!") else: return token_obj.user.name,token_obj.token """
# 随机字符串token值 def get_random_str(user): import hashlib,time ctime=str(time.time()) md5=hashlib.md5(bytes(user,encoding="utf8")) md5.update(bytes(ctime,encoding="utf8")) return md5.hexdigest() from .models import User
# 登录视窗 class LoginView(APIView): authentication_classes = [TokenAuth,] # 局部视图认证 def post(self,request): name=request.data.get("name") pwd=request.data.get("pwd") user=User.objects.filter(name=name,pwd=pwd).first() print(user,name,pwd,"222222222222222") res = {"state_code": 1000, "msg": None} if user: random_str=get_random_str(user.name) token = Token.objects.update_or_create(user=user, defaults={"token": random_str}) res["token"]=random_str else: res["state_code"]=100 #错误状态码 res["msg"] = "用户名或者密码错误" import json return Response(json.dumps(res,ensure_ascii=False))
 url(r'^login/$', views.LoginView.as_view(), name="login"),

2.  全局级别认证

settings.py配置如下:

REST_FRAMEWORK={
    "DEFAULT_AUTHENTICATION_CLASSES":["myapp.auth.Authentication",]
}

在setting中设置

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        # django默认session校验:校验规则 游客 及 登录用户
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        # 'rest_framework.permissions.AllowAny',
        # 全局配置:一站式网站(所有操作都需要登录后才能访问)
        # 'rest_framework.permissions.IsAuthenticated',
    ],
}
原文地址:https://www.cnblogs.com/lovershowtime/p/11647789.html