Flask-cors wrapper not working when jwt auth wrapp

2019-06-23 08:34发布

问题:

I'm trying to build a api site using Flask, and I am using Flask-jwt to provide token authorization.
The authorizaiton works fine if I do CORS in Apache ( using mod_headers to add Allow-Access headers, like this

Header set Access-Control-Allow-Origin "*"

However, I want to have more detailed access control instead of just using wildcard. and I looked at flask-cors, which is a nice wrapper to check origin and send the header. And now my route looks like this (and no header manipulation in apache settings)

@app.route('/protected/place')
@cross_origin(headers=['Content-Type']) # Send Access-Control-Allow-Headers
@jwt_required()
def my_view_func():
    do something

But now I will not get the Access-Control headers response from the server if I make the http request from javascript. (However, if I manually post, like doing curl, i can still see the cross origin plugin working and the Access control headers)

When I remove the @jwt_required wrapper, the cross_origin wrapper functions fine and it will give me response. when the jwt_required wrapper is applied, no response can be seen from the server.

I'm debugging my client page with chrome. BTW

I tried to change the order of the wrappers, but it doesn't help.

Is it possible that, if the authentication fails, the cross_origin wrapper will not send the Access Control headers?

the source code of the two wrappers :
flask-jwt:
https://github.com/mattupstate/flask-jwt/blob/master/flask_jwt/init.py
flask-cors:
https://github.com/wcdolphin/flask-cors/blob/master/flask_cors.py

回答1:

After struggling for many hours, I finally found the problem. Hope it helps others who encouter the same problem.
Just need to include Authorization in "headers" argument (which sets the Access-Control-Allow-Headers field) when authentication is needed.
Like this
@app.route('/protected/place') @cross_origin(headers=['Content-Type','Authorization']) # Send Access-Control-Allow-Headers @jwt_required() def my_view_func(): do something