Search code examples
ruby-on-railsresthttpresponsefunctional-testinghttp-response-codes

When to 401 vs when to 302


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.


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.