Bearer.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. declare(strict_types=1);
  3. namespace Sabre\HTTP\Auth;
  4. /**
  5. * HTTP Bearer authentication utility.
  6. *
  7. * This class helps you setup bearer auth. The process is fairly simple:
  8. *
  9. * 1. Instantiate the class.
  10. * 2. Call getToken (this will return null or a token as string)
  11. * 3. If you didn't get a valid token, call 'requireLogin'
  12. *
  13. * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
  14. * @author François Kooman (fkooman@tuxed.net)
  15. * @license http://sabre.io/license/ Modified BSD License
  16. */
  17. class Bearer extends AbstractAuth
  18. {
  19. /**
  20. * This method returns a string with an access token.
  21. *
  22. * If no token was found, this method returns null.
  23. *
  24. * @return string|null
  25. */
  26. public function getToken()
  27. {
  28. $auth = $this->request->getHeader('Authorization');
  29. if (!$auth) {
  30. return null;
  31. }
  32. if ('bearer ' !== strtolower(substr($auth, 0, 7))) {
  33. return null;
  34. }
  35. return substr($auth, 7);
  36. }
  37. /**
  38. * This method sends the needed HTTP header and status code (401) to force
  39. * authentication.
  40. */
  41. public function requireLogin()
  42. {
  43. $this->response->addHeader('WWW-Authenticate', 'Bearer realm="'.$this->realm.'"');
  44. $this->response->setStatus(401);
  45. }
  46. }