How to protect Google Maps API key on Ionic app?

前端 未结 2 1603
盖世英雄少女心
盖世英雄少女心 2021-01-17 15:24

I have Ionic PWA app published for Android and iOS (I used Capacitor to generate the native build). In the frontend code, it has my Google Maps API key, however, I can\'t re

相关标签:
2条回答
  • 2021-01-17 15:56

    In order to protect your API key you have to check the value of the window.location.href within a webview. I guess you will see something like file://some/path.

    So you will need apply HTTP referrer restriction for this path. Note that URLs with a file:// protocol require special representation as explained in

    https://developers.google.com/maps/documentation/javascript/get-api-key#restrict_key

    Note: file:// referers need a special representation to be added to the key restriction. The "file://" part should be replaced with "__file_url__" before being added to the key restriction. For example, "file:///path/to/" should be formatted as "__file_url__//path/to/*". After enabling file:// referers, it is recommended you regularly check your usage, to make sure it matches your expectations.

    I hope this helps.

    0 讨论(0)
  • 2021-01-17 15:58

    You can configure the hostname of capacitor apps

    "server": {
        // You can configure the local hostname, but it's recommended to keep localhost
        // as it allows to run web APIs that require a secure context such as
        // navigator.geolocation and MediaDevices.getUserMedia.
        "hostname": "unique-app",
      }
    

    and then restrict the the API keys to capacitor://unique-app

    https://capacitor.ionicframework.com/docs/basics/configuring-your-app

    0 讨论(0)
提交回复
热议问题