Reputation: 4421
how to send CSRF token using flutter HTTP request
I have a Django based project that uses django-rest-framework
for API, when I send a POST
request using Postman
it works perfectly fine,, but when I send an HTTP.post
request from my flutter application I get this response :
Forbidden 403
CSRF verification failed. Request aborted.
You are seeing this message because this HTTPS site requires a “Referer header” to be sent by your Web browser, but none was sent
In django am using function based view
to receive the requests:
@api_view(['POST'])
@permission_classes([AllowAny,])
@csrf_exempt
def create_user(request):
......
.....
then in the URLS
:
path("api/v1/create_user/", api.create_user, name="create_user"),
and am sending the request in flutter :
http.post(Uri(myURL),header={
'Content-Type': 'application/x-www-form-urlencoded',
}
,body={
'my_key':'my_value',
})
Upvotes: 0
Views: 5226
Reputation: 616
Trying to get a Flutter app to send a CSRF token is possibly the wrong approach. If you're using some sort of token based authentication then the users auth token should be sufficient for the API to trust the request.
Carefully setting the order of the values in the REST_FRAMEWORK.DEFAULT_AUTHENTICATION_CLASSES
list may be enough to prevent the request from checking for the CSRF token. It is worth noting that rest_framework.authentication.SessionAuthentication
is the authentication class that ultimately causes the 403 response.
Try moving whatever authentication class which provides your token auth to the top of the list, for example:
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"oauth2_provider.contrib.rest_framework.OAuth2Authentication", # <- this at top!
"rest_framework.authentication.BasicAuthentication",
"rest_framework.authentication.SessionAuthentication",
),
}
Upvotes: -1
Reputation: 326
When you are creating a HTTPS website using django, you need to use a Referer header.
Assuming your website's domain is yoursite.com
, you need to set this in your header
{"Referer": "https://yoursite.com"}
in dart/flutter using http package
import 'package:http/http.dart' as http;
var resp = http.post(Uri.parse("https://yoursite.com/api/v1/create_user"),
headers: {"Referer": "https://yoursite.com"}
Upvotes: 1