fetch を通じて API にアクセスする際の API キーによる認証

こんにちは!

雑誌のヘッドレス WordPress サイトを構築しており、コミュニティは Discourse にあります。記事ページにコメントを統合しようとしています。API ドキュメントを見つけ、非常に喜んでいますが、iframe 埋め込みは望むものではなく、サイトがダークモードとライトモードの両方に対応するため、コメントテンプレートがルート要素から CSS 変数を継承する必要があります。

しかし、https://discourseurl.com/t/{id}.json に直接 API をアクセスしようとすると(fetch を使用して)、常にレート制限に引っかかってしまいます。そのため、API キーを追加して認証を試みることにしました。

以下のコードを使用しています:

fetch(this.apiUrl, {
        headers: {
          'User-Api-Key': '{Discourse 管理画面から取得したユーザー API キー}',
        },
      })

どのキーを使っても(管理者キーを試しても)以下のエラーが発生します:

error_type: "invalid_access"
errors: Array [ "Du har inte behörighet att visa den efterfrågade resursen." ]

(おおよその翻訳:「要求されたリソースを表示する権限がありません」)

API キーの仕組みについて何か見落としているのでしょうか?レート制限に引っかからずにこれらの API エンドポイントをリクエストするための推奨アプローチは何でしょうか?

「いいね!」 1

Have a look at the Authentication section that’s near the top of https://docs.discourse.org/. It gives an example of how to set your API credentials in the request header. You need to use Api-Key and Api-Username in the header.

「いいね!」 7

Thanks! Can’t imagine how I missed the auth part there, been looking through the docs over and over again :joy:

Anyway, I seem to be making some kind of progress, but I run into this issue now in the browser console:
(Reason: missing token ‘api-key’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).

I’m not sure what might be causing it, can’t find anything in the forum about it either. Am I missing something? Weird thing is that I am specifying the header as ‘Api-Key’ in my code. Any ideas? :slight_smile:

Sounds like you are building a JavaScript app and making the API requests from the browser?

The recommended approach would be to make the API calls to Discourse server side, and have your JavaScript app talk to your server just how it talks to WordPress. This way you avoid any CORS issues.

「いいね!」 3

Ah, awesome! This made me look through the WP Discourse code and realize I’m just an option away from WP exposing the API endpoint I need (exposing the Discourse comments via an API). I’ll just have to tweak it a little bit. That’s excellent, thanks a bunch :slight_smile:

Just curious, why isn’t it recommended to work directly against the Discourse API from the client side? I have some ideas on expanding on the project later on if there will be any budget (with a login functionality, for example), and I would like it to talk with the Discourse API. Would I have to route everything through Wordpress? :slight_smile:

「いいね!」 2