28 / 65 · 14 API Testing Fundamentals · Authentication Testing← prev⊞ allnext →☰ Read as one page
4.4Authorization Testing (RBAC)
Authentication verifies identity. Authorization verifies permissions. Test that users can only access what their role allows.
@pytest.mark.parametrize("role,endpoint,method,expected", [
("admin", "/users", "GET", 200),
("admin", "/users", "POST", 201),
("admin", "/users/1", "DELETE", 204),
("viewer", "/users", "GET", 200),
("viewer", "/users", "POST", 403),
("viewer", "/users/1", "DELETE", 403),
("editor", "/users", "GET", 200),
("editor", "/users", "POST", 201),
("editor", "/users/1", "DELETE", 403),
])
def test_role_based_access(base_url, get_token_for_role, role, endpoint, method, expected):
token = get_token_for_role(role)
r = requests.request(method, f"{base_url}{endpoint}",
headers={"Authorization": f"Bearer {token}"},
json={"name": "Test", "email": f"{role}@test.com"} if method == "POST" else None)
assert r.status_code == expected, \
f"Role {role} got {r.status_code} on {method} {endpoint}, expected {expected}"
Horizontal Authorization (IDOR)
Users should not access other users' data:
def test_user_cannot_access_other_users_data(base_url, user_a_token, user_b_id):
"""User A should not be able to view User B's private data."""
r = requests.get(f"{base_url}/users/{user_b_id}/private-data",
headers={"Authorization": f"Bearer {user_a_token}"})
assert r.status_code in (403, 404) # Either forbidden or not found