1

I would like to return a HTTP status 404 (NotFound) when a anonymous user tries to access a resource (/preferences) that only makes sense for a identified user.

Using as [Authorize] attribute on my Controller/Method automatically returns a 401 (Unauthorized) for a anonymous user, but handling authorization inside method does not sound good. Any thoughts?

Edit: I am using Asp.Net Web API 2 and Authorize attribute to secure resources.

Related resources for people wandering why would I return a 404:

Community
  • 1
  • 1
Filipe Borges
  • 2,712
  • 20
  • 32

2 Answers2

0

Make your web api method return an HttpResponseMessage, and configure it to return 404. I'm sure you can easily convert this to c#:

return Me.Request.CreateResponse(HttpStatusCode.NotFound, "Your message here.")
Crowcoder
  • 11,250
  • 3
  • 36
  • 45
  • Thanks for your answer, but... Maybe I did not make it clear, but this is exactly what I want to avoid: testing if user is authorized and then returning a custom response. Ideally I would "configure" the Authorized to return a custom code when not authorized. (does it makes sense at all?) – Filipe Borges Feb 12 '15 at 13:08
  • 1
    Yes, I see. This article demonstrates a custom authorization filter. It sets the response to 401 but you could easily set it to whatever you want: http://www.asp.net/web-api/overview/security/authentication-filters – Crowcoder Feb 12 '15 at 13:19
0

I think the problem here is that 401 is 'technically' the correct code to return whenever an endpoint requires an authorized user and the user making the call is anonymous. After all, anonymous users are not authorized. How could they be? You cannot authorized an anonymous user.

So the behavior that the standard code is providing is correct, you just want to do something that is different for some reason. It is probably a bad idea in the long run to redefine what the HTTP status codes just for your application. For example, how could a client of your application tell the difference between a problem with authentication and a problem with resource identification? Both would return not found.

If I sound like a scold I apologize that is not my intent. :-)

GlennSills
  • 3,977
  • 26
  • 28
  • yeah, but if you wish to hide that such route even exists, it's ok to return 404 as specified by the RFC 7231. – JobaDiniz Jul 28 '20 at 17:46