tags:

views:

411

answers:

4

I have a web application that uses RESTful url patterns. Currently if a users tries to access a page where they need to be authenticated it just returns nothing. Is it good practice to return the HTTP status code in this case? Would I use 403 or a different one?

+1  A: 

If they don't have permissions return 401 to give them the chance to respond to the authentication challenge or 403 if you don't want them to.

Restlet 1.1 onwards return 403, while earlier versions return 401. 403 seems to be regarded as more correct, if not necessarily more helpful.

Rich Seller
A: 

It depends. You really ought to return something, of course, just to have a decent client experience. If you'd like to give them opportunity to authenticate at that moment, you can return a 401 and the client will know to pass credentials using standard authentication. If, however, you'd prefer that they authenticate through some other mechanism (some login URL and then set a cookie or somesuch), then returning a 403 is probably the way to go.

Nick Bastin
+3  A: 

You should send a response with the HTTP status code.

I wouldn't send a 403 Forbidden back though as the spec specifies for this status code :

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated

Return a 401 Unauthorized status code instead. See this for more info on the status codes:

http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

The way I do this with Jersey is to send a response with the status and then include a String entity which contains a human readable message, e.g.

Response response = Response.status(Status.PRECONDITION_FAILED).entity(
                    new String("Incorrect " + id + " [" + id + "]")).build();

This will be displayed to the client. I throw a Jersey WebApplicationException which wraps this response.

Jon
Thanks Jon, this was most helpful.
Graham
A: 

lol... in the REST API implementation I just built I returned a 401 status code with a response body that read "goodbye". Was the first thing complained about by guy interacting with API. I still think "goodbye" said it all ; )

codemonkey