http-auth.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * @package chamilo.webservices
  5. */
  6. $realm = 'The batcave';
  7. // Just a random id
  8. $nonce = uniqid();
  9. // Get the digest from the http header
  10. $digest = getDigest();
  11. // If there was no digest, show login
  12. if (is_null($digest)) {
  13. requireLogin($realm, $nonce);
  14. }
  15. $digestParts = digestParse($digest);
  16. $validUser = 'admin';
  17. $validPass = 'admin';
  18. // Based on all the info we gathered we can figure out what the response should be
  19. $A1 = md5("{$digestParts['username']}:{$realm}:{$validPass}");
  20. $A2 = md5("{$_SERVER['REQUEST_METHOD']}:{$digestParts['uri']}");
  21. $validResponse = md5("{$A1}:{$digestParts['nonce']}:{$digestParts['nc']}:{$digestParts['cnonce']}:{$digestParts['qop']}:{$A2}");
  22. if ($digestParts['response'] != $validResponse) {
  23. requireLogin($realm, $nonce);
  24. } else {
  25. // We're in!
  26. echo 'a7532ae474e5e66a0c16eddab02e02a7';
  27. die();
  28. }
  29. // This function returns the digest string
  30. function getDigest()
  31. {
  32. // mod_php
  33. if (isset($_SERVER['PHP_AUTH_DIGEST'])) {
  34. $digest = $_SERVER['PHP_AUTH_DIGEST'];
  35. // most other servers
  36. } elseif (isset($_SERVER['HTTP_AUTHENTICATION'])) {
  37. if (strpos(
  38. strtolower($_SERVER['HTTP_AUTHENTICATION']),
  39. 'digest'
  40. ) === 0) {
  41. $digest = substr($_SERVER['HTTP_AUTHORIZATION'], 7);
  42. }
  43. } elseif (isset($_SERVER['HTTP_WWW_AUTHENTICATE'])) {
  44. $digest = $_SERVER['HTTP_WWW_AUTHENTICATE'];
  45. }
  46. return $digest;
  47. }
  48. // This function forces a login prompt
  49. function requireLogin($realm, $nonce)
  50. {
  51. header('WWW-Authenticate: Digest realm="'.$realm.'",qop="auth",nonce="'.$nonce.'",opaque="'.md5($realm).'"');
  52. header('HTTP/1.1 401');
  53. echo 'Authentication Canceled';
  54. die();
  55. }
  56. // This function extracts the separate values from the digest string
  57. function digestParse($digest)
  58. {
  59. // protect against missing data
  60. $needed_parts = ['nonce' => 1, 'nc' => 1, 'cnonce' => 1, 'qop' => 1, 'username' => 1, 'uri' => 1, 'response' => 1];
  61. $data = [];
  62. preg_match_all('@(\w+)=(?:(?:")([^"]+)"|([^\s,$]+))@', $digest, $matches, PREG_SET_ORDER);
  63. foreach ($matches as $m) {
  64. $data[$m[1]] = $m[2] ? $m[2] : $m[3];
  65. unset($needed_parts[$m[1]]);
  66. }
  67. return $needed_parts ? false : $data;
  68. }