A distinct HTTP status for not logged in vs. not authorized in a RESTful API
Asked Answered
N

2

23

So send a few different status headers in my API including 404, 409, 201, 302 and the like. Now I'm running into issues with 401 Unauthorized. I'm currently sending it if a user is not logged in (the entire API is rights managed) or if a user doesn't satisfy the specific access requirements for the particular resource being retrieved/modified.

Now, I also control the frontend client (a jQuery/HTML application), and I'd like to differentiate between the two cases for 401. Is there a distinct status I should be using for not logged in? Is the best way to handle it to send body content alongside the header?

Nimocks answered 19/8, 2010 at 22:29 Comment(1)
Similar question to #3297548Constitutive
E
34

You should use 403 to indicate that the user isn't authorized to access the resource. Using 401 is for indicating that the user needs to supply credentials just as you are currently using it. See the descriptions of 401 and 403 here.

Estragon answered 20/8, 2010 at 2:56 Comment(0)
R
7

As laz say, you should use 403 when you've authenticated the user, but the user doesn't have permission to do what she's asking for. e.g. you might allow GET'ing a resource, but not DELETE or PUT.

  • 401 would be incorrect since it basically says that "I don't recognise these credentials"
  • 403 is correct since it says that "You're not allowed to do this"

In any case, the response body should always contain more information, even when it's an error response. This allows a client a way out, hopefully moving forward (using embedded links) or by providing enough information on how to proceed (e.g. "My records indicate that you do not have permission to delete XXX, please contact your system administrator and ask for the FOOBAR permission").

Reefer answered 20/8, 2010 at 8:25 Comment(2)
Wouldn't it be "do not have permission to FOOBAR XXX"?Vish
The "do not have permission to delete XXX" was thought of as a response to a DELETE request, so yes. If you serve a 403 to a PUT request, you'd word it appropriately. The FOOBAR thing should have read "FOOBAR role". The point is to tell the user how they can solve the problem, but that (error message design) is another topic!Reefer

© 2022 - 2024 — McMap. All rights reserved.