Angular can't get CSRF cookie from Django - django

I did a lot of research on this topic, but it's still not working for me.
I set my csrftoken cookie in Django,and it does in the response object.
But in any browser, it says no cookies in this site
Backend:
#ensure_csrf_cookie
def home(request):
csrf_token = get_token(request)
response = HttpResponse()
response = render(request, 'index.html')
response.set_cookie(key='csrftoken', value=csrf_token)
return response
Angular:
myapp.config(function($httpProvider){
//I use this when in angular1.0.x
//$http.defaults.headers.post['X-CSRFToken'] = $cookies['csrftoken'];
//now in angular1.2.x I use code below. but none of them works
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
});
When I do a POST I get message
Failed to load resource: the server responded with a status of 403 (FORBIDDEN)
Also if I print out header info in the $http error function:
console.log(header('Set-Cookie'));
console.log(header('Access-Control-Allow-Headers'));
console.log(header('Access-Control-Allow-Methods'));
all of these three are null.
I can't figure it why! Especially, it works fine in localhost, either Firefox or Chrome, but in an Apache server, always no cookie in this site.
Is there any setting should I do? Can anyone help my with this issue?

I'm not sure this will help, but your view is terribly written. You're trying to force the csrf in about five different ways, and you also have some redundant lines that don't do anything (you do response = HttpResponse() and then override it completely, making that line completely void). so there's a good chance one of them is screwing things over.
The point is - when you use render you don't need to do anything else to enforce the csrf (you know, except for making sure it's enabled). That's the point of using it over render_to_response. Try this much simpler version and see how much it helps:
def home(request):
return render(request, 'index.html')

Please check the domain of the cookie set by Django.
Be aware of cross-domain requests.
$http docs : Angular provides a mechanism to counter XSRF, When performing XHR requests but will not be set for cross-domain requests.
Here is a small lib that might help you https://github.com/pasupulaphani/angular-csrf-cross-domain/blob/master/dist/angular-csrf-cross-domain.js

Try including the ngCookies module in your application.
myApp.run(function ($http, $cookies) {
$http.defaults.headers.common['X-CSRFToken'] = $cookies.csrftoken;
});

Related

Add CSRF to locust post request to prevent django error - Forbidden (CSRF cookie not set.)

