I am working on a Rails REST-based website and am writing my functional tests for the controllers. As a REST based application, I am making use of several HTTP verbs, GET
, POST
, PUT
, DELETE
etc.
I've noticed that I am inconsistent in my application of 401 and 302 HTTP response codes regarding anonymous users. Sometimes when they make a request for a resource that requires authentication, I return 401 Unauthorized. Other times, I return 302 and redirect them to a login page.
Is there standard that I should be following here? When should 401s be used? When should I redirect to a login page? For example,
GETs
be redirected? POSTs
get a 401
? Or perhaps this is all just matter of opinion, a convention that I need choose and enforce on my own.
As I read the RFC, unauthenticated users requesting a resource which requires authentication should consistently receive a 401 Unauthorized
. From the RFC:
302 Found
: The requested resource resides temporarily under a different URI.
401 Unauthorized
: The request requires user authentication.
Clearly the 302
does not correctly describe your situation and the 401
does.