some wms or wfs sources require user and password authentication. for example https://apps.sogelink.fr/maplink/public/wfs?request=GetCapabilities need Basic authentication. How can I inject this authentication?
1 Answer
You can provide your own imageLoadFunction to an ImageWMS source.
The default one just takes the URL and inserts it as the src of the img tag:
ol.source.Image.defaultImageLoadFunction = function(image, src) {
image.getImage().src = src;
};
That question was already asked on the OpenLayers GitHub, here is an example from there:
function customLoader(tile, src) {
var client = new XMLHttpRequest();
client.open('GET', src);
client.setRequestHeader('foo', 'bar');
client.onload = function() {
var data = 'data:image/png;base64,' + btoa(unescape(encodeURIComponent(this.responseText));
tile.getImage().src = data;
};
client.send();
}
The documentation of OpenLayers is really good. Just find an example that uses features you want and then follow the links to the API docs.The ol.source.Vector doc even includes an example of a loading function for WFS, where you could manipulate the request:
new ol.source.Vector({
format: new ol.format.GeoJSON(),
loader: function(extent, resolution, projection) {
var wfsUrl = 'TODO';
var xhr = new XMLHttpRequest();
// see above example....
}
});
9 Comments
ericire
hello It is very difficult to post comments, because the number of caracters are limited and the add comment box is very little.moreover I no longer have the possibility to enter formatted code. copy past sometimes removes line breaks. In short, I do not know how to do it easily. I will try to split my comment.
ericire
I have already seen this answer but I do not know how to apply it here and then it only concerns wms, what about the wfs?
ericire
My try : //image dict var imagedict = new ol.layer.Image({ title: 'dict raster', opacity: 1.0, source: new ol.source.ImageWMS({ url: 'apps.sogelink.fr/maplink/public/wms?request=GetCapabilities', params: {FORMAT: 'image/png'}, imageLoadFunction: function customLoader(tile, src)
ericire
{ var client = new XMLHttpRequest(); var user = '[email protected]'; var pass = '#####'; client.open('GET', src); //client.setRequestHeader('foo', 'bar'); client.setRequestHeader("Authorization", "Basic " + btoa(user + ":" + pass));
ericire
client.onload(function() { var data = 'data:image/png;base64,' + btoa(unescape(encodeURIComponent(this.responseText))); tile.getImage().src = data; }); client.send(); } }) });
|