Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 828
user1187968 Avatar asked Feb 04 '23 05:02

user1187968


1 Answers

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
like image 108
davidism Avatar answered Feb 06 '23 19:02

davidism