basic.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # -*- test-case-name: twisted.web.test.test_httpauth -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. HTTP BASIC authentication.
  6. @see: U{http://tools.ietf.org/html/rfc1945}
  7. @see: U{http://tools.ietf.org/html/rfc2616}
  8. @see: U{http://tools.ietf.org/html/rfc2617}
  9. """
  10. import binascii
  11. from zope.interface import implementer
  12. from twisted.cred import credentials, error
  13. from twisted.web.iweb import ICredentialFactory
  14. @implementer(ICredentialFactory)
  15. class BasicCredentialFactory:
  16. """
  17. Credential Factory for HTTP Basic Authentication
  18. @type authenticationRealm: L{bytes}
  19. @ivar authenticationRealm: The HTTP authentication realm which will be issued in
  20. challenges.
  21. """
  22. scheme = b"basic"
  23. def __init__(self, authenticationRealm):
  24. self.authenticationRealm = authenticationRealm
  25. def getChallenge(self, request):
  26. """
  27. Return a challenge including the HTTP authentication realm with which
  28. this factory was created.
  29. """
  30. return {"realm": self.authenticationRealm}
  31. def decode(self, response, request):
  32. """
  33. Parse the base64-encoded, colon-separated username and password into a
  34. L{credentials.UsernamePassword} instance.
  35. """
  36. try:
  37. creds = binascii.a2b_base64(response + b"===")
  38. except binascii.Error:
  39. raise error.LoginFailed("Invalid credentials")
  40. creds = creds.split(b":", 1)
  41. if len(creds) == 2:
  42. return credentials.UsernamePassword(*creds)
  43. else:
  44. raise error.LoginFailed("Invalid credentials")