Django REST framework之BasicAuthentication

目的

一直用Token做Django REST API的验证方式,突然有个低安全要求的应用,只用用户名密码来访问。

from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

class ExampleView(APIView):
    authentication_classes = [SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request, format=None):
        content = {
            'user': str(request.user),  # `django.contrib.auth.User` instance.
            'auth': str(request.auth),  # None
        }
        return Response(content)

实现方式一 

python 的requests的

from requests.auth import HTTPBasicAuth
 url="http://127.0.0.1:8000/customs_app/customs_special_material_clearance/"
res=requests.get(url=url,auth=HTTPBasicAuth(username="username",password="password"))
print(res.text)

实现方式二 

根据HTTPBasicAuth 自己设置headers

import base64
headers={}
headers["Authorization"]='Basic ' +   base64.b64encode(b':'.join(("username".encode(), "password".encode()))).decode()
url="http://127.0.0.1:8000/customs_app/customs_special_material_clearance/"
res=requests.get(url=url,headers=headers)
print(res.text)

 

posted @ 2022-08-04 13:12  帆帆Evan  阅读(195)  评论(0编辑  收藏  举报