Authorization helps control what users can do in an app. It keeps private parts safe and stops people from doing things they shouldn't.
0
0
Why authorization matters in Flask
Introduction
When you want only logged-in users to see their personal info.
When some users should edit content but others can only view it.
When you need to protect admin pages from regular users.
When you want to limit access to paid features.
When you want to keep sensitive data safe from unauthorized users.
Syntax
Flask
from flask import Flask, request, abort app = Flask(__name__) @app.route('/secret') def secret(): user_role = request.headers.get('Role') if user_role != 'admin': abort(403) # Forbidden return 'Welcome, admin!'
Use abort(403) to stop users without permission.
Check user roles or permissions before showing sensitive info.
Examples
Simple check to allow only admins.
Flask
if user_role == 'admin': return 'Access granted' else: abort(403)
Allow multiple roles to access a page.
Flask
allowed_roles = ['admin', 'editor'] if user_role in allowed_roles: return 'Access granted' else: abort(403)
Check if user is logged in and has permission.
Flask
from flask_login import current_user if not current_user.is_authenticated: abort(401) # Unauthorized if not current_user.has_permission('edit'): abort(403)
Sample Program
This Flask app has a dashboard route. It checks the user's role from the request headers. If the user is not an admin, it stops with a 403 error. Otherwise, it shows a welcome message.
Flask
from flask import Flask, request, abort app = Flask(__name__) @app.route('/dashboard') def dashboard(): user_role = request.headers.get('Role') if user_role != 'admin': abort(403) # Forbidden return 'Welcome to the admin dashboard!' if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
Authorization is different from authentication. Authentication checks who you are; authorization checks what you can do.
Always validate permissions on the server side to keep your app secure.
Summary
Authorization controls user access to parts of your app.
It protects sensitive data and features.
Use simple role checks and return errors if access is denied.