question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Using flask-cors with flask-restful and @before_request decorator for jwt auth

See original GitHub issue

I’m trying to use flask-cors for the development configuration for a flask-restful api, simplified below:

import config

from flask import Flask, request
from flask_restful import Api, Resource
from flask_cors import CORS

app = Flask(__name__)
app.config.from_object('config.DevelopmentConfig')
api = Api(app)
if app.config['CORS_ENABLED'] is True:
    CORS(app, origins="http://127.0.0.1:8080", allow_headers=[
        "Content-Type", "Authorization", "Access-Control-Allow-Credentials"],
        supports_credentials=True)


@app.before_request
def authorize_token():
    if request.endpoint != 'token':
        try:
            authorize_jwt(request)
        except Exception as e:
            return "401 Unauthorized\n{}\n\n".format(e), 401


class GetToken(Resource):
    def post(self):
        token = generate_jwt()
        return token       # token sent to client to return in subsequent requests in Authorization header


# requires authentication through before_request decorator
class Test(Resource):
    def get(self):
        return {"test": "testing"}


api.add_resource(GetToken, '/token', endpoint='token')
api.add_resource(Test, '/test', endpoint='test')

if __name__ == '__main__':
    app.run()

But whatever I try I always get the error ‘Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.’

Without the JWT auth piece, everything else works fine. (And the JWT auth works fine without flask-cors.) Seems like the hangup is something with using flask-cors with the before_request decorator (?).

Any suggestions?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:11 (3 by maintainers)

github_iconTop GitHub Comments

20reactions
gwvtcommented, Apr 25, 2017

Right. The test_headers() function assigns the value of the Authorization header to auth_header, while the test() function that is ‘protected’ by the before_request decorator and authorize_token function does not.

I figured out that the problem was that the authorize_token function requires a test to run the function only on the passed GET method, not the preflight request, so this now works:

@app.before_request
def authorize_token():
    if request.endpoint == 'test':
        try:
            if request.method != 'OPTIONS':  # <-- required
                auth_header = request.headers.get("Authorization")
                if "Bearer" in auth_header:
                    token = auth_header.split(' ')[1]
                    if token != '12345678':
                        raise ValueError('Authorization failed.')
        except Exception as e:
            return "401 Unauthorized\n{}\n\n".format(e), 401
1reaction
gemisolocnvcommented, Jan 14, 2022

You are my savior @gwvt . Thank you very much

Read more comments on GitHub >

github_iconTop Results From Across the Web

Using authentication decorators in Flask - CircleCI
In this tutorial, we have learned how to create custom authentication decorators and use them in our API to receive and decode JWT...
Read more >
Part 4: JWT Authentication, Decorators and Blacklisting Tokens
The process to create a custom decorator that only allows access to users with a valid JWT is covered in-depth. How to send...
Read more >
Newest 'flask-jwt-extended' Questions - Page 2 - Stack Overflow
I'm using flask-jwt-extended library for my authentication, everything works but I want to ... How to choose which decorator to apply based on...
Read more >
Flask-CORS — Flask-Cors 3.0.10 documentation
It allows parameterization of all CORS headers on a per-resource level. The package also contains a decorator, for those who prefer this approach....
Read more >
Fast way to enable CORS in Flask servers - DEV Community ‍ ‍
To install Flask-CORS using pip: pip install flask-cors. In an example of a POST request, simply add the decorator @cross_origin in the ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found