54

When creating a web service (RESTful), what status code should I use when session token is invalid? Currently the one in my company sends me a 404, not found, but I think this is not correct, because the resource exists. Maybe I should use 401 Unauthorized. What do you think? What status code do you recommend me to use in this scenario? Thanks.

2 Answers 2

101

401 Unauthorized.

Your existing session token doesn't authorize you any more, so you are unauthorized.

Don't forget that a session token is just a short-cut to avoid having to provide credentials for every request.

Sending 404 is incorrect because, as you observe, the resource does exist. You just don't currently have authorization to see it.

NB Don't use 403 Forbidden; the HTTP specification defines it as follows: "The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated." That doesn't apply in this case as authorization WILL help.

Sign up to request clarification or add additional context in comments.

6 Comments

No. 498 is an unofficial code used by a proprietary product.
Wouldnt a 404 be more "secure" since i wouldnt be revealing that such a path exists.
@user3711421 I would check credentials before I check whether or not a resource even exists, and so return 401 without valid credentials, even if later the resource may not actually exist. So the 401 says nothing about your resources. It may help you to think of an analogy of a building protected by a card reader at the entrance. It doesn't help you to know that you want to go to room 10 on floor 40 if you don't have a valid keycard -- you're not getting in anyway. Whether or not there is a room 10 on floor 40 (or if there are even that many floors in the building) is irrelevant.
But if i come to know the information that room 10 on floor 40 exists i can keep trying different cards. If i didnt know about room 10 on floor 40 i wouldnt even know if i am swiping for a room that exists. Now i have in mind a system which both has open and authenticated endpoints.
@user3711421 1) The 401 doesn't tell you whether or not the "room 10 on floor 40" exists. 2) Security through obscurity. Sooner or later word is going to get out that "room 10 on floor 40" exists. Then you better have secure "keycards".
|
4

Looking through the HttpStatusCode enum, I think Unauthorized is probably the closest to what you're looking for.

Take a look at the list there, and read the descriptions for each one.

2 Comments

I prefer to use the definitive source: w3.org/Protocols/rfc2616/rfc2616-sec10.html
@Colin'tHart That's definitely a good source. It's pretty long though. The MSDN link serves as a good quick-reference (I actually just typed ((HttpStatusCode). into Visual Studio, which gives you this list).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.