HTTP 401不使用HTTP基本身份验证时未授权? [英] HTTP 401 Unauthorized when not using HTTP basic auth?

查看:303
本文介绍了HTTP 401不使用HTTP基本身份验证时未授权?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在构建不使用 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:

生成401响应的服务器必须发送WWW-Authenticate标头字段

The server generating a 401 response MUST send a WWW-Authenticate header field

这是否意味着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:

HTTP 401响应必须始终包含WWW-Authenticate标头,该标头指示客户端如何进行身份验证. HTTP 403响应不包含WWW-Authenticate标头.

HTTP 401 responses must always include a WWW-Authenticate header, that instructs the client how to authenticate. HTTP 403 responses do not include the WWW-Authenticate header.

将使用的响应类型取决于身份验证方案.

The kind of response that will be used depends on the authentication scheme.

理查森(Richardson)

While Richardson seems to disagree:

401(未经授权")
重要性:高.
客户端尝试在受保护的资源上操作,而没有提供适当的身份验证凭据.它可能提供了错误的凭据,或者根本没有提供. 凭据可以是用户名和密码,API密钥或身份验证 令牌-所涉及的服务期望什么.客户通常会 一个URI请求并接受401,这样它就知道要发送哪种凭据 以及什么格式. [...]

401 ("Unauthorized")
Importance: High.
The client tried to operate on a protected resource without providing the proper authentication credentials. It may have provided the wrong credentials, or none at all. The credentials may be a username and password, an API key, or an authentication token—whatever the service in question is expecting. It’s common for a client to make a request for a URI and accept a 401 just so it knows what kind of credentials to send and in what format. [...]

推荐答案

您假设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基本身份验证时未授权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