How to add CSRF to the URL to test django from locust to prevent the error Forbidden (CSRF cookie not set.)?
Here is what I have tried:
#task
def some_task(self):
response = self.client.get("api/test/")
csrftoken = response.cookies['csrftoken']
self.client.post(
"api/test/",
{"csrfmiddlewaretoken": csrftoken},
headers={"X-CSRFToken": csrftoken},
cookies={"csrftoken": csrftoken})
The error I get is
KeyError: "name='csrftoken', domain=None, path=None"
Try to debug your response.cookies because you could have the "csrftoken" inside a class, which was my case.
I was getting something like this when I printed on the console:
print(response.cookies)
<RequestsCookieJar[Cookie(version=0, name='csrftoken', value='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
which it will result in a KeyError: "name='csrftoken' if I try to access it via response.cookies['csrftoken']
What you need to do to get this value is response.cookies.get_dict()["csrftoken"]. This way you will be able to get the artribute value from inside the RequestsCookieJar class.
You can have this problem when the CSRF_COOKIE_SECURE setting is True.
I believe browsers are smart enough to ignore the secure setting when making requests to 127.0.0.1 so you don't notice the issue during normal development, but Locust respects the cookie's secure setting and will not send the CSRF cookie to http://127.0.0.1:8000, for example.
I had the exact same error and using CSRF_COOKIE_SECURE=False fixed it. You may also want SESSION_COOKIE_SECURE=False.

Django CSRF Token present but still getting 403 Forbidden Error

I am trying to set up a Django API that receives POST requests with some JSON data and basically sends emails to a list of recipients. The logic is rather simple:
First I have the view for when I create a blog post. In the template, I include the csrf_token as specified on the Django Documentation. When I hit the submit button, behind the scene the create-post view, in addition to creating the post, makes a request (I am using the requests module) to the API which is charged with sending the emails. This is the piece of logic the sends the request to the API:
data = {
"title": new_post.title,
"summary": new_post.summary,
"link": var["BASE_URL"] + f"blog/post/{new_post.slug}"
}
csrf_token = get_token(request)
# print(csrf_token)
headers = {"X-CSRFToken": csrf_token}
requests.post(var["BASE_URL"] + "_api/send-notification/", json=data, headers=headers)
As you can see I am adding the X-CSRFToken to the headers which I generate through the get_token() method, as per the Django docs. However, the response in the API is a 403 Forbidden status CSRF Token not set.
I have checked the headers in the request and the token is indeed present. In addition, I have been providing other routes to the API and I have been using it for AJAX calls which again is very simple just follow the Django docs and they work perfectly well.
The problem seems to arise when I make the call from within the view, AJAX calls are handle by Javascript static files, and as I said they work fine.
I have thought that Django didn't allow the use of 2 CSRF tokens on the same page (one for the submit form and the other in the view by get_token()), but that's not the problem.
This is typically the error I get:
>>> Forbidden (CSRF cookie not set.): /_api/send-notification/
>>> "POST /_api/send-notification/ HTTP/1.1" 403 2864
I have read several similar questions on SO but they mostly involved using the csrf_exempt decorator, which in my opinion is not really a solution. It just gets rid of the CRSF token usefulness altogether.
Does anyone have any idea what might be causing this problem?
Thanks
Error tries to tell you that you need to add token into cookie storage like that:
cookies = {'csrftoken': csrf_token}
requests.post(var["BASE_URL"] + "_api/send-notification/", json=data, headers=headers, cookies=cookies)

Django - get the running server absolute url

Is there any way I can set a variable in settings.py to point to the current url ?
For example, If I'm running a debug server on http://0.0.0.0:8080 or http://127.0.0.1:9000 or https://www.mydomain.com.
I basically need to generate full path for image fields returned from an API. The trick is that I don't always have a request object (POST on DRF for example - The request does not exist in the context when transform_xxx is called).
Appreciate any help with this.
Assuming you're using the contrib.sites framework you can pull the site URL from there.
There's a good example in the docs for when you don't have access to the request:
current_site = Site.objects.get_current()
if current_site.domain == 'foo.com':
# Do something
pass
else:
# Do something else.
pass
Hopefully that's what you need.
UPDATE: I see from the comments that used correctly you would have the request available. I'll leave this here answering the challenge for when you don't.

Unit test through an oauth flow in Django

I have an oauth flow in which a user grants access to a certain scope and then my application can do stuff. For this to work, I need an access token with the defined scope.
I implemented this (with the django allauth package) and it works great. But...
I would like to test it.
This is what I have so far (request package is like an urllib on steroids):
login = self.client.login(username='test_user', password='test')
self.assertTrue(login)
resp = self.client.post(reverse('oauth_login'))
self.assertEqual(resp.status_code, 302)
payload = {'session_key': 'email', 'session_password': 'pw', }
resp2 = requests.post(resp['location'], data=payload)
resp3 = self.client.get(reverse('do_stuff_with_access_token'))
self.assertEqual(resp.status_code, 302)
The issue here is that I do not get the access token in my request variables. My guess is that I am going out of the scope of the application and Django does not get the variable in its request scope.
How can you test this in an elegant manner? Mocking an access_token seems a bit wrong to me. I am now trying to go Selenium for filling in the form, but even that is not really a success so far...
Thanks!
Kudos to Mark!
To help anyone on their way.
Mocking worked out. In my case (django 1.4) you need to add your tokens to the session. A lot of different advices can be found on the net, but I like simple things and this works in Django at least with the test suite:
session = self.client.session
session['request_token'] = {...}
session['access_token'] = {...}
session.save()
I faced the same problem and found the following solved my dilemma:
user = User.objects.get(username='lauren')
client = APIClient()
client.force_authenticate(user=user)
This was taken directly from the Django documentation:
http://www.django-rest-framework.org/api-guide/testing/#force_authenticateusernone-tokennone
Unfortunately it took a number of searches before getting to this point. I hope this saves someone else some time.

Setting HTTP_REFERER header in Django test

I'm working on a Django web application which (amongst other things) needs to handle transaction status info sent using a POST request.
In addition to the HTTP security supported by the payment gateway, my view checks request.META['HTTP_REFERER'] against an entry in settings.py to try to prevent funny business:
if request.META.get('HTTP_REFERER', '') != settings.PAYMENT_URL and not settings.DEBUG:
return HttpResponseForbidden('Incorrect source URL for updating payment status')
Now I'd like to work out how to test this behaviour.
I can generate a failure easily enough; HTTP_REFERER is (predictably) None with a normal page load:
def test_transaction_status_succeeds(self):
response = self.client.post(reverse('transaction_status'), { ... })
self.assertEqual(response.status_code, 403)
How, though, can I fake a successful submission? I've tried setting HTTP_REFERER in extra, e.g. self.client.post(..., extra={'HTTP_REFERER': 'http://foo/bar'}), but this isn't working; the view is apparently still seeing a blank header.
Does the test client even support custom headers? Is there a work-around if not? I'm using Django 1.1, and would prefer not to upgrade just yet if at all possible.
Almost right. It's actually:
def transaction_status_suceeds(self):
response = self.client.post(reverse('transaction_status'), {}, HTTP_REFERER='http://foo/bar')
I'd missed a ** (scatter operator / keyword argument unpacking operator / whatever) when reading the source of test/client.py; extra ends up being a dictionary of extra keyword arguments to the function itself.
You can pass HTTP headers to the constructor of Client:
from django.test import Client
from django.urls import reverse
client = Client(
HTTP_USER_AGENT='Mozilla/5.0',
HTTP_REFERER='http://www.google.com',
)
response1 = client.get(reverse('foo'))
response2 = client.get(reverse('bar'))
This way you don't need to pass headers every time you make a request.