Last time I wrote about decorators, I explained their usefulness in rate limiting API endpoints. Today, I’m demonstrating another common use: authorization.
If you store the usernames of logged-in users in the session, your endpoint and decorator might look something like this:
@app.route("/get_secret", methods=["GET"]) @login_required def secret_info(): return "The truth is...I am Iron Man." def login_required(func): def login_wrapper(*args, **kwargs): if not flask.session.get("username"): return "Unauthorized", 401 return func(*args, **kwargs) return login_wrapper
That’s it! Just add @login_required to any endpoint at which you want to restrict access. It’s likely that you’ll want to do something more complex–maybe different users have different roles, or there are other attributes to check–but the concepts will be the same. There are good libraries for integrating HTTP Basic Authentication into your API which is another useful authentication method.
What authentication decorators do you use in your applications? Let me know in the comments below!
Ryan from The Bunch