Skip to main content

Lesson 10 of 10

Practice & Quiz - Authentication & Authorization

Test your auth knowledge: JWT security, OAuth 2.0 flows, RBAC vs ABAC, MFA, and zero trust with a practical JWT attack/defense exercise and 5 quiz questions.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical Exercise - JWT Security: Attacks & Defenses

Practical Exercise - JWT Security: Attacks & Defenses
import jwt, json, base64, hmac, hashlib, time, secrets
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization

# ─── JWT Structure ─────────────────────────────────────────────
# JWT = base64url(header) . base64url(payload) . base64url(signature)
# Header and payload are NOT encrypted by default - only signed

SECRET_KEY = secrets.token_hex(32)   # HS256 secret
ALGORITHM  = 'HS256'

def create_jwt(user_id: int, role: str, expiry_minutes: int = 15) -> str:
    payload = {
        'sub': str(user_id),
        'role': role,
        'iat': int(time.time()),
        'exp': int(time.time()) + (expiry_minutes * 60),
        'jti': secrets.token_hex(16),   # JWT ID - prevents replay attacks
    }
    return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)

def verify_jwt(token: str) -> dict:
    """Secure JWT verification - explicit algorithm, all claims validated."""
    try:
        payload = jwt.decode(
            token,
            SECRET_KEY,
            algorithms=['HS256'],  # NEVER use algorithms=jwt.get_unverified_header(token)['alg']
            options={
                'verify_exp': True,
                'verify_iat': True,
                'require': ['sub', 'exp', 'iat', 'jti'],
            }
        )
        return payload
    except jwt.ExpiredSignatureError:
        raise ValueError('Token expired - user must re-authenticate')
    except jwt.InvalidTokenError as e:
        raise ValueError(f'Invalid token: {e}')

# ─── Common JWT Attacks ────────────────────────────────────────
def demonstrate_jwt_attacks():
    token = create_jwt(user_id=42, role='user')
    header, payload_b64, signature = token.split('.')

    print('=== JWT Attack Demonstrations ===')

    # Attack 1: Algorithm Confusion - none algorithm
    # Vulnerable libraries accept alg:none (no signature verification)
    fake_header = base64.urlsafe_b64encode(
        json.dumps({'alg': 'none', 'typ': 'JWT'}).encode()
    ).rstrip(b'=').decode()
    fake_payload = base64.urlsafe_b64encode(
        json.dumps({'sub': '1', 'role': 'admin', 'exp': int(time.time()) + 3600}).encode()
    ).rstrip(b'=').decode()
    none_token = f'{fake_header}.{fake_payload}.'
    print(f'[Attack 1] None algorithm token: {none_token[:80]}...')
    # Secure library: raises jwt.exceptions.InvalidAlgorithmError

    # Attack 2: Payload tampering (changes role from user to admin)
    # Since header+payload are base64, attacker can decode, modify, re-encode
    decoded_payload = json.loads(base64.urlsafe_b64decode(payload_b64 + '=='))
    decoded_payload['role'] = 'admin'  # privilege escalation attempt
    tampered_payload = base64.urlsafe_b64encode(
        json.dumps(decoded_payload).encode()
    ).rstrip(b'=').decode()
    tampered_token = f'{header}.{tampered_payload}.{signature}'
    print(f'[Attack 2] Tampered payload (role→admin): verification should fail')
    try:
        verify_jwt(tampered_token)
        print('  VULNERABLE: tampered token accepted!')
    except ValueError as e:
        print(f'  SECURE: {e}')

    # Attack 3: JWT secret brute force
    # Short secrets are vulnerable to offline brute force
    print('[Attack 3] Brute force test: weak secret "password123"')
    weak_token = jwt.encode({'sub': '1', 'exp': time.time() + 3600}, 'password123', algorithm='HS256')
    for candidate in ['password', 'password123', 'secret', '12345']:
        try:
            jwt.decode(weak_token, candidate, algorithms=['HS256'])
            print(f'  CRACKED! Secret is: {candidate}')
            break
        except jwt.InvalidSignatureError:
            pass

demonstrate_jwt_attacks()

# ─── RBAC Implementation ──────────────────────────────────────
ROLES_PERMISSIONS = {
    'admin':    {'read', 'write', 'delete', 'manage_users', 'view_audit'},
    'editor':   {'read', 'write'},
    'viewer':   {'read'},
    'auditor':  {'read', 'view_audit'},
}

def check_permission(user_role: str, required_permission: str) -> bool:
    return required_permission in ROLES_PERMISSIONS.get(user_role, set())

# Test RBAC
for role in ['admin', 'editor', 'viewer']:
    can_delete = check_permission(role, 'delete')
    print(f'{role} can delete: {can_delete}')

Module Quiz

Module Quiz
Question 1 of 5

What is the 'algorithm confusion' JWT attack and how do you prevent it?

Tip

Tip

Practice Practice Quiz Authentication Authorization in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).

Practice Task

Note

Practice Task - (1) Write a working example of Practice Quiz Authentication Authorization from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Practice Quiz Authentication Authorization is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/10 done