Django REST Framework如何设置默认接口无需认证仅部分需JWT校验
解决方案
问题原因
你之前在全局配置了默认权限规则为IsAuthenticated+IsAdminUser,所以所有接口默认都会继承这个规则,强制要求校验身份凭证,才会出现公开接口返回未提供认证信息的报错。
1. 修改全局配置
把settings.py里的REST_FRAMEWORK配置调整为如下内容,将默认权限改为允许所有用户访问,保留JWT认证类供需要保护的接口使用:
REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ) } JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1), }
调整完成后你现有的CoopList接口就可以正常公开访问,不需要认证。
2. 给需要保护的接口单独配置权限
如果有需要JWT校验的接口,只需要在对应视图上单独指定权限和认证规则即可:
类视图配置示例
from rest_framework.permissions import IsAuthenticated, IsAdminUser from rest_framework_jwt.authentication import JSONWebTokenAuthentication # 这个是需要管理员权限才能访问的受保护视图 class CoopManage(APIView): authentication_classes = [JSONWebTokenAuthentication] permission_classes = [IsAuthenticated, IsAdminUser] def post(self, request, format=None): # 受保护的新增逻辑 ...
如果需要同一个视图下部分HTTP方法公开、部分受保护,可以重写get_permissions方法实现:
class CoopList(APIView): def get_permissions(self): # GET方法公开 if self.request.method == 'GET': return [] # POST/PUT等其他方法需要登录 return [IsAuthenticated()] def get(self, request, format=None): # 公开的查询逻辑 ... def post(self, request, format=None): # 受保护的新增逻辑 ...
函数视图配置示例
如果使用函数式视图,用装饰器配置即可:
from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework_jwt.authentication import JSONWebTokenAuthentication @api_view(['GET']) @authentication_classes([JSONWebTokenAuthentication]) @permission_classes([IsAuthenticated]) def protected_view(request): ...
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

