Day 13 – Authentication & Authorization in Python Web Apps

Introduction

Imagine logging into Facebook and seeing someone else’s profile feed. Unthinkable, right? This nightmare is prevented by Authentication (who you are) and Authorization (what you can access). In Python Full Stack development, these two pillars ensure that applications remain secure, user-specific, and trustworthy.

In CuriosityTech’s Full Stack training, students often realize early on that writing code is easy, but writing secure code is essential. Authentication and Authorization are where this distinction becomes clear.


Authentication vs Authorization – The Core Difference

FeatureAuthenticationAuthorization
DefinitionVerifying user identity (login/signup)Granting permissions after login
Question Answered“Who are you?”“What are you allowed to do?”
ExampleEntering username & passwordAdmin panel accessible only to admins

💡 Think of Authentication as showing your ID at the gate, and Authorization as deciding which rooms you can enter once inside.


Implementing Authentication in Flask

Flask doesn’t provide authentication out of the box, but you can use Flask-Login.

Example: Flask Authentication

from flask import Flask, render_template, redirect, url_for, request

from flask_login import LoginManager, login_user, UserMixin, logout_user, login_required

app = Flask(__name__)

app.secret_key = ‘secret_key’

login_manager = LoginManager()

login_manager.init_app(app)

# Dummy user model

class User(UserMixin):

    def __init__(self, id):

        self.id = id

users = {‘admin’: User(‘admin’)}

@login_manager.user_loader

def load_user(user_id):

    return users.get(user_id)

@app.route(‘/login’, methods=[‘GET’, ‘POST’])

def login():

    if request.method == ‘POST’:

        username = request.form[‘username’]

        if username in users:

            login_user(users[username])

            return redirect(url_for(‘dashboard’))

    return render_template(‘login.html’)

@app.route(‘/dashboard’)

@login_required

def dashboard():

    return “Welcome to the Dashboard!”

@app.route(‘/logout’)

def logout():

    logout_user()

    return redirect(url_for(‘login’))

if __name__ == ‘__main__’:

    app.run(debug=True)

  • @login_required ensures only authenticated users can access certain routes.

  • Logout functionality ensures proper session management.


Authentication in Django – Built-In Power

Django comes with a powerful authentication system by default.

Example: Django Views with Authentication

from django.contrib.auth import authenticate, login, logout

from django.shortcuts import render, redirect

def login_view(request):

    if request.method == ‘POST’:

        username = request.POST[‘username’]

        password = request.POST[‘password’]

        user = authenticate(request, username=username, password=password)

        if user:

            login(request, user)

            return redirect(‘dashboard’)

    return render(request, ‘login.html’)

def logout_view(request):

    logout(request)

    return redirect(‘login’)

Django also offers permissions and groups, making role-based authorization seamless.


Role-Based Authorization Example

In Django REST Framework:

from rest_framework.permissions import BasePermission

class IsAdminUser(BasePermission):

    def has_permission(self, request, view):

        return request.user and request.user.is_staff

  • Attach this permission to an API view → only admins can access it.


Infographic Idea – “Layers of Web App Security”


Common Security Practices

  1. Never store plain-text passwords → always hash using bcrypt or Django’s password hasher.

  2. Use JWT (JSON Web Tokens) for stateless API authentication.

  3. Implement Multi-Factor Authentication (MFA) for sensitive applications.

  4. Use HTTPS & secure cookies for session management.


Real-World Case Study

When building a Python Full Stack e-commerce app, CuriosityTech learners faced a scenario:

  • Normal users could browse and purchase products.

  • Admins could add/delete products.

  • Vendors could manage their own listings.

This multi-role architecture was implemented using Django Groups & Permissions, a real example of authorization in action.


Abstract Diagram Idea – User Flow

User → Login → Token/Session → Role Mapping (Admin/User/Vendor) → Access to Resources

This flow can be visualized as a tree diagram branching into different access rights.


Conclusion

Authentication and Authorization are the guardians of your Python web apps. Without them, even the most beautiful frontend or optimized backend would be a sitting duck for attackers.

At CuriosityTech, these topics are emphasized not just as theory but as practical labs, where learners build login systems, role-based dashboards, and secure APIs. The lesson? A great developer doesn’t just build apps; they build trustworthy and secure apps.


Leave a Comment

Your email address will not be published. Required fields are marked *