赞
踩
- REST_FRAMEWORK = {
- 'DEFAULT_AUTHENTICATION_CLASSES': (
- 'rest_framework.authentication.BasicAuthentication', # 基本认证
- 'rest_framework.authentication.SessionAuthentication', # session认证
- )
- }
一、基本认证:所有请求都需要用户名密码
session认证:只有第一次请求需要用户名密码
配置文件中配置全局的认证方案;
视图中可以单独设置authentication_classess属性来设置
- from rest_framework.authentication import SessionAuthentication, BasicAuthentication
- from rest_framework.views import APIView
- class ExampleView(APIView):
- authentication_classes = (SessionAuthentication, BasicAuthentication)
- ...
二、认证失败返回值
三、配置只是有认证功能,但是需要在权限中具体指明如何使用
----------------------------------------------------------------------------------------------------------
权限:
可以在配置文件中全局设置权限管理类:
- REST_FRAMEWORK = {
- 'DEFAULT_PERMISSION_CLASSES': (
- 'rest_framework.permissions.IsAuthenticated',
- )
- }
也可以在视图中设置:
- from rest_framework.permissions import IsAuthenticated
- from rest_framework.views import APIView
- class ExampleView(APIView):
- permission_classes = (IsAuthenticated,)
- ...
- class BookDetailView(RetrieveAPIView):
- queryset = BookInfo.objects.all()
- serializer_class = BookInfoSerializer
- authentication_classes = [SessionAuthentication]
- permission_classes = [IsAuthenticated]
自定义权限
继承rest_framework.permissions.BasePermission,实现
.has_permission(self, request, view)
是否可以访问视图, view表示当前视图对象
.has_object_permission(self, request, view, obj)
是否可以访问数据对象, view表示当前视图, obj为数据对象
- class MyPermission(BasePermission):
- def has_object_permission(self, request, view, obj):
- """控制对obj对象的访问权限,此案例决绝所有对对象的访问"""
- return False
-
- class BookInfoViewSet(ModelViewSet):
- queryset = BookInfo.objects.all()
- serializer_class = BookInfoSerializer
- permission_classes = [IsAuthenticated, MyPermission]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。