drf-认证

Djago authod:  https://www.cnblogs.com/kaibindirver/p/16687787.html

https://www.bilibili.com/video/BV1XR4y157rk?p=16&vd_source=caabcbd2a759a67e2a3de8acbaaf08ea

先创建用户和表啥的见上方链接

 

setting

REST_FRAMEWORK={
    'DEFAULT_AUTHENTICATION_CLASSES':(
         'authod.authentication.aa',#自定义认证
        'rest_framework.authentication.SessionAuthentication', #session认证
        'rest_framework.authentication.BasicAuthentication', #基本认证
    )
}

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # mysql数据库引擎,
        'NAME': 'Django_model',  # 数据库名字
        'USER': 'root',  # 用户名
        'PASSWORD': '123456',  # 密码
        'HOST': 'localhost',  # 主机
        'PORT': '3317',  # 端口

        'OPTIONS': {  # 添加以下代码,取消外键检查
        "init_command": "SET foreign_key_checks = 0;",
    }
} }

 

init

import pymysql
pymysql.version_info = (1, 4, 13, "final", 0)
pymysql.install_as_MySQLdb()  # 使用pymysql代替mysqldb连接数据库

 

view

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.response import Response
from rest_framework.views import APIView

from authod.authentication import aa


class authod(APIView):
    authentication_classes = [aa,SessionAuthentication,BasicAuthentication]
    def get(self, request):
        print(request.user) #未登录用户AnonymousUser

        if request.user.id :
            print("认证通过")
        else:
            print("未通过认证")
        return Response("ok")

 

authentication

(自定义认证 aa类)

from django.contrib.auth import get_user_model
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import PermissionDenied, AuthenticationFailed, NotAuthenticated, NotFound, bad_request, \
    ValidationError, ErrorDetail, NotAcceptable

class aa(BaseAuthentication):
    '''
    自定义认证
    '''
    def authenticate(self,request):

        user= request.query_params.get("user")
        pwd = request.query_params.get("pwd")
        if user != "root" or pwd !="houmen":
            return None
            #不返回None 也可以直接让接口抛异常
            raise AuthenticationFailed      #{"status": 403,"msg": "认证失败","succese": false}
        # 获取当前系统中用户表对应的用户模型
        user=get_user_model().objects.first()
        return (user,None)  #按照固定的返回格式填写 (用户模型对象,None)  这里视图层用 request.user 可以拿到这里返回的信息

 

https://blog.csdn.net/weixin_51103262/article/details/108855570

 

一、authentication_classes  认证

https://www.cnblogs.com/paulwhw/articles/11358339.html

二、jwt

https://www.cnblogs.com/kaibindirver/p/17098903.html

 

 

后记:

重写返回的响应码,视图层用法同上

from rest_framework.exceptions import APIException ,AuthenticationFailed
#exceptions库里面有很多已写好的返回
    
class NotAcceptable(APIException):    #NotAcceptable在exceptions库默认是返回406 我们可以重写他
    status_code = status.HTTP_401_UNAUTHORIZED   #重写返回的响应码


class MyAutheentication(BaseAuthentication):
    def authenticate(self,request):
        token=request.COOKIES.get("dev_internal_account_token")
        tokenResult=checkTokenEffective(token)
        #这里加需要认证的逻辑,获取token查数据库啥的,这里return的下面用request.use去拿
        # 判断token是否有效
        if token is None:
            raise NotAcceptable('请先登录') #401 跳登录页   不输入参数就输出默认值
        elif:
            raise AuthenticationFailed('没有权限进入测试平台') #403 跳无权限页面
        else:
            return ("张三",None)

 

posted @ 2022-12-13 14:51  凯宾斯基  阅读(31)  评论(0)    收藏  举报