I want to add a React frontend to a website with Django backend. For this I used the Django REST framework. But how can I prevent people who are not logged in from sending a POST action to add an article? I want to run the whole frontend as a React app and not redirect to a React app after a successful login.
In django rest framework you have the notion of permissions [DRF docs].
You can set a specific permission by default in your settings like this:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
And then you can override permissions for each view, for example:
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
is not the only pre-defined permission class you can use. There is a permission called rest_framework.permissions.IsAuthenticatedOrReadOnly
, which is I think what you want: allow read access to everyone, but write access (eg. POST on your articles) only to authenticated users.
And by the way once you have set the correct permissions, you will need to define and configure an authentication method to authenticate your frontend, and be able to send the POST requests from it. For that, you will need to read the 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.