المصادقة باستخدام مفاتيح API عند الوصول إلى الـ API عبر fetch

مرحبًا!

أقوم ببناء موقع ووردبريس بدون واجهة أمامية (headless) لمجلة، ولديهم مجتمعهم على Discourse، ويتم دمج التعليقات في صفحات المقالات. لقد وجدت وثائق الـ API وسعدت جدًا، حيث أن تضمين iframe لم يكن ما كنت أبحث عنه حقًا، لأن الموقع سيحتوي على وضع ليلي ونهاري، لذا أحتاج إلى قالب التعليقات ليرث متغيرات CSS من العنصر الجذر.

ومع ذلك، أستمر في الوصول إلى حد معدل الطلبات (rate limit) عند محاولة الوصول إلى الـ API مباشرة (باستخدام fetch على https://discourseurl.com/t/{id}.json)، لذا فكرت في تجربة إضافة مفتاح API والمصادقة باستخدامه.

أستخدم هذا الكود:

fetch(this.apiUrl, {
        headers: {
          'User-Api-Key': '{مفتاح API الخاص بالمستخدم من لوحة تحكم Discourse}',
        },
      })

وأحصل على هذه الرسالة، بغض النظر عن المفتاح الذي أستخدمه (حتى عند تجربة مفتاح المسؤول):

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

تقريبًا الترجمة: “ليس لديك صلاحية لعرض المورد المطلوب”.

هل هناك شيء أفتقده فيما يتعلق بكيفية عمل مفاتيح الـ API؟ ما هو النهج الموصى به لطلب نقاط نهاية الـ API هذه دون الوصول إلى حد معدل الطلبات؟

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.

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.

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: