Reputation: 1619
I am trying to create a simple web application in order to better study how it works. The idea is that the user can login via twitter, and after that can access different functions on the front end. I can make the user authenticate via twitter, but I lost the session from one request to another. I use python3
flask
and flask-oauthlib
from flask import Flask, request, url_for, session, redirect, flash
from flask_cors import CORS
from flask_oauthlib.client import OAuth
app = Flask(__name__)
cors = CORS(app)
oauth = OAuth()
@app.route('/login')
def login():
callback_url = url_for('oauthorized', next=request.args.get('next'))
return twitter.authorize(callback=callback_url or request.referrer or None)
@app.route('/logout')
def logout():
session.pop('twitter_oauth', None)
return redirect(app.config['FRONT_END_URL'])
@app.route('/oauthorized')
def oauthorized():
frontend_url = app.config['FRONT_END_URL']
resp = twitter.authorized_response()
if resp is None:
flash('You denied the request to sign in.')
return redirect(frontend_url)
elif resp['screen_name'] not in allowed_twitter:
flash('You dont have premission')
return redirect(frontend_url)
access_token = resp['oauth_token']
session['access_token'] = access_token
session['screen_name'] = resp['screen_name']
session['twitter_token'] = (
resp['oauth_token'],
resp['oauth_token_secret']
)
flash('You were successfully logged in')
return redirect(frontend_url + "/accionDirecta")
@app.route('/test')
def test():
print(session) # Is always empty
access_token = session.get('access_token')
if access_token is None:
return("Not login")
else:
return("login")
The print(session)
inside oauthorized()
is correct, but when the user ,after login, make a get to /test
using jquery $ajax
, I the session is empty. Why?
Upvotes: 2
Views: 903
Reputation: 1619
The problem is in the $ajax get
. By default, ajax don't include your cookies, so you must force to use. In the $ajax
you must add:
crossDomain: true,
xhrFields: { withCredentials: true }
And this force to use your cookies.
Upvotes: 0