0

This might be more of a PHP and SO question, but since it deals with HTTP codes, I thought I'd ask here first.

So I'm building a very simple user authentication backend that basically checks the (fairly secured) session tokens to confirm if the user's session exists and is valid. If all checks out, the page loads, if authentication fails, they are redirected to the login page.

I wanted to use the 401 HTTP status code instead of the 302, so that it would reflect at the browser level and in the server logs that the browser was attempting to access a non-yet authorized page, but this has not been successful.

Following several examples, I've tried setting the ErrorDocument directive in the .htaccess file, but no luck (a 404 redirect works fine). I've sent various combinations of headers via the script, the three that seemed most promising were:

 header('Location: http://mysite.org/login.php', 1, 401);

The browser shows a 401 response, but no redirect.

 header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized"); 
 header('Location: http://mysite.org/login.php');

The browser redirects, but shows the original page redirect as a 302.

header('WWW-Authenticate: Basic realm="My Realm"');
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
header('Status: 401 Unauthorized');
header('Location: http://mysite.org/login.php');

With the last one, I've tried it with and without the Location header, with and without the Status, but in all combinations it only triggers the browser's Basic authentication dialog.

So is there a right or recommended way to handle a web-based (non-browser default) unauthorized redirect?

I know that I can just go with a normal 302, but I want to know if that's the only option (or only standards-compliant option) before I give up.

Anthony
  • 305
  • 4
  • 14

1 Answers1

0

According to RFC 2616, section 10.4, 4XX response codes indicate errors, and the browser is not indicated to follow any Location header in the response. Additionally, a 401 response code is used strictly for HTTP authentication, and the directives in RFC 2617 must be followed.

I would recommend using a 303 or 302 response code instead.

Ignacio Vazquez-Abrams
  • 45,019
  • 5
  • 78
  • 84
  • So none of the big web apps are using HTTP authentication but via a form? Part of what I was hoping to pull of was making it so that the PHP script only had to throw a 401 and the server would handle the redirect, thus loosening the authentication so that if some other authentication system is adopted, the scripts would still just throw their 401 and get to the right place. Dare to dream, I guess. – Anthony Apr 01 '12 at 12:01