test_oauth.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #!/usr/bin/env python3
  2. """
  3. 测试OAuth2端点
  4. """
  5. import requests
  6. import json
  7. def test_oauth_authorize():
  8. """测试OAuth2授权端点"""
  9. url = "http://localhost:8000/oauth/authorize"
  10. params = {
  11. "response_type": "code",
  12. "client_id": "eqhoIdAyAWbA8MsYHsNqQqNLJbCayTjY",
  13. "redirect_uri": "http://localhost:8001/auth/callback",
  14. "scope": "profile email",
  15. "state": "test_state_123"
  16. }
  17. print("测试OAuth2授权端点...")
  18. print(f"URL: {url}")
  19. print(f"参数: {json.dumps(params, indent=2)}")
  20. try:
  21. response = requests.get(url, params=params, timeout=10, allow_redirects=False)
  22. print(f"\n状态码: {response.status_code}")
  23. print(f"响应头: {dict(response.headers)}")
  24. if response.status_code == 200:
  25. print("✅ 授权端点正常工作!")
  26. print("返回了授权页面HTML")
  27. elif response.status_code == 302:
  28. print("✅ 受信任应用自动重定向!")
  29. print(f"重定向到: {response.headers.get('location')}")
  30. else:
  31. print(f"❌ 意外的状态码: {response.status_code}")
  32. print(f"响应内容: {response.text}")
  33. except requests.exceptions.ConnectionError:
  34. print("\n❌ 无法连接到服务器,请确保后端服务正在运行")
  35. except Exception as e:
  36. print(f"\n❌ 测试失败: {e}")
  37. def test_oauth_token():
  38. """测试OAuth2令牌端点"""
  39. url = "http://localhost:8000/oauth/token"
  40. data = {
  41. "grant_type": "authorization_code",
  42. "code": "test_auth_code_123",
  43. "redirect_uri": "http://localhost:8001/auth/callback",
  44. "client_id": "eqhoIdAyAWbA8MsYHsNqQqNLJbCayTjY",
  45. "client_secret": "LKJm5XHJFhhgxSv9nQhoQNNI3wrKyWGZCaPQ4qc43Lf5qfXdLAHoGAHhCYqApEpr"
  46. }
  47. print("\n" + "="*50)
  48. print("测试OAuth2令牌端点...")
  49. print(f"URL: {url}")
  50. print(f"数据: {json.dumps(data, indent=2)}")
  51. try:
  52. response = requests.post(url, data=data, timeout=10)
  53. print(f"\n状态码: {response.status_code}")
  54. if response.status_code == 200:
  55. result = response.json()
  56. print("✅ 令牌端点正常工作!")
  57. print(f"访问令牌: {result.get('access_token', '')[:50]}...")
  58. print(f"令牌类型: {result.get('token_type')}")
  59. print(f"过期时间: {result.get('expires_in')} 秒")
  60. else:
  61. print(f"❌ 令牌请求失败: {response.status_code}")
  62. print(f"响应内容: {response.text}")
  63. except Exception as e:
  64. print(f"\n❌ 测试失败: {e}")
  65. if __name__ == "__main__":
  66. test_oauth_authorize()
  67. test_oauth_token()