A
AiTechWorlds
AiTechWorlds
Authentication factors, RBAC implementation, JWT best practices, password hashing (Argon2), and audit log formats.
AAA is the foundational framework for controlling access to systems and resources:
| Pillar | Question | Example |
|---|---|---|
| Authentication (AuthN) | Who are you? | Login with username + password + MFA |
| Authorization (AuthZ) | What can you do? | Admin can delete users; user can only view own data |
| Accounting (Audit) | What did you do? | Log every action for compliance and forensics |
| Factor | Type | Examples |
|---|---|---|
| Knowledge | Something you know | Password, PIN, security question |
| Possession | Something you have | TOTP app, hardware key (YubiKey), SMS OTP |
| Inherence | Something you are | Fingerprint, face ID, retina scan |
| Location | Somewhere you are | IP geolocation, trusted network |
| Behavior | Something you do | Typing pattern, mouse movement |
| Method | Security Level | UX | Use Case |
|---|---|---|---|
| Password | Low (if weak) | High | Universal baseline |
| Password + TOTP | Medium-High | Medium | Apps with MFA |
| Hardware key (FIDO2) | Very high | High | High-security accounts |
| SSO (SAML/OIDC) | High | Very high | Enterprise |
| Magic link (email) | Medium | Very high | Low-friction apps |
| Biometric | High | Very high | Mobile apps |
| Certificate-based | Very high | Low | Server-to-server, VPN |
| Passkey (WebAuthn) | Very high | High | Modern web/mobile |
| Algorithm | Recommended? | Notes |
|---|---|---|
| bcrypt | Yes | Adaptive cost, widely supported |
| scrypt | Yes | Memory-hard, better than bcrypt |
| Argon2id | Best choice | Winner of Password Hashing Competition |
| SHA-256 | NO | Too fast, brute-forceable in seconds |
| MD5 | NEVER | Completely broken |
| SHA-1 | NEVER | Broken |
# Argon2 in Python
from argon2 import PasswordHasher
ph = PasswordHasher(
time_cost=2, # iterations
memory_cost=65536, # 64 MB
parallelism=2
)
hash = ph.hash("user_password")
# $argon2id$v=19$m=65536,t=2,p=2$...
# Verify
try:
ph.verify(hash, "user_password") # True
except Exception:
# Invalid password
passβ Minimum 8 characters (12+ recommended)
β Allow all printable ASCII + Unicode
β Check against known breached passwords (Have I Been Pwned)
β No mandatory periodic rotation (promotes weak passwords)
β No complexity rules (uppercase + special char requirements)
β No password hints
β Allow password managers (no paste blocking)| Model | How It Works | Use Case |
|---|---|---|
| DAC (Discretionary) | Owner grants permissions | File systems |
| MAC (Mandatory) | System-enforced labels (secret, top-secret) | Military, government |
| RBAC (Role-Based) | Permissions assigned to roles | Most enterprise apps |
| ABAC (Attribute-Based) | Rules based on attributes of user, resource, environment | Complex fine-grained access |
| ReBAC (Relationship-Based) | Access based on relationships (Google Zanzibar) | Social networks, Google Drive |
# Roles and permissions table
PERMISSIONS = {
'admin': {'users:read', 'users:write', 'users:delete', 'reports:read'},
'editor': {'posts:read', 'posts:write', 'posts:delete'},
'viewer': {'posts:read', 'reports:read'},
}
def has_permission(user_role: str, required_permission: str) -> bool:
return required_permission in PERMISSIONS.get(user_role, set())
# Middleware
def require_permission(permission: str):
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
if not has_permission(current_user.role, permission):
abort(403)
return f(*args, **kwargs)
return wrapper
return decorator
@app.route('/api/users', methods=['DELETE'])
@require_permission('users:delete')
def delete_user():
passheader.payload.signature
Header: { "alg": "HS256", "typ": "JWT" }
Payload: { "sub": "42", "role": "admin", "exp": 1735689600 }
Signature: HMACSHA256(base64(header) + "." + base64(payload), secret)import jwt
from datetime import datetime, timedelta
# Issue token
payload = {
"sub": str(user.id),
"role": user.role,
"iat": datetime.utcnow(),
"exp": datetime.utcnow() + timedelta(hours=1),
}
token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
# Verify token
try:
data = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
user_id = data["sub"]
except jwt.ExpiredSignatureError:
# Token expired β require re-login
except jwt.InvalidTokenError:
# Invalid token β rejectJWT Security Rules:
exp, iss, and aud claimshttpOnly cookie, not localStorageAuthentication events:
- Login success/failure (with IP, timestamp, device)
- MFA success/failure
- Password change/reset
- Account lockout
Authorization events:
- Access denied (403)
- Role changes
- Permission grants/revocations
Resource access:
- Read/write/delete on sensitive data
- Export operations
- API calls by service accounts
Admin actions:
- Configuration changes
- User management
- System access{
"event_id": "evt_01HZ...",
"timestamp": "2026-01-15T10:23:45.123Z",
"event_type": "auth.login_success",
"actor": {
"user_id": "usr_42",
"email": "alice@example.com",
"ip": "203.0.113.50",
"user_agent": "Mozilla/5.0..."
},
"resource": { "type": "session", "id": "ses_789" },
"outcome": "success",
"metadata": { "mfa_method": "totp" }
}Download AAA: Authentication, Authorization & Audit
Get this note + 100s more free on Telegram
Get more notes like this daily on Telegram!
Free study notes, cheat sheets & AI tips
Join AiTechWorlds on Telegram and get daily AI tips, prompt engineering templates, coding resources, and exclusive content β 100% free!
No spam. Leave anytime.