auth_callback.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/bin/env python3
  2. """Example of using callback-based authentication with dulwich HTTP client.
  3. This example demonstrates how to use the new callback-based authentication
  4. feature to handle HTTP and proxy authentication dynamically.
  5. Note: Dulwich currently supports 'basic' and 'anyauth' proxy authentication
  6. methods via the http.proxyAuthMethod git config option or the
  7. GIT_HTTP_PROXY_AUTHMETHOD environment variable. Other methods like 'digest',
  8. 'negotiate', and 'ntlm' will raise NotImplementedError.
  9. """
  10. from dulwich.client import HttpGitClient
  11. def my_auth_callback(url, www_authenticate, attempt):
  12. """Callback function for HTTP authentication.
  13. Args:
  14. url: The URL that requires authentication
  15. www_authenticate: The WWW-Authenticate header value from the server
  16. attempt: The attempt number (starts at 1)
  17. Returns:
  18. dict: Credentials with 'username' and 'password' keys, or None to cancel
  19. """
  20. print(f"Authentication required for {url}")
  21. print(f"Server says: {www_authenticate}")
  22. print(f"Attempt {attempt} of 3")
  23. # In a real application, you might:
  24. # - Prompt the user for credentials
  25. # - Look up credentials in a password manager
  26. # - Parse the www_authenticate header to determine the auth scheme
  27. if attempt <= 2:
  28. # Example: return hardcoded credentials for demo
  29. return {"username": "myuser", "password": "mypassword"}
  30. else:
  31. # Give up after 2 attempts
  32. return None
  33. def my_proxy_auth_callback(url, proxy_authenticate, attempt):
  34. """Callback function for proxy authentication.
  35. Args:
  36. url: The URL being accessed through the proxy
  37. proxy_authenticate: The Proxy-Authenticate header value from the proxy
  38. attempt: The attempt number (starts at 1)
  39. Returns:
  40. dict: Credentials with 'username' and 'password' keys, or None to cancel
  41. """
  42. print(f"Proxy authentication required for accessing {url}")
  43. print(f"Proxy says: {proxy_authenticate}")
  44. # Return proxy credentials
  45. return {"username": "proxyuser", "password": "proxypass"}
  46. def main():
  47. # Create an HTTP Git client with authentication callbacks
  48. client = HttpGitClient(
  49. "https://github.com/private/repo.git",
  50. auth_callback=my_auth_callback,
  51. proxy_auth_callback=my_proxy_auth_callback,
  52. )
  53. # Now when you use the client, it will call your callbacks
  54. # if authentication is required
  55. try:
  56. # Example: fetch refs from the repository
  57. refs = client.fetch_refs("https://github.com/private/repo.git")
  58. print(f"Successfully fetched refs: {refs}")
  59. except Exception as e:
  60. print(f"Error: {e}")
  61. if __name__ == "__main__":
  62. main()