I have an contact forms api for unauthenticated user. So anyone can visit my website and submit forms. I integrated my api in reactjs. But anyone can view the json data if he directly visit the api url. Anyone can also submit post request using POSTMAN using the api url. How to restrict anyone to view the api page and also prevent unauthorized post request.
here is my code:
settings.py:
REST_FRAMEWORK = {
# Only enable JSON renderer by default.
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
],
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
],
'DEFAULT_THROTTLE_RATES': {
'anon': '10/minute',
}
}
views.py
api_view(['POST', 'GET'])
def farhyn_api(request):
if request.method == 'POST':
data = request.data
serializer = ContactSerializer(data=data)
if serializer.is_valid():
serializer.save()
print(serializer.data)
return Response({
'status': True,
'message': 'sucess'
})
return Response({
'status': False,
'message': serializer.errors
})
if request.method == "GET":
contact = Contact.objects.all()
serializer = ContactSerializer(contact, many=True)
return Response(serializer.data)
I used AnonRateThrottle but still now anyone can submit POST request using the api url. How to prevent it? Basically I want to allow post request if it's actually come from my website and also how to restrict access view api page?
You have the permission_classes
and IsAuthenticated
.
Just do the following?
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import permission_classes
api_view(['POST', 'GET'])
@permission_classes((IsAuthenticated, )) # < --------
def farhyn_api(request):
if request.method == 'POST':
data = request.data
serializer = ContactSerializer(data=data)
if serializer.is_valid():
serializer.save()
print(serializer.data)
return Response({
'status': True,
'message': 'sucess'
})
return Response({
'status': False,
'message': serializer.errors
})
if request.method == "GET":
contact = Contact.objects.all()
serializer = ContactSerializer(contact, many=True)
return Response(serializer.data)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.