# API端点users/by-external/使用授权头时失败，不使用则工作正常

**URL:** https://meta.discourse.org/t/api-endpoint-users-by-external-failing-with-authorization-headers-works-without/259885
**Category:** Bug
**Tags:** rest-api
**Created:** [2023年三月29日 17:57 UTC](https://meta.discourse.org/t/api-endpoint-users-by-external-failing-with-authorization-headers-works-without/259885 "2023-03-29T17:57:34Z")
**Posts on this page:** 4
**Page:** 1

<div class="post-metadata">

### Author: ![Tim\_Scaffidi](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/tim_scaffidi/32/300232_2.png) [@Tim\_Scaffidi](https://meta.discourse.org/u/Tim_Scaffidi)
#### Post date: [2023年三月29日 17:57 UTC](https://meta.discourse.org/t/api-endpoint-users-by-external-failing-with-authorization-headers-works-without/259885/1 "2023-03-29T17:57:34Z")

</div>

自3月24日起，Discourse API响应请求的方式似乎发生了一些变化。

我们这边没有进行任何代码更改，并且Api-Key仍然有效，但是我们一个试图获取用户信息后端服务在访问 `users/by-external/{id}.json` 时开始失败。

我们向这些请求发送了 `Api-Key` 和 `Api-Username` 标头，根据文档，这些标头应该是必需的。这些请求已经正常工作了很多年。

现在，所有发往此端点的请求都以403失败，响应正文如下：

```plaintext
{
    "errors": [
        "您无权查看所请求的资源。"
    ],
    "error_type": "invalid_access"
}

```

即使我尝试请求 `/u/{username}.json` 也会发生这种情况。

令人惊讶的是，当我_不_发送标头时，这些根据文档需要身份验证标头的请求实际上会响应所请求的数据，就好像已通过身份验证一样。

我也尝试发送了错误的Api-Key，响应会有一个略有不同的消息：

```plaintext
{
    "errors": [
        "您无权查看所请求的资源。API用户名或密钥无效。"
    ],
    "error_type": "invalid_access"
}

```

这告诉我密钥被接受了，但错误地报告它没有授予对资源的访问权限，同时却授予了未经身份验证的请求完全访问权限。

我也刚用一个具有所有用户/全局选项的新Api-Key进行了测试，结果相同。

---

<div class="post-metadata">

### Author: ![blake](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/blake/32/157322_2.png) [@blake](https://meta.discourse.org/u/blake)
#### Post date: [2023年三月29日 22:50 UTC](https://meta.discourse.org/t/api-endpoint-users-by-external-failing-with-authorization-headers-works-without/259885/10 "2023-03-29T22:50:15Z")

</div>

在与 @Tim_Scaffidi 一起处理这个问题后，我们意识到传递给 `Api-Username` 的用户已被 `SiteSetting.invalidate_inactive_admin_email_after_days` 自动停用。此设置可能存在一个 bug，即用户发出的 API 调用没有更新该用户的“登录”活动。

---

<div class="post-metadata">

### Author: ![blake](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/blake/32/157322_2.png) [@blake](https://meta.discourse.org/u/blake)
#### Post date: [2023年六月26日 21:41 UTC](https://meta.discourse.org/t/api-endpoint-users-by-external-failing-with-authorization-headers-works-without/259885/15 "2023-06-26T21:41:27Z")

</div>

我再次对此进行了研究，看看是否有任何代码需要更改以改进，但由于该问题仅因使用了“所有用户”API 密钥而发生，因此我认为我们不应在代码方面进行任何更改。为避免用户停用，最佳选择是使用“单用户”API 密钥，这样我们就可以检查 API 密钥记录上的 `last_used_at`，而不是尝试检查用户记录上的 `last_seen_at`。

---

<div class="post-metadata">

### Author: ![blake](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/blake/32/157322_2.png) [@blake](https://meta.discourse.org/u/blake)
#### Post date: [2023年六月26日 21:41 UTC](https://meta.discourse.org/t/api-endpoint-users-by-external-failing-with-authorization-headers-works-without/259885/16 "2023-06-26T21:41:33Z")

</div>


