0

I'm building an API endpoint. This endpoint needs to be secured by HTTP basic auth.

If API requests access I would like to show http basic auth, if data is incorrect I would like to throw a 403 forbidden message. If data is correct I simply show "correct" at the moment. Here's my code:

  $username = null;
  $password = null;

  // if data is sent
  if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']) ) {
      $username = $_SERVER['PHP_AUTH_USER'];
      $password = $_SERVER['PHP_AUTH_PW'];

      //perforn check if data is correct
      if($username == 'as' && $password = 'pass'){
        die(var_dump("correct"));
      }
      //if data uncorrect throw 403 code
      else
        header('HTTP/1.0 403 Forbidden');

  }

  //request HTTP auth if nothing sent
  if (!isset($_SERVER['PHP_AUTH_USER']) && !isset($_SERVER['PHP_AUTH_PW'])) {

      header('WWW-Authenticate: Basic realm="My Realm"');
      header('HTTP/1.0 401 Unauthorized');

      die();

  }

At the moment my code is triggering 403 all the time. Any idea how to fix this matching my requirements described above?

peke_peke
  • 441
  • 7
  • 21
  • This script doesn't work on all servers, I tried it on a web server and the script keeps popping up the login dialog, I tested it on a localhost server and it worked perfectly.. – node_modules Apr 19 '16 at 07:56
  • any idea why this occurs? On my local dev setup I use MAMP (apache webserver). – peke_peke Apr 19 '16 at 07:58
  • Still haven't figured out why this happens, But it has something to do with the `HTTP_AUTHORIZATION` I think.. See the answer below, maybe that's the right answer? – node_modules Apr 19 '16 at 08:01

1 Answers1

1

You're missing one = which is making your test into an assignment:

if($username == 'as' && $password == 'pass'){ //right here
    die(var_dump("correct"));
} else { //if data incorrect throw 403 code
    header('HTTP/1.0 403 Forbidden');
}
larsAnders
  • 3,813
  • 1
  • 15
  • 19