I try to load WMS image layer with openlayers 4.6 and angular 5, the code is:
const syr_layer = new ol_layer_Image({
source: new ol_source_ImageWMS({
url: 'serverurl', crossOrigin: 'anonymous', serverType: 'geoserver',
params: { 'LAYERS': 'tst:syr'},
projection: 'EPSG:4326'
});
});
But it throws an error:
GET (myserverurl) 401 (An Authentication object was not found in the
SecurityContext)
How can I send authentication header with the GET request sent by openlayers?
For you purpose, you may want to use tileLoadFunction
(API doc) from ol.source.ImageWMS
To illustrate, you can look below. The 2 "secrets" are customLoader
and for authentication to uncomment req.setRequestHeader("Authorization", "Basic " + window.btoa(user + ":" + pass));
<!DOCTYPE html>
<html>
<head>
<title>Tiled WMS</title>
<link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script>
function customLoader(tile, src) {
var client = new XMLHttpRequest();
client.open('GET', src);
// Uncomment to pass authentication header
//req.setRequestHeader("Authorization", "Basic " + window.btoa(user + ":" + pass));
client.onload = function() {
tile.getImage().src = src;
};
client.send();
}
var layers = [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Tile({
extent: [-13884991, 2870341, -7455066, 6338219],
source: new ol.source.TileWMS({
url: 'https://ahocevar.com/geoserver/wms',
tileLoadFunction: customLoader,
params: {'LAYERS': 'topp:states', 'TILED': true},
serverType: 'geoserver',
// Countries have transparency, so do not fade tiles:
transition: 0
})
})
];
var map = new ol.Map({
layers: layers,
target: 'map',
view: new ol.View({
center: [-10997148, 4569099],
zoom: 4
})
});
</script>
</body>
</html>
The answer is mainly borrowed from How to add a http header to openlayers3 requests? but with some adaptations as the syntax provided was not working.
Thanks @Thomas, your answer isn't correct 100% but it clear the way for me to get the correct answer.
This is the tileLoader
function that worked for me:
private tileLoader(tile, src) {
const client = new XMLHttpRequest();
client.open('GET', src);
client.responseType = 'arraybuffer';
client.setRequestHeader('Authorization', 'Basic ' + btoa(user + ':' + pass));
client.onload = function () {
const arrayBufferView = new Uint8Array(this.response);
const blob = new Blob([arrayBufferView], { type: 'image/png' });
const urlCreator = window.URL || (window as any).webkitURL;
const imageUrl = urlCreator.createObjectURL(blob);
tile.getImage().src = imageUrl;
};
client.send();
}