Noam
Noam

Reputation: 5266

Secure google maps api key in an angular app

I'm using angular and google maps. In all the tutorials I find, the instruction says something as: add to your index.html code:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY" type="text/javascript"> </script>

In this method, the API key is stored in my source code - which is not recommended.

How do I do this differently in angular?

Upvotes: 4

Views: 2776

Answers (2)

kenef
kenef

Reputation: 183

I know this was asked a while ago but I just came across this while looking for answers to the same question. Here's what I came up with:

  1. I protect my key by referrer URL.
  2. I created a service that holds my google maps types and modules imports. The service handles all things Google Maps API related. In the service, I created a string property of the google script tag with my api key in it, I also gave the script tag a custom id="" attribute. Then, in the constructor of my new service, I check for the existence of the tag with if ( !document.getElementById('my-custom-id') ) { append script } if the tag is not found, the constructor will append it to the <head> tag.

The intent is that the script tag is never present in the head tag unless the user is accessing a component that actually needs it. My implementation of this is behind a login, thus you need to be logged in to access the component with the Google Maps API functionality. Scrapers would need to bypass the login to find the script tag (not going to happen).

Upvotes: 0

HanJeaHwan
HanJeaHwan

Reputation: 1026

usually i will restrict my api key by referrer URLs.

https://developers.google.com/maps/api-key-best-practices#apply_apikey_restrictions

Upvotes: 1

Related Questions