简体   繁体   中英

Should I return a 401 or a 405 response code to a REST API user without sufficient access?

I'm developing an API which will also have an authentication/authorization component.

Anybody, regardless of authentication status, will be able to write (POST), but depending on if you are unauthenticated, authenticated as a normal user or authenticated as an admin and what resource you are trying to access I'm going to return different responses for GET, DELETE and PUT.

I'm trying to figure out the most appropriate response code for a user who isn't authenticated and/or authorized.

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

Unauthorized -> 401

Forbidden -> 403

Method Not Allowed -> 405

Let's use a specific examples:

  • John Doe is unauthenticated, on DELETE should he receive a 401 or a 405?
  • Amy is authenticated but not authorized, on DELETE should she receive a 403 or a 405?

(Keep in mind that even though John and Amy are forbidden or unauthorized that doesn't mean they arent able to access the same resource with a different HTTP VERB.)

Thanks.

In this case, I think providing some examples for clarification are useful:

  • Unauthenticated + Supported method = 401
  • Unauthenticated + Unsupported method = 405
  • Authenticated + Authorized + Supported method = 2xx
  • Authenticated + Authorized + Unsupported method = 405
  • Authenticated + Unauthorized + Supported method = 403
  • Authenticated + Unauthorized + Unsupported method = 405

In other words, from a procedural standpoint:

  1. Check whether methods are supported. If not: 405
  2. If supported, check if the user is authenticated. If not: 401
  3. If authenticated, check if the user is authorized. If not: 403
  4. If authorized: 2xx

EDIT: I stumbled upon this diagram and thought it might be useful to anyone else who might stumble across this post. Click to enlarge.

在此输入图像描述

Original here .

405 Method Not Allowed should only be used if you don't support the method. It shouldn't be used to tell the client that they cannot use this method.

So the only good HTTP code in your case would be 401 Unauthorized . It indicates the client that the method exists and that they need to login to access it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM