12

How do I set a request header for a wms source with mapbox-gl-js? I need all tile requests to add a header that looks like:

Authorization: "Bearer base64-encoded-token"

The WMS example, map#addSource and map#addLayer lead me to believe it is not possible to set tile request headers.

Pete
  • 10,310
  • 7
  • 53
  • 59

1 Answers1

23

You can now use the transformRequest option to add a custom header:

A callback run before the Map makes a request for an external URL. The callback can be used to modify the url, set headers, or set the credentials property for cross-origin requests. Expected to return an object with a url property and optionally headers and credentials properties.

Example:

const map = new mapboxgl.Map({
  container: 'map',
  center: [2.35, 48.86],
  zoom: 13,
  transformRequest: (url, resourceType) => {
    if (resourceType === 'Source' && url.startsWith('http://myHost')) {
      return {
        url: url,
        headers: { 'Authorization': 'Bearer ' + yourAuthToken }
      }
    }
  }
});
Tanner Semerad
  • 12,472
  • 12
  • 40
  • 49
ThunderDev
  • 1,118
  • 2
  • 19
  • 38
  • Steve Bennett and ThunderDev, does this still works with current GL JS release? I am sending authorization to server but my map is not authorizing. – Devil's Dream Oct 12 '19 at 11:27
  • 2
    Mapbox's api docs still mention this option along with an similar example, so yes, I believe it should still work with the current release. You might have a problem with your auth token. – ThunderDev Oct 14 '19 at 19:46
  • @ThunderDev if I understand correctly, this would add a 'hidden' authorization code in the `header` of the request so others can't peep into the browser's network tools and use my token? I am integrating it in Wordpress and your reply would be greatly appreciated. Thanks. – Raging Vids Jan 07 '22 at 21:29
  • @RagingVids I think you are talking about your mapbox access token, this cannot be hidden unfortunatly. – ThunderDev Jan 10 '22 at 16:56
  • @ThunderDev maybe I am missing something then, how could anyone protect their tokens then? Is it even fair to openly make them visible so anyone can come in and enjoy free map loads off of others? I'm not too experienced in network calls so please excuse me for the naivety. – Raging Vids Jan 11 '22 at 09:42
  • @RagingVids usually there is a domain restriction, eg. a token is only valid if called from your specific domain. If you need more information on this, I would suggest to open a new question if that's ok with you. – ThunderDev Jan 11 '22 at 18:24
  • @ThunderDev I would do that but the community has been unwelcoming lately, down votes for no reason. And I do provide screenshots and codes for reference. Anyway, thanks. – Raging Vids Jan 12 '22 at 13:16