ruby-on-railsrubyapisecurityapi-key

How to best secure an API key in an iframe widget


I am developing a Javascript widget which will be embedded on client sites using an Iframe.

The widget code makes an API call to my backend service using an API key. The API key for each different client will change.

At the moment, the API key is visible in the iframe src tag. This means that it is easy for anyone to find the API key in the page source and for unauthorised users to make API calls.

What is the best way of securing API access in this situation? I thought about using a client secret to encrypt the API key but that doesn't solve the problem as anyone who intercepts the key will still be able to be validated and make calls on the API backend.

There are a few questions online about this already but none with a detailed recommendation on how to go about the implementation.

My widget is HTML generated by a React.js application and the API backend is Ruby on Rails.


Solution

  • Google Maps allows you to embed maps like https://mapsurl.com/?address=123Street&api_key=KDFJSDKFHSH

    And the key is public. The reason it's safe is because they check the referrer URL. It can't be used on other websites because they will send the wrong referrer. So if you're creating a widget that people can embed in their sites, you can collect the URL from them that the embed will come from, and deny requests without that referrer.