Search code examples
pythondjangofacebook-graph-apifacebook-authenticationfacebook-permissions

Python: Check if Facebook user has granted access to my app. Fails with "HTTP Error 400: Bad Request"


I am trying to determine whether a user has granted access to my application and, if so, which permissions it has. This is NOT during the initial sign-up process, but later when I need to verify that the users hasn't removed permissions.

I run the following:

access_token = "users_access_token"; # saved when user signed up using FB
url = "https://graph.facebook.com/v2.0/me/permissions/?access_token="+access_token
response = urllib2.urlopen(url)

If the user has granted access then the response is a json string with permissions. This is the same that I see if I copy-paste the url into a browser.

However, if the user has NOT granted access (ie removed my app after initial sign-up) then I get an error: "HTTP Error 400: Bad Request". But, if I copy-paste the url into my browser then I get a json string with a proper error message: "The user has not authorized application..." (If I enter a wrong access_token in the browser url then I still get a proper error message "Malformed access token")

So, how can I gracefully check whether user has revoked access to my app? I don't want to get an exception, but rather a proper FB error response. It seems that this should be possible since it works when I copy-paste the url into the browser.

Note that I do not change my code at all. The only thing that changes is whether the user has granted access to the app (so it's not that the url is malformed.)


Solution

  • HTTPError itself contains the info you need, just do this:

    try:
        response = urllib2.urlopen(url)
    except urllib2.HTTPError as e:
        print(e.read())
    

    Then it will print out the error message:

    {"error":{"message":"Invalid OAuth access token.","type":"OAuthException","code":190}}