drf:认证及权限

一、认证Authentication

在drf中我们还可以进行权限和认证操作,我们先来看看认证

1、全局认证

全局认证我们只需在django配置文件中加入一个字典即可:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}

2、局部认证

局部认证我们需要在视图中进行处理:

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView, CreateAPIView,UpdateAPIView,ListAPIView,RetrieveAPIView,DestroyAPIView
from rest_framework.response import Response
from rest_framework.mixins import CreateModelMixin,ListModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin
from rest_framework.viewsets import ModelViewSet

from .models import BookMessage
from rest_framework import status
from .serializer import BookSerializer
from rest_framework.decorators import action
from rest_framework.authentication import SessionAuthentication

# Create your views here.

class BookOperation(ModelViewSet):
	queryset = BookMessage.objects.all()
	serializer_class = BookSerializer
	# 认证
	authentication_classes = [SessionAuthentication]

当全局认证及局部认证同时存在时,优先局部认证。

二、权限

全局权限及局部权限设置方法和认证类似

1、全局权限

1、IsAuthenticated 允许普通用户访问
2、AllowAny 允许任何用户访问
3、IsAdminUser 允许超管访问
全局配置方法,在配置文件中添加:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
        'rest_framework.permissions.AllowAny',
        'rest_framework.permissions.IsAdminUser',
    ]
}

2、局部权限

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView, CreateAPIView,UpdateAPIView,ListAPIView,RetrieveAPIView,DestroyAPIView
from rest_framework.response import Response
from rest_framework.mixins import CreateModelMixin,ListModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin
from rest_framework.viewsets import ModelViewSet

from .models import BookMessage
from rest_framework import status
from .serializer import BookSerializer
from rest_framework.decorators import action
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import AllowAny,IsAdminUser

# Create your views here.

class BookOperation(ModelViewSet):
	queryset = BookMessage.objects.all()
	serializer_class = BookSerializer
	authentication_classes = [SessionAuthentication]
	# 只允许管理员访问
	permission_classes = [IsAdminUser]

三、测试

配置完成后,我们来进行测试:
配置为局部session认证,允许管理员权限访问
我们首先不做任何登陆访问:
在这里插入图片描述
如图,认证机制拒绝了访问
接下来,我们新建一个管理员用户,并在admin页面登陆:
创建用户
登陆
此时我们再次访问刚才的页面:
访问
如图,以管理员身份成功访问页面。

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 点我我会动 设计师:白松林 返回首页