使用 React 和 Django REST Framework 进行身份验证
Authentication with React and Django REST Framework
我想将 React 前端添加到具有 Django 后端的网站。为此,我使用了 Django REST 框架。但是如何防止未登录的人发送 POST 操作来添加文章?我想 运行 整个前端作为 React 应用程序,而不是在成功登录后重定向到 React 应用程序。
在 django rest 框架中你有 permissions [DRF docs] 的概念。
您可以在设置中默认设置特定权限,如下所示:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
然后您可以覆盖每个视图的权限,例如:
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
class ExampleView(APIView):
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
rest_framework.permissions.IsAuthenticated
不是您可以使用的唯一预定义权限 class。有一个名为 rest_framework.permissions.IsAuthenticatedOrReadOnly
的权限,这就是我认为您想要的:允许所有人读取访问权限,但只允许经过身份验证的用户进行写入访问(例如 POST 在您的文章上)。
顺便说一下,一旦您设置了正确的权限,您将需要定义和配置一种身份验证方法来验证您的前端,并能够从中发送 POST 请求。
为此,您需要阅读 authentication DRF documentation, choose between the methods (session authentication, token authentication etc.), and configure them correctly. There are third party libraries that can help you like dj-rest-auth or djoser.
我想将 React 前端添加到具有 Django 后端的网站。为此,我使用了 Django REST 框架。但是如何防止未登录的人发送 POST 操作来添加文章?我想 运行 整个前端作为 React 应用程序,而不是在成功登录后重定向到 React 应用程序。
在 django rest 框架中你有 permissions [DRF docs] 的概念。
您可以在设置中默认设置特定权限,如下所示:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
然后您可以覆盖每个视图的权限,例如:
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
class ExampleView(APIView):
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
rest_framework.permissions.IsAuthenticated
不是您可以使用的唯一预定义权限 class。有一个名为 rest_framework.permissions.IsAuthenticatedOrReadOnly
的权限,这就是我认为您想要的:允许所有人读取访问权限,但只允许经过身份验证的用户进行写入访问(例如 POST 在您的文章上)。
顺便说一下,一旦您设置了正确的权限,您将需要定义和配置一种身份验证方法来验证您的前端,并能够从中发送 POST 请求。 为此,您需要阅读 authentication DRF documentation, choose between the methods (session authentication, token authentication etc.), and configure them correctly. There are third party libraries that can help you like dj-rest-auth or djoser.