I need to send authorization request using basic auth. I have successfully implemented this using jquery. However when I get 401 error basic auth browser popup is opened and
As others have pointed out, the only way to change the browser's behavior is to make sure the response either does not contain a 401 status code or if it does, not include the WWW-Authenticate: Basic
header. Since changing the status code is not very semantic and undesirable, a good approach is to remove the WWW-Authenticate
header. If you can't or don't want to modify your web server application, you can always serve or proxy it through Apache (if you are not using Apache already).
Here is a configuration for Apache to rewrite the response to remove the WWW-Authenticate header IFF the request contains contains the header X-Requested-With: XMLHttpRequest
(which is set by default by major Javascript frameworks such as JQuery/AngularJS, etc...) AND the response contains the header WWW-Authenticate: Basic
.
Tested on Apache 2.4 (not sure if it works with 2.2).
This relies on the mod_headers
module being installed.
(On Debian/Ubuntu, sudo a2enmod headers
and restart Apache)
# Make sure that if it is an XHR request,
# we don't send back basic authentication header.
# This is to prevent the browser from displaying a basic auth login dialog.
Header unset WWW-Authenticate "expr=req('X-Requested-With') == 'XMLHttpRequest' && resp('WWW-Authenticate') =~ /^Basic/"