

# 排查 HTTP API JWT 授权方的问题
<a name="http-api-troubleshooting-jwt"></a>

以下内容为您在将 JSON Web 令牌 (JWT) 授权方与 HTTP API 结合使用时可能遇到的错误和问题提供故障排除建议。

## 问题：我的 API 返回 `401 {"message":"Unauthorized"}`
<a name="http-api-troubleshooting-jwt.unauthorized"></a>

检查来自 API 的响应中的 `www-authenticate` 标头。

以下命令使用 `curl` 将请求发送到具有 JWT 授权方（ `$request.header.Authorization` 作为其身份源）的 API。

```
$curl -v -H "Authorization: token" https://api-id.execute-api.us-west-2.amazonaws.com/route
```

来自 API 的响应包含一个 `www-authenticate` 标头。

```
...
< HTTP/1.1 401 Unauthorized
< Date: Wed, 13 May 2020 04:07:30 GMT
< Content-Length: 26
< Connection: keep-alive
< www-authenticate: Bearer scope="" error="invalid_token" error_description="the token does not have a valid audience"
< apigw-requestid: Mc7UVioPPHcEKPA=
<
* Connection #0 to host api-id.execute-api.us-west-2.amazonaws.com left intact
{"message":"Unauthorized"}}
```

在这种情况下，`www-authenticate` 标头显示未为有效的受众颁发令牌。为使 Lambda 对请求授权，JWT 的 `aud` 或 `client_id` 声明必须与为授权方配置的受众条目之一匹配。API Gateway 只有在 `aud` 不存在时才验证 `client_id`。当 `aud` 和 `client_id` 同时存在时，API Gateway 会评估 `aud`。

您还可以对 JWT 进行解码，并验证它与 API 所需的发布者、受众和作用域匹配。网站 [jwt.io](https://jwt.io/) 可以在浏览器中调试 JWT。OpenID Foundation 维护[用于处理 JWT 的库列表](https://openid.net/developers/jwt-jws-jwe-jwk-and-jwa-implementations/)。

要了解有关 JWT 授权方的更多信息，请参阅 [在 API Gateway 中使用 JWT 授权方控制对 HTTP API 的访问](http-api-jwt-authorizer.md)。