authenticationleafletwms

WMS service basic authentication


I am building a leaflet map on a server without root access. I'd like to add a WMS service which is secured by basic authentication(username and password). There is a simple method in leaflet adding WMS services with L.tileLayer.wms but this does not work for secured WMS services. So is there a way I can authenticate at the wms server and receive the WMS tiles and parse them to leaflet? Adding the login credentials to the WMS URL (f.e. https://username:password@wmsserver.com)does not work for me.


Solution

  • When using basic authentication, you pass username and password in the header to the server:

    Authorization: Basic <credentials>
    

    <credentials> is the Base64 encoded username and password joined by a single colon :.

    You could use leaflet-wms-header to pass along a custom header. Unfortunately, I don't have any WMS server with basic authentication at hand for testing but here is an example based on the example provided by leaflet-wms-header:

    // untested code
    
    var wmsLayer = L.TileLayer.wmsHeader(
        'https://GEOSERVER_PATH/geoserver/wms?',
        {
            layers: 'YOUR_LAYER',
            format: 'image/png',
            transparent: true,
        },
        [
            { 
                header: 'Authorization', 
                value: `Basic ${btoa(username + ':' + password)}` 
            },
        ],
        null
    ).addTo(map);
    

    (btoa encodes the given string to a Base64 encoded string.)