Login

Manual CSRF check for Django Facebook canvas applications

Author:
krvss
Posted:
September 5, 2011
Language:
Python
Version:
1.3
Tags:
django python post facebook csrf fb
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

Comments

Please login first before commenting.