http-auth.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. // mod_php
  30. if (isset($_SERVER['PHP_AUTH_DIGEST'])) {
  31. $digest = $_SERVER['PHP_AUTH_DIGEST'];
  32. // most other servers
  33. }
  34. elseif (isset($_SERVER['HTTP_AUTHENTICATION'])) {
  35. if (strpos(strtolower($_SERVER['HTTP_AUTHENTICATION']), 'digest') === 0)
  36. $digest = substr($_SERVER['HTTP_AUTHORIZATION'], 7);
  37. }
  38. elseif (isset($_SERVER['HTTP_WWW_AUTHENTICATE'])) {
  39. $digest = $_SERVER['HTTP_WWW_AUTHENTICATE'];
  40. }
  41. return $digest;
  42. }
  43. // This function forces a login prompt
  44. function requireLogin($realm, $nonce) {
  45. header('WWW-Authenticate: Digest realm="'.$realm.'",qop="auth",nonce="'.$nonce.'",opaque="'.md5($realm).'"');
  46. header('HTTP/1.1 401');
  47. echo 'Authentication Canceled';
  48. die();
  49. }
  50. // This function extracts the separate values from the digest string
  51. function digestParse($digest) {
  52. // protect against missing data
  53. $needed_parts = array('nonce' => 1, 'nc' => 1, 'cnonce' => 1, 'qop' => 1, 'username' => 1, 'uri' => 1, 'response' => 1);
  54. $data = array();
  55. preg_match_all('@(\w+)=(?:(?:")([^"]+)"|([^\s,$]+))@', $digest, $matches, PREG_SET_ORDER);
  56. foreach ($matches as $m) {
  57. $data[$m[1]] = $m[2] ? $m[2] : $m[3];
  58. unset($needed_parts[$m[1]]);
  59. }
  60. return $needed_parts ? false : $data;
  61. }