【问题标题】:Why does SessionAuthentication in Django REST Framework Never Return HTTP401为什么 Django REST 框架中的 SessionAuthentication 从不返回 HTTP401
【发布时间】:2014-10-28 23:15:01
【问题描述】:
查看 Django REST 框架的 the docs 和 the source,我看到 SessionAuthentication 只返回 HTTP 403 代码,而其他 Authentication 类将返回 401。这是什么原因?
401 makes sense 肯定有很多情况。
这个问题尤其成问题,因为“在确定响应类型时使用了视图上设置的第一个身份验证类。” SessionAuthentication 默认是第一个 Authentication 类。
【问题讨论】:
标签:
django
django-rest-framework
【解决方案1】:
Django REST Framework 遵守HTTP specification,当Authentication 类没有返回可以使用的WWW-Authenticate 标头时,不会返回401 响应。
HTTP 401 响应必须始终包含 WWW-Authenticate 标头,指示客户端如何进行身份验证。 HTTP 403 响应不包含 WWW-Authenticate 标头。
-- Django REST Framework documentation
由于SessionAuthentication 类没有定义可以使用的WWW-Authenticate 标头,因此Django REST Framework 无法返回401 响应并仍然遵循规范。您可以通过将另一个支持标头的 Authentication 类设置到列表顶部来解决此问题,例如 BasicAuthentication。