What is correct HTTP status code when redirecting to a login page?

依然范特西╮ 提交于 2019-11-27 10:38:13

I'd say 303 see other 302 Found:

The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.

fits a login page most closely in my opinion. I initially considered 303 see other which would work just as well. After some thought, I'd say 302 Found is more fitting because the requested resource was found, there just is another page to go through before it can be accessed. The response doesn't get cached by default which is fine as well.

This is a misuse of HTTP redirection mechanism. If user is not authorized then your app must return 401 Unauthorized. In case that the user is authorized but does not have an access to the requested resource then 403 Forbidden must be returned.

You should do the redirect on client side, e.g. by javascript. status code for redirection because required authorization does not exist. Using 30x for this does not conform to HTTP.

How to Think About HTTP Status Codes by Mark Nottingham

401 Unauthorized triggers HTTP’s request authentication mechanism.

401 Unauthorized status code requires presence of WWW-Authenticate header that supports various authentication types:

WWW-Authenticate: <type> realm=<realm>

Bearer, OAuth, Basic, Digest, Cookie, etc

I think the appropriate solution is the HTTP 401 (Not Authorized) header.

http://en.wikipedia.org/wiki/HTTP_codes#4xx_Client_Error

The purpose of this header is exactly this. But, instead of redirecting to a login page, the correct process would be something like:

  • User not logged try to access a login-restricted page.
  • system identifies user is not logged
  • system returns HTTP 401 header, AND display the login form in the same response (not a redirect).

This is a good practice, like providing a useful 404 page, with sitemap links, and a search form for example.

See you.

I had rare cases where the Firefox browser cached the 302 redirect. That is the reason why I'm using 307 for login pages and e.g. redirects to the newest article/post/comment/etc.

If you are using 302, don't forget to double check that caching is disabled:

header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache');
header('Pragma: no-cache');
header('Cache-Control: post-check=0, pre-check=0', false);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!