1.1 全局认证认证需要结合权限来使用! Authentication 官方配置文档
- 使用DEFAULT_AUTHENTICATION_CLASSES设置全局的默认身份验证方案
# settings.py
# REST_frameWORK DRF中所有的配置都写与此中
REST_frameWORK = {
# 配置全局的认证方案
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication', # 基本认证
'rest_framework.authentication.SessionAuthentication',# session认证
)
}
1.2 局部认证
- 单独的在视图里面通过设置authentication_classes属性来设置,需要认证的视图类就写在需要的视图类中即可。
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': unicode(request.user), # `django.contrib.auth.User` 实例。
'auth': unicode(request.auth), # None
}
return Response(content)
二、权限 Permissions认证失败的返回值有:403权限被禁止、401未认证。一般认证使用全局认证即可。
2.1 全局权限权限 Permissions 官方文档,提供的权限有:
- 允许所有用户:AllowAny
- 仅通过认证的用户:isAuthenicated
- 仅管理员用户:isAdminUser
- 认证的用户可以完全操作,否则只能get访问读取:IsAuthenticatedOrReadOnly
- 默认权限策略可以使用DEFAULT_PERMISSION_CLASSES设置进行全局设置。
REST_frameWORK = {
'DEFAULT_PERMISSION_CLASSES': (
# 仅通过的认证的用户才能访问
'rest_framework.permissions.IsAuthenticated',
)
}
- 如果未指定,则此设置默认为允许无限制访问:
'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', )2.2 局部权限
from rest_framework.permissions import IsAuthenticated
class ExampleView(APIView):
# 设置权限
permission_classes = (IsAuthenticated,)
三、限流 Shrottling认证一般全局使用,权限一般局部使用
3.1 全局限流对接口访问的频次进行限制,以减轻服务器压力。限流 Shrottling官方地址
使用DEFAULT_THROTTLE_CLASSES和DEFAULT_THROTTLE_RATES默认限流策略将被全局设定,秒second,分minute、时hour 、天 day 作为限流周期
REST_frameWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
),
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day', # 匿名用户
'user': '1000/day' # 登录用户
}
}
3.2 局部限流
- 对于基于 APIView 类的视图,您可以以每个视图或每个视图集为基础设置限流策略
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView
class ExampleView(APIView):
throttle_classes = (UserRateThrottle,)
def get(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)



