Autenticación usando API keys al acceder a la API a través de fetch

¡Hola!

Estoy construyendo un sitio de WordPress sin cabeza (headless) para una revista que tiene su comunidad en Discourse, y los comentarios deben integrarse en las páginas de los artículos. Encontré la documentación de la API y estaba muy contento, ya que el incrustado en iframe no era realmente lo que buscaba, dado que el sitio tendrá modo oscuro y claro, por lo que necesito que la plantilla de comentarios herede las variables CSS del elemento raíz.

Sin embargo, sigo tropezando con el límite de velocidad cuando intento acceder a la API directamente (usando fetch en https://discourseurl.com/t/{id}.json), así que pensé en intentar agregar una clave de API y autenticarme con ella.

Estoy usando este código:

fetch(this.apiUrl, {
        headers: {
          'User-Api-Key': '{clave de API de usuario de la administración de Discourse}',
        },
      })

Y obtengo este error, sin importar qué clave use (incluso probando con una clave de administrador):

error_type: "invalid_access"
errors: Array [ "No tienes permiso para ver el recurso solicitado." ]

Traducción aproximada: “No tienes acceso al recurso solicitado”.

¿Me estoy perdiendo algo en cuanto a cómo funcionan las claves de API? ¿Cuál sería el enfoque recomendado para solicitar estos puntos de la API sin alcanzar el límite de velocidad?

1 me gusta

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 Me gusta

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 Me gusta

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 Me gusta