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?