Basic.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. declare(strict_types=1);
  3. namespace Sabre\HTTP\Auth;
  4. /**
  5. * HTTP Basic authentication utility.
  6. *
  7. * This class helps you setup basic auth. The process is fairly simple:
  8. *
  9. * 1. Instantiate the class.
  10. * 2. Call getCredentials (this will return null or a user/pass pair)
  11. * 3. If you didn't get valid credentials, call 'requireLogin'
  12. *
  13. * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
  14. * @author Evert Pot (http://evertpot.com/)
  15. * @license http://sabre.io/license/ Modified BSD License
  16. */
  17. class Basic extends AbstractAuth
  18. {
  19. /**
  20. * This method returns a numeric array with a username and password as the
  21. * only elements.
  22. *
  23. * If no credentials were found, this method returns null.
  24. *
  25. * @return array|null
  26. */
  27. public function getCredentials()
  28. {
  29. $auth = $this->request->getHeader('Authorization');
  30. if (!$auth) {
  31. return null;
  32. }
  33. if ('basic ' !== strtolower(substr($auth, 0, 6))) {
  34. return null;
  35. }
  36. $credentials = explode(':', base64_decode(substr($auth, 6)), 2);
  37. if (2 !== count($credentials)) {
  38. return null;
  39. }
  40. return $credentials;
  41. }
  42. /**
  43. * This method sends the needed HTTP header and status code (401) to force
  44. * the user to login.
  45. */
  46. public function requireLogin()
  47. {
  48. $this->response->addHeader('WWW-Authenticate', 'Basic realm="'.$this->realm.'", charset="UTF-8"');
  49. $this->response->setStatus(401);
  50. }
  51. }