Files
novalon-manage-system/e2e_tests/debug_security.py
T

93 lines
3.9 KiB
Python

"""
测试Spring Security配置的简单验证脚本
"""
import httpx
async def test_security_config():
"""测试不同端点的认证行为"""
base_url = "http://localhost:8080"
print("=" * 60)
print("测试Spring Security配置")
print("=" * 60)
# 测试1: 无认证访问auth端点
print("\n1. 测试 /api/auth/login (无认证)")
async with httpx.AsyncClient() as client:
response = await client.post(
f"{base_url}/api/auth/login",
json={"username": "admin", "password": "admin123"}
)
print(f" 状态码: {response.status_code}")
print(f" 预期: 200, 实际: {response.status_code}")
print(f" 结果: {'✅ 通过' if response.status_code == 200 else '❌ 失败'}")
# 测试2: 无认证访问users端点
print("\n2. 测试 /api/users (无认证)")
async with httpx.AsyncClient() as client:
response = await client.get(f"{base_url}/api/users")
print(f" 状态码: {response.status_code}")
print(f" 预期: 200 (permitAll), 实际: {response.status_code}")
print(f" 结果: {'✅ 通过' if response.status_code == 200 else '❌ 失败'}")
# 测试3: 无认证访问特定用户
print("\n3. 测试 /api/users/1 (无认证)")
async with httpx.AsyncClient() as client:
response = await client.get(f"{base_url}/api/users/1")
print(f" 状态码: {response.status_code}")
print(f" 预期: 200 (permitAll), 实际: {response.status_code}")
print(f" 结果: {'✅ 通过' if response.status_code == 200 else '❌ 失败'}")
# 测试4: 使用Bearer Token访问users端点
print("\n4. 测试 /api/users (Bearer Token)")
async with httpx.AsyncClient() as client:
# 先获取token
login_response = await client.post(
f"{base_url}/api/auth/login",
json={"username": "admin", "password": "admin123"}
)
if login_response.status_code == 200:
token = login_response.json().get("token")
response = await client.get(
f"{base_url}/api/users",
headers={"Authorization": f"Bearer {token}"}
)
print(f" 状态码: {response.status_code}")
print(f" 预期: 200, 实际: {response.status_code}")
print(f" 结果: {'✅ 通过' if response.status_code == 200 else '❌ 失败'}")
else:
print(" 无法获取token,跳过此测试")
# 测试5: 使用无效Bearer Token访问users端点
print("\n5. 测试 /api/users (无效Bearer Token)")
async with httpx.AsyncClient() as client:
response = await client.get(
f"{base_url}/api/users",
headers={"Authorization": "Bearer invalid_token"}
)
print(f" 状态码: {response.status_code}")
print(f" 预期: 401 (无效token), 实际: {response.status_code}")
print(f" 结果: {'✅ 通过' if response.status_code == 401 else '❌ 失败'}")
# 测试6: 检查响应头
print("\n6. 检查 /api/users 响应头")
async with httpx.AsyncClient() as client:
response = await client.get(f"{base_url}/api/users")
print(f" WWW-Authenticate: {response.headers.get('WWW-Authenticate', 'None')}")
print(f" Content-Type: {response.headers.get('Content-Type', 'None')}")
print(f" 分析: {'存在Basic认证头' if 'Basic' in response.headers.get('WWW-Authenticate', '') else '无Basic认证头'}")
print("\n" + "=" * 60)
print("测试结论:")
print("=" * 60)
print("如果 /api/auth/** 端点正常工作,但其他端点返回401,")
print("则说明SecurityConfig配置存在问题。")
print("可能的原因:")
print("1. permitAll()配置未生效")
print("2. 默认Basic认证仍在起作用")
print("3. 路径匹配器配置错误")
if __name__ == "__main__":
import asyncio
asyncio.run(test_security_config())