Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should 401 Unauthorized or 403 Forbidden be used here?

I've read this similar question but it doesn't quite satisfy me.

I have two use cases.

  1. An anonymous(unauthenticated) user tries to access a protected(authorized only) resource
  2. An authenticated user tries to access a resource which he is not entitled to access(ie, doesn't belong to a group)

For these two cases, which error code should be returned? I'm guessing 401 for the first and 403 for the second. But for 401, a WWW-Authenticate header must be included in the response. I'm not wanting to use the basic HTTP authentication, opting instead for the more conventional form based approach. (ie, user submits a form from Login.aspx or whatever).

So which one should I use?

like image 964
Earlz Avatar asked Nov 06 '22 00:11

Earlz


1 Answers

For the first case you should use 401 Unauthorized:

The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource.

For the second case you should use 403 Forbidden:

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

EDIT: It seems I didn't RTFQ - my bad.

If you don't want to use HTTP-Authentication, then for case #1 you might want to simply return a 200 OK:

...or a 307 Temporary Redirect pointing to the login screen - which would then 307 the client back to the original URL once authenticated.

For case #2 a 403 still sounds like a fairly reasonable response - although on second thought it might be intended for resources that should not be served to anyone - as 404 is suggested as an valid alternative response.

...So maybe case #2 should receive a 307 or 200 response as well.

like image 140
Már Örlygsson Avatar answered Nov 09 '22 16:11

Már Örlygsson