问题描述
在构建不使用 HTTP基本身份验证的REST API时(但还有其他方法) (例如api键)和客户端提供的无效凭据,您应该返回什么HTTP状态代码? 401未经授权或403禁止访问?
When building a REST API that doesn't use HTTP basic authentication (but something else like an api-key) and the client provides invalid credentials, what HTTP Status Code are you supposed to return? 401 Unauthorized or 403 Forbidden?
IANA HTTP状态代码注册表列出了 RFC7235第3.1 条,其中涉及"401未经授权"状态:
The IANA HTTP Status Code Registry lists RFC7235, Section 3.1 as responsible for "401 Unauthorized", where it states:
这是否意味着REST API仅在使用HTTP基本身份验证时才返回401,而在例如通过api-key使用身份验证时不应该返回401?
Does that mean that a REST API should only ever return a 401 when using HTTP basic authentication but not when for example using authentication via an api-key?
Django 似乎同意:
Django seems to agree:
将使用的响应类型取决于身份验证方案.
The kind of response that will be used depends on the authentication scheme.
理查森(Richardson)不同意:
While Richardson seems to disagree:
推荐答案
您假设www-authenticate值必须是基本值.您可以返回诸如"API密钥"之类的其他值作为需要进行的身份验证的类型.因此,请随时返回401和带有其他值的www-authenticate标头.您甚至可以返回带有不同值的多个标头,以指示您的应用程序支持的身份验证的不同类型.
You are assuming that the www-authenticate value needs to be basic. You can return a different value like "API-key" as the type of auth that needs to happen. So feel free to return 401 and www-authenticate header with some other value. You can even return multiple headers with different values indicating the different types of authentication that your app supports.
这篇关于HTTP 401不使用HTTP基本身份验证时未授权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!