basic.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. from __future__ import division, absolute_import
  11. import binascii
  12. from zope.interface import implementer
  13. from twisted.cred import credentials, error
  14. from twisted.web.iweb import ICredentialFactory
  15. @implementer(ICredentialFactory)
  16. class BasicCredentialFactory(object):
  17. """
  18. Credential Factory for HTTP Basic Authentication
  19. @type authenticationRealm: L{bytes}
  20. @ivar authenticationRealm: The HTTP authentication realm which will be issued in
  21. challenges.
  22. """
  23. scheme = b'basic'
  24. def __init__(self, authenticationRealm):
  25. self.authenticationRealm = authenticationRealm
  26. def getChallenge(self, request):
  27. """
  28. Return a challenge including the HTTP authentication realm with which
  29. this factory was created.
  30. """
  31. return {'realm': self.authenticationRealm}
  32. def decode(self, response, request):
  33. """
  34. Parse the base64-encoded, colon-separated username and password into a
  35. L{credentials.UsernamePassword} instance.
  36. """
  37. try:
  38. creds = binascii.a2b_base64(response + b'===')
  39. except binascii.Error:
  40. raise error.LoginFailed('Invalid credentials')
  41. creds = creds.split(b':', 1)
  42. if len(creds) == 2:
  43. return credentials.UsernamePassword(*creds)
  44. else:
  45. raise error.LoginFailed('Invalid credentials')