LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
Python

Python - Authentication & Security

Secure Python web applications by hashing passwords with bcrypt, issuing signed JSON Web Tokens (JWT) for stateless sessions, and configuring strict CORS policies.

Authentication & Security in Python – Securing Web Applications with JWT, Password Hashing, and CORS

Quick Answer: Secure Python web applications by hashing passwords with bcrypt, issuing signed JSON Web Tokens (JWT) for stateless sessions, and configuring strict CORS policies.

Imagine Priya manages a cooperative member portal in Bengaluru with 10,000 active users logging in every day.

If passwords are stored in plain text or login tokens can be easily forged, malicious actors can breach user accounts.

How do we authenticate users securely and protect endpoints from unauthorized access?

1. Why Do We Need Secure Authentication and Security Protocols?

The problem without secure authentication

Storing user passwords in plain text or returning unencrypted session flags allows anyone who intercepts network traffic to steal user accounts instantly.

Example 1: Insecure credential check without hashing

This insecure approach compares raw strings and exposes passwords in database leaks.

def login_user(input_password, stored_password):
    if input_password == stored_password:
        return "Login Success"
    return "Invalid Password"

Expected output

Login Success

This code runs, but it creates critical security vulnerabilities.

  1. Database compromises immediately reveal all user passwords in plain text.
  2. No expiration mechanism for active user sessions.
  3. Lack of cross-origin resource controls lets unauthorized external sites invoke APIs.

We need robust password hashing, cryptographically signed tokens, and explicit CORS permissions.

The solution: Hashing, JWT, and CORS

Hashing = converting plaintext into an irreversible cryptographic string.

JWT = a compact, URL-safe token format used to securely transmit claims between parties.

CORS = an HTTP-header mechanism that controls which external domains can access server resources.

Secure Authentication Flow in Priya's Portal
From user login to token verification and protected resource access
1. User Login Request Sends username and password
Verify & Sign
2. Password Hash Bcrypt verification
3. Issue JWT Signed token returned
4. Protected API Bearer token validated
Client Request Active Step Secure Token

Figure 1: Complete authentication lifecycle incorporating password hashing and JWT validation.

2. Implementing Password Hashing with Passlib and Bcrypt

Password hashing ensures that even if database tables are leaked, original passwords cannot be easily recovered.

Let us write a complete runnable Python example demonstrating password hashing and verification using passlib.

Example 2: Secure password hashing and verification

This code uses bcrypt to securely hash and verify user passwords.

from passlib.context import CryptContext

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def get_password_hash(password):
    return pwd_context.hash(password)

def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)

if __name__ == "__main__":
    my_password = "BengaluruSecure@123"
    hashed = get_password_hash(my_password)
    print("Hashed Password:", hashed[:20] + "...")
    
    is_valid = verify_password("BengaluruSecure@123", hashed)
    print("Password Match:", is_valid)

Expected output

Hashed Password: $2b$12$...
Password Match: True

Notice how CryptContext automatically handles cryptographic salting and hashing securely.

3. Issuing and Verifying JSON Web Tokens (JWT)

Once a user authenticates successfully, we issue a signed token so they do not need to resend credentials on every request.

Example 3: Creating and decoding JWT tokens

This code generates a signed JWT payload with an expiration time.

import jwt
from datetime import datetime, timedelta

SECRET_KEY = "super-secret-key-for-upgradix-portal"
ALGORITHM = "HS256"

def create_access_token(data: dict):
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(minutes=30)
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)

if __name__ == "__main__":
    token = create_access_token({"sub": "priya@portal.com"})
    print("Generated Token Length:", len(token))
    
    payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    print("Decoded Subject:", payload.get("sub"))

Expected output

Generated Token Length: 144
Decoded Subject: priya@portal.com

If the secret key changes or the token expires, jwt.decode() raises an exception to reject unauthorized access.

4. Managing CORS in FastAPI

Cross-Origin Resource Sharing (CORS) restricts web browsers from making requests to a different domain unless explicitly allowed.

Example 4: Configuring CORS middleware in FastAPI

This code enables secure cross-origin communication for authorized frontend applications.

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
    "http://localhost:3000",
    "https://portal.shrashstudio.com"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# @app.get("/api/data")
# def get_data():
#     return {"status": "secure"}

Expected output

CORS Middleware Configured Successfully
Comparing Insecure vs Secure Web Application Design
Insecure Approach Secure Production Approach
Plain text password storage Bcrypt hashed passwords with salts
Persistent server sessions or no expiration Short-lived signed JWT tokens
Allow-all CORS headers (*) Explicit whitelist of trusted frontend domains

The important terms to remember

  • Bcrypt = a secure password hashing algorithm designed to resist brute-force attacks.
  • JWT = JSON Web Token used for stateless, authenticated client-server communication.
  • CORS = browser security policy controlling cross-origin resource sharing.

Design tip: Never hardcode production secret keys in your source code; load them securely from environment variables.

5. Common Mistakes to Avoid

1. Storing JWT tokens in local storage for high-security sites

Storing sensitive access tokens in browser localStorage leaves them vulnerable to Cross-Site Scripting (XSS) attacks.

Better approach: Store sensitive authentication tokens in HTTP-only, secure cookies whenever possible.

6. Interview Questions & Answers

Question 1: Why should we hash passwords instead of encrypting them?

What the interviewer expects: A clear distinction between encryption (reversible) and hashing (one-way).

Strong answer: "Encryption is two-way, meaning any valid key can decrypt the data back to plaintext. Hashing is a one-way mathematical transformation. We hash passwords so that even if our database is compromised, the original passwords cannot be decrypted."

What interviewers expect at different levels

  • Junior developer: Knows how to hash passwords with bcrypt and generate basic JWT tokens.
  • Senior developer: Understands token revocation strategies, token expiration, and secure cookie storage.
  • Technical architect: Designs robust OAuth2/OIDC identity providers with strict token scopes and CORS boundaries.

7. Practice Exercises

Beginner: Password Validation

Write a Python function that verifies if an entered password meets minimum length and character complexity requirements before hashing.

Expected result: Returns boolean status indicating password strength.

Intermediate: Custom JWT Claims

Add user role information (e.g., "role": "admin") inside the JWT payload and verify it on protected routes.

Hint: Include role-checking logic in your FastAPI dependency injector.

8. Frequently Asked Questions (FAQ)

Can JWT tokens be tampered with by clients?

No. If a client alters any part of the JWT payload, the cryptographic signature verification will fail.

What is the purpose of the exp claim in a JWT?

The exp (expiration time) claim ensures that the token becomes invalid after a specific duration.

9. Next Steps

Now that you have mastered authentication and security, you are ready to explore automated testing and containerization in the next section.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.