http-auth.php 2.3 KB

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