Authentication.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\HTTP;
  7. /**
  8. * Library for working with HTTP authentication
  9. */
  10. class Authentication
  11. {
  12. /**
  13. * Request object
  14. *
  15. * @var \Magento\Framework\App\RequestInterface
  16. */
  17. protected $request;
  18. /**
  19. * Response object
  20. *
  21. * @var \Magento\Framework\App\ResponseInterface
  22. */
  23. protected $response;
  24. /**
  25. * @param \Magento\Framework\App\RequestInterface $httpRequest
  26. * @param \Magento\Framework\App\ResponseInterface $httpResponse
  27. */
  28. public function __construct(
  29. \Magento\Framework\App\RequestInterface $httpRequest,
  30. \Magento\Framework\App\ResponseInterface $httpResponse
  31. ) {
  32. $this->request = $httpRequest;
  33. $this->response = $httpResponse;
  34. }
  35. /**
  36. * Extract "login" and "password" credentials from HTTP-request
  37. *
  38. * Returns plain array with 2 items: login and password respectively
  39. *
  40. * @return array
  41. */
  42. public function getCredentials()
  43. {
  44. $server = $this->request->getServerValue();
  45. $user = '';
  46. $pass = '';
  47. if (empty($server['HTTP_AUTHORIZATION'])) {
  48. foreach ($server as $k => $v) {
  49. if (substr($k, -18) === 'HTTP_AUTHORIZATION' && !empty($v)) {
  50. $server['HTTP_AUTHORIZATION'] = $v;
  51. break;
  52. }
  53. }
  54. }
  55. if (isset($server['PHP_AUTH_USER']) && isset($server['PHP_AUTH_PW'])) {
  56. $user = $server['PHP_AUTH_USER'];
  57. $pass = $server['PHP_AUTH_PW'];
  58. } elseif (!empty($server['HTTP_AUTHORIZATION'])) {
  59. /**
  60. * IIS Note: for HTTP authentication to work with IIS,
  61. * the PHP directive cgi.rfc2616_headers must be set to 0 (the default value).
  62. */
  63. $auth = $server['HTTP_AUTHORIZATION'];
  64. list($user, $pass) = explode(':', base64_decode(substr($auth, strpos($auth, " ") + 1)));
  65. } elseif (!empty($server['Authorization'])) {
  66. $auth = $server['Authorization'];
  67. list($user, $pass) = explode(':', base64_decode(substr($auth, strpos($auth, " ") + 1)));
  68. }
  69. return [$user, $pass];
  70. }
  71. /**
  72. * Set "auth failed" headers to the specified response object
  73. *
  74. * @param string $realm
  75. * @return void
  76. */
  77. public function setAuthenticationFailed($realm)
  78. {
  79. $this->response->setStatusHeader(401, '1.1', 'Unauthorized');
  80. $this->response->setHeader(
  81. 'WWW-Authenticate',
  82. 'Basic realm="' . $realm . '"'
  83. )->setBody(
  84. '<h1>401 Unauthorized</h1>'
  85. );
  86. }
  87. }