Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify Authorization Header for a source in mapbox-gl-js?

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.

like image 260
Pete Avatar asked Dec 02 '16 21:12

Pete


People also ask

How do I request a post with authorization header?

To send a request with the Bearer Token authorization header, you need to make an HTTP request and provide your Bearer Token with the "Authorization: Bearer {token}" header. A Bearer Token is a cryptic string typically generated by the server in response to a login request.

How do I add a source to Mapbox?

Add a vector source to a map. Add any Mapbox-hosted tileset using its tileset URL ( mapbox:// + tileset ID). To find a list of Default tilesets provided by Mapbox and Custom tilesets you have uploaded to your account, sign into Mapbox Studio and visit the Tilesets page.

How do I send the authorization header in HTTP?

The HTTP Authorization request header can be used to provide credentials that authenticate a user agent with a server, allowing access to a protected resource. The Authorization header is usually, but not always, sent after the user agent first attempts to request a protected resource without credentials.


Video Answer


1 Answers

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 }
      }
    }
  }
});
like image 170
ThunderDev Avatar answered Oct 07 '22 04:10

ThunderDev