Note that there are some explanatory texts on larger screens.

plurals
  1. POFacebook app: Access token expires with XMLHttpRequest?
    text
    copied!<p>Edit 2: When the token fails oauth gives <code>{"error":{"message":"This authorization code has been used.","type":"OAuthException","code":100}}</code></p> <p>Edit: This is also occasionally occurring during normal page navigation.</p> <p>My facebook user access tokens are expiring the second time I use XMLHttpRequest. The access tokens are not expiring when I navigate within the app otherwise. I am using a python Flask app with Heroku. When a page loads it gets the token with <code>get_token</code>:</p> <pre><code>def fbapi_get_string(path, domain=u'graph', params=None, access_token=None, encode_func=urllib.urlencode): """Make an API call""" if not params: params = {} params[u'method'] = u'GET' if access_token: params[u'access_token'] = access_token for k, v in params.iteritems(): if hasattr(v, 'encode'): params[k] = v.encode('utf-8') url = u'https://' + domain + u'.facebook.com' + path params_encoded = encode_func(params) url = url + params_encoded result = requests.get(url).content return result def fbapi_auth(code): params = {'client_id': app.config['FB_APP_ID'], 'redirect_uri': request.url, 'client_secret': app.config['FB_APP_SECRET'], 'code': code} result = fbapi_get_string(path=u"/oauth/access_token?", params=params, encode_func=simple_dict_serialisation) print result pairs = result.split("&amp;", 1) result_dict = {} for pair in pairs: (key, value) = pair.split("=") result_dict[key] = value return (result_dict["access_token"], result_dict["expires"]) def get_token(): if request.args.get('code', None): return fbapi_auth(request.args.get('code'))[0] cookie_key = 'fbsr_{0}'.format(FB_APP_ID) if cookie_key in request.cookies: c = request.cookies.get(cookie_key) encoded_data = c.split('.', 2) sig = encoded_data[0] data = json.loads(urlsafe_b64decode(str(encoded_data[1]) + (64-len(encoded_data[1])%64)*"=")) if not data['algorithm'].upper() == 'HMAC-SHA256': raise ValueError('unknown algorithm {0}'.format(data['algorithm'])) h = hmac.new(FB_APP_SECRET, digestmod=hashlib.sha256) h.update(encoded_data[1]) expected_sig = urlsafe_b64encode(h.digest()).replace('=', '') if sig != expected_sig: raise ValueError('bad signature') params = { 'client_id': FB_APP_ID, 'client_secret': FB_APP_SECRET, 'redirect_uri': '', 'code': data['code'] } from urlparse import parse_qs r = requests.get('https://graph.facebook.com/oauth/access_token', params=params) token = parse_qs(r.content).get('access_token') return token </code></pre> <p><code>None</code> is returned from <code>get_token</code> when there is no token. When <code>None</code> is returned or if the user has not given the appropriate permissions <code>redirect(oauthLoginUrl())</code> is called:</p> <pre><code>def oauthLoginUrl(): fb_login_uri = ("https://www.facebook.com/dialog/oauth" "?client_id=%s&amp;redirect_uri=%s" % (app.config['FB_APP_ID'], request.url)) if app.config['FBAPI_SCOPE']: fb_login_uri += "&amp;scope=%s" % ",".join(app.config['FBAPI_SCOPE']) return fb_login_uri </code></pre> <p>This seems to work for the pages navigated in the browser but for XMLHttpRequests the token expires. The response for these Ajax requests gives an error code instead of the redirect when the token has expired. The user is told that their session has expired and is asked to refresh the page.</p> <p>Does anyone have any ideas about why the tokens are expiring with Ajax? </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload