Hiding the API Key

I would like to make calls to the JSON API at various points. Sometimes, I need to provide an API key–so I generate one on the admin dashboard, and need to include it in the API call. For example:

var token = [API KEY]
$.ajax({
     url: 'https://myforum.com/groups/[groupname].json',
      contentType: "application/json",
      headers: {
          "Api-Key": token,
          "Api-Username": "[username]"
        },
        dataType: 'json',
        success: function(result){
             console.log('result = ' + result);
         }
})

Is there a way for me to protect this key so that it is not visible to users?

Right now, my solution is to have this function occur off my Discourse app–so my app would call an endpoint housed elsewhere that would then call this function. That way, the API Key is in a function stored separately from my Discourse app, and my app only knows the endpoint.

BUT, it would be cleaner if I could include this function within my Discourse app, for example in a theme or plugin. But it seems to me that no matter what, if it is part of the code, a user can view the API Key.

Is there a way to hide the API Key?

An app doing any kind of sensitive API requests will want do do those in the backend, instead of the front end.

You get many benefits, like custom caching, parallel API calls, security, etc. It isn’t a good idea to do this in JS code running in the client.

4 Likes

Thanks. I’ve set up a backend structure to handle the API request, but it is separate from my discourse instance (not connected to discourse at all). Is there a way to have this occur on the back-end of the discourse app itself?

I assume it depends on how/where your discourse instance is hosted. Would there be a way to link to the backend for an app hosted with discourse.org?

You need to build it in rails in a plugin and be on a plan that permits the addition of 3rd party plugins.

2 Likes