保护Django API的最佳方法是使用Token验证和权限控制。下面是一个包含代码示例的解决方法:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}
from django.urls import path
from .views import MyAPIView
urlpatterns = [
path('my-api/', MyAPIView.as_view(), name='my-api'),
]
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
class MyAPIView(APIView):
permission_classes = [IsAuthenticated]
def get(self, request):
# 检查是否认证通过
if not request.user.is_authenticated:
return Response({'error': '未认证'}, status=401)
# 其他处理逻辑
...
def post(self, request):
# 检查是否认证通过
if not request.user.is_authenticated:
return Response({'error': '未认证'}, status=401)
# 其他处理逻辑
...
在上述代码中,IsAuthenticated
权限类用于验证用户是否通过Token认证。如果用户未通过认证,会返回401未认证状态码。
这样,每次客户端发送请求时,都需要在请求的头部添加一个名为Authorization
的字段,值为Token
,其中
是用户的Token值。如果Token验证通过,API视图中的逻辑会继续执行,否则返回未认证错误。
需要注意的是,以上代码只是基本示例,实际的权限控制可能更加复杂,可以根据实际需求进行自定义。