Authentication Patterns
Implement secure login systems, JWT, and OAuth in your Python web apps.
Secure Passwords
Never store passwords in plain text. Always use a strong hashing algorithm like bcrypt or Argon2.
import bcrypt
# Hashing
pw = "mypassword"
hashed = bcrypt.hashpw(pw.encode('utf-8'), bcrypt.gensalt())
# Verification
is_valid = bcrypt.checkpw(pw.encode('utf-8'), hashed)
# Hashing
pw = "mypassword"
hashed = bcrypt.hashpw(pw.encode('utf-8'), bcrypt.gensalt())
# Verification
is_valid = bcrypt.checkpw(pw.encode('utf-8'), hashed)
JSON Web Tokens (JWT)
JWTs are commonly used for stateless authentication in modern APIs.
import jwt
token = jwt.encode({"user_id": 1}, "secret_key", algorithm="HS256")
decoded = jwt.decode(token, "secret_key", algorithms=["HS256"])
token = jwt.encode({"user_id": 1}, "secret_key", algorithm="HS256")
decoded = jwt.decode(token, "secret_key", algorithms=["HS256"])
Best Practices
- Use HTTPS: Encrypt all data in transit.
- Short-lived tokens: Use refresh tokens and keep access tokens short-lived.
- Secrets management: Store keys in environment variables, never in code.
- Rate Limiting: Protect your auth endpoints from brute-force attacks.
โ Practice (30 minutes)
- Implement a simple login route in Flask or FastAPI.
- Hash the user's password before saving it to a dictionary (mock DB).
- Return a JWT token on successful login.
- Create a "protected" route that requires a valid JWT token in the header.