corydolphin / flask-cors

Cross Origin Resource Sharing ( CORS ) support for Flask
https://flask-cors.corydolphin.com/
MIT License
877 stars 137 forks source link

flask-cors + flask-login + vuejs #249

Closed juli-vert closed 5 years ago

juli-vert commented 5 years ago

Hi there,

I'm trying to use this stack to build an application up, but unable to mix them up properly.

When requesting the login directly to the backend it works quite fine (despite of some extra cookies being set), but when adding CORS due the call from the VueJS application, the drama starts. CORS is configured like this:

CORS(app, supports_credentials=True, resources={r'/*': {'origins': 'http://localhost:8080'}}) being http://localhost:8080 the vuejs application.

I do call the login view from vuejs like this: login(payload) { const path = 'http://localhost:9123/login'; axios.post(path, querystring.stringify(payload), { headers: { 'Content-type': 'application/x-www-form-urlencoded' } }) .then((res) => { this.map = res.data; }) .catch((error) => { this.console.log(error); }); },

being localhost:9123 the flask application. the backend is catching it right here: @app.route('/login', methods=['GET', 'POST']) @cross_origin() def login(): for k in request.form.keys(): print("Key {0}".format(k))

global _db
if request.method == 'GET':
    return render_template('login.html')
data = request.form
name = data['name']
uid = _db.getUserByName(name)
if data['password'] == _db.getUserPassword(uid):
    user = User()
    user.id = name
    user.uid = uid
    flask_login.login_user(user)
    return redirect(url_for('getMap'))
return 'Bad login request'

It does work because it performs the redirection to "getMap", but then is when the weird thing happens, instead of calling the flask-login.user_loader it does call the request_loader instead with an empty request (the parameters are not passed thru, but still figuring out why it's not using the user_loader once the user is actually logged in).

I've been checking header back and forth and I saw the Cookie is not included when CORS requests happen. Being totally honest, I don't know whether the problem is in flask-cors and the Allow-Credentials, in vuejs not storing the cookie or so.

Any idea is appreciated

juli-vert commented 5 years ago

Hi there,

I found the issue and it's nothing related to flask-cors, not even flask-login or vuejs, it's how the engine uses the 302 redirect. Some of them change the method from "any" to "get" making the request body empty, so when it's reviewed by the login component it does have the original request parameters.

Changing the redirect code to 307 did the job.

Closing