

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 對 HTTP API JWT 授權方的問題進行疑難排解
<a name="http-api-troubleshooting-jwt"></a>

以下建議說明當您在搭配 HTTP API 使用 JSON Web Token (JWT) 授權方時，如何對可能遇到的錯誤和問題進行疑難排解。

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

檢查 API 回應中的 `www-authenticate` 標頭。

下列命令會用 `curl` 來將請求傳送至 API，並使用 JWT 授權方 `$request.header.Authorization` 做為其身分識別來源。

```
$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` 標頭會顯示字符並未發給有效的對象。若 API Gateway 要授權請求，JWT 的 `aud` or `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)。