Search code examples
pythonflaskauth0flask-restful

Use Auth0 decorator with Flask-RESTful resource


I need to use Auth0 for my Flask-RESTful app. Auth0 has an example using the requires_auth decorator on a view function.

@app.route('/secured/ping')
@cross_origin(headers=['Content-Type', 'Authorization'])
@requires_auth
def securedPing():
    return "All good. You only get this message if you're authenticated"

With Flask-RESTful I use add_resource with a Resource class, not app.route with a view function. How do I apply requires_auth to Version?

app = Flask(__name__)
API = Api(app)
CORS = CORS(app, resources={r'/api/*': {'origins': '*'}})
API.add_resource(Version, '/api/v1')

Solution

  • The Flask-Restful docs describe how to specify decorators for a resource.

    There is a property on the Resource class called method_decorators. You can subclass the Resource and add your own decorators that will be added to all method functions in resource.

    class AuthResource(Resource):
        method_decorators = [requires_auth]
    
    # inherit AuthResource instead of Resource to define Version