MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Role-Based Access Control & Custom Decorators0%
Study Materials
FlaskProgress 0%
1.1What is Flask & WSGI Architecture1.2Virtual Environments & First Flask Application1.3Flask CLI & Environment Configuration
6.1Password Hashing with Werkzeug Security6.2User Session Management with Flask-Login6.3Role-Based Access Control & Custom Decorators
HomeTutorialsFlaskRole-Based Access Control & Custom Decorators
Modular Routing with Flask Blueprints

Role-Based Access Control & Custom Decorators

Beginner12 min read•Updated: 2026-09-16•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

While authentication answers "Who are you?", authorization answers "What are you allowed to do?". A student should not be able to access the admin portal, and an instructor should not be able to delete another instructor's course.

In Flask, Role-Based Access Control (RBAC) is cleanly implemented using Python Decorators combined with functools.wraps.


1. Defining User Roles on the Model

First, attach role attributes or an Enum to your User model:

1from flask_sqlalchemy import SQLAlchemy
2from flask_login import UserMixin
3 
4db = SQLAlchemy()
5 
6class User(UserMixin, db.Model):
7 __tablename__ = "users"
8 
9 id = db.Column(db.Integer, primary_key=True)
10 username = db.Column(db.String(50), unique=True, nullable=False)
11 role = db.Column(db.String(20), default="student", nullable=False) # 'student', 'instructor', 'admin'
12 
13 def is_admin(self):
14 return self.role == "admin"
15 
16 def is_instructor(self):
17 return self.role in ("instructor", "admin")

2. Crafting Custom Authorization Decorators

A custom decorator wraps a view function and checks permission conditions before invoking the original handler. Use functools.wraps to preserve function signatures and docstrings (essential for Flask routing!):

1from functools import wraps
2from flask import abort
3from flask_login import current_user
4 
5def admin_required(f):
6 @wraps(f)
7 def decorated_function(*args, **kwargs):
8 # 1. Check if user is logged in
9 if not current_user.is_authenticated:
10 abort(401) # Unauthorized
11
12 # 2. Check if user holds the admin role
13 if not current_user.is_admin():
14 abort(403) # Forbidden: authenticated, but insufficient privileges!
15
16 return f(*args, **kwargs)
17 return decorated_function

3. Parameterized Role Guard Decorator

For enterprise applications with multiple roles, create a reusable decorator that accepts permissible role names:

1def roles_required(*allowed_roles):
2 def decorator(f):
3 @wraps(f)
4 def decorated_function(*args, **kwargs):
5 if not current_user.is_authenticated:
6 abort(401)
7
8 if current_user.role not in allowed_roles:
9 abort(403, description=f"Access requires one of these roles: {allowed_roles}")
10
11 return f(*args, **kwargs)
12 return decorated_function
13 return decorator

4. Applying Decorators to Protected Routes

[!IMPORTANT] Decorator Order Matters: The @app.route() decorator must always be on the outside (top), followed by authentication/authorization decorators:
1from flask import Flask, render_template
2 
3app = Flask(__name__)
4 
5# Only accessible by system administrators
6@app.route("/admin/dashboard")
7@admin_required
8def admin_panel():
9 return render_template("admin/dashboard.html")
10 
11# Accessible by instructors and admins
12@app.route("/courses/create", methods=["GET", "POST"])
13@roles_required("instructor", "admin")
14def create_course():
15 return render_template("instructor/create_course.html")

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What HTTP status code should be returned when an authenticated user attempts to access a resource they do not have permissions for?
Question 2
Why is @wraps(f) from functools required when writing custom Flask view decorators?
Question 3
What is the correct ordering when applying @app.route and a custom permission decorator?
Question 4
What does calling abort(403) do inside a decorator?
Question 5
How can UI navigation links be conditionally hidden from non-admin users in Jinja2 templates?
Next Lesson

Modular Routing with Flask Blueprints

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
User Session Management with Flask-LoginModular Routing with Flask Blueprints

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Flask with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext