OpenLayers Authentication – Using HTTP Basic Authentication with OpenLayers

authenticationjavascriptopenlayers-2

I am trying to use OpenLayers 2.12 to display WMS layers from a server which has HTTP Basic Authentication enabled.

I have tried to handle the authentication by putting the username and password in the URL parameter in my JavaScript code. Example layer creation:

myLayer = new OpenLayers.Layer.WMS('background',
        'https://username:password@ws.nls.fi/rasteriaineistot/image?',
        {
            layers: 'background',
            bbox: '-380188,6249943,1347312,8226943'
        },                                   
        {
            displayInLayerSwitcher: true,
            isBaseLayer: false,
            projection: 'EPSG:3067',
            visibility: true
        });

Of course this is not secure since the credentials are stored in JavaScript code and does not work in all browsers. Internet Explorer 8 gives security error pointing to OpenLayers.js and refuses to display the map at all. Firefox 13 pops up some authentication dialogs which I can cancel(the map displays correctly after that). In Chrome 23 the authentication seems to work flawlessly.

Can you confirm that it is not possible to handle the HTTP basic authentication in a cross-browser manner by encoding it in the URL and giving it to OpenLayers like in the example?

Can you suggest alternative ways to handle the HTTP basic authentication so that it works transparently to the user (no authentication popups displayed)? Perhaps use some kind of proxy server to work around this.

Best Answer

The solution we ended up with was to add an authenticating proxy server between the OpenLayers client and the backend WMS service. So instead of connecting directly to the WMS service the OpenLayers client connects to a proxy server which adds the required authentication headers to the requests.

Example code for creating the layers:

var layer = new OpenLayers.Layer.WMS( "background", "http://myproxyaddress.com/23ergwe435dw3463", {layers: 'basic'} );

Example Apache proxy configuration:

ProxyRequests     Off
ProxyPreserveHost On
SSLProxyEngine On
<Proxy *>
    Order deny,allow
    Allow from all
</Proxy>
SetEnvIf Request_URI "23ergwe435dw3463" wms_provider_name
RequestHeader set Authorization: "Basic Xk12BLdVNzUo5UGl0po5Y" env=wms_provider_name
ProxyPass         /23ergwe435dw3463  https://wmsprovideraddress.com
ProxyPassReverse  /23ergwe435dw3463  https://wmsprovideraddress.com

You can have multiple proxy configurations using this style.

What you should put inside the Authorization quotes is just the base-64 encoding of the string "username:password" (without the quotes). For more information see this link: https://stackoverflow.com/questions/567814/apache2-reverse-proxy-to-an-end-point-that-requires-basicauth-but-want-to-hide-t

Related Question