Login

Manual CSRF check for Django Facebook canvas applications

Author:
krvss
Posted:
September 5, 2011
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

The way to manually control CSRF correctness for FB applications. Automatic check cannot be used because FB does POST on your canvas URL when initializing your application without CSRF token. If you still want to use Django CSRF stuff do manual checks.

You only need to perform manual check when there is no correct signed_request present in your request - correct request means you really deal with FB. Use facebook_csrf_check to verify POST requests when signed_request is absent.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from django.views.decorators.csrf import csrf_view_exempt
from django.middleware.csrf import CsrfViewMiddleware
 
# Function to check CSRF on demand (use {% csrf_token %} in your forms as usual)
def facebook_csrf_check(request):
    return CsrfViewMiddleware().process_view(request, facebook_csrf_check, None, None) == None

# Your canvas view
@csrf_view_exempt
def facebook_canvas(request):
 
    if is_valid_access_token(request): # check whether a correct access_token presents
        # do something
 
    print 'CSRF ' + str(facebook_csrf_check(request)) # facebook_csrf_check == True means CSRF is OK

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 3 weeks ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.