Question

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,

  • Should GETs be redirected?
  • Should POSTs get a 401?
  • What do I do for AJAX requests where a 302 wouldnt be followed?

Or perhaps this is all just matter of opinion, a convention that I need choose and enforce on my own.

Was it helpful?

Solution

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.

OTHER TIPS

I don't know if search engines will index a 401 page.

Ideally, for a restricted page for users who are not authenticated: 401 status code and show the sign in form.

For authenticated users who are still not allowed: 403 and "Not Authorized" page.

For the sign in page: 200 OK and show the sign in form.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top