A service worker that proxies browser-initiated fetch request to support HTTP Basic Authentication.
This is useful to support HTTP Basic Authentication in
<audio>
and
<video>
elements.
Previously, you could include credentials in src
URLs (eg. <video src="https://USERNAME:PASSWORD@example.com">
), but
this is now
disallowed by some web browsers.
Install from npm.
npm install --save http-basic-auth-proxy-worker
Install the worker.js
file at the root of your application or at a location that matches
your desired
scope.
module.exports = {
entry: {
main: "./src/index.js",
worker: "./node_modules/http-basic-auth-proxy-worker/worker.js"
}
};
Register the service-worker in your entrypoint script, and pass it its initial configuration.
window.addEventListener("load", async () => {
const registration = await window.navigator.serviceWorker.register(
"./worker.js"
);
const serviceWorker = registration.active;
if (serviceWorker) {
serviceWorker.postMessage({
baseURL: "https://example.com/",
proxyBaseURL: `${window.location.href}proxy/`,
username: "username",
password: "password"
});
}
});
The service worker must be configured before it can be used.
Name | Description |
---|---|
baseURL | Required The destination/backend base URL to proxy requests to. |
proxyBaseURL | Required The base URL of requests that you wish to proxy. Matching fetch requests will be proxied; others will be ignored. |
username | If present, an HTTP Basic Authentication header will be added, and the request.mode will be set to 'cors'. |
password | See "username" above. |
You must configure your web server to support CORS requests, by adding the requisite access control headers:
location / {
root /var/www/html;
autoindex on;
auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/cybertron.spacectrl.com.htpasswd;
add_header Access-Control-Allow-Credentials true always;
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Methods GET,POST,HEAD,DELETE,PUT,OPTIONS always;
add_header Access-Control-Allow-Headers authorization,chrome-proxy,range always;
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Credentials true always;
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Methods GET,POST,HEAD,DELETE,PUT,OPTIONS always;
add_header Access-Control-Allow-Headers authorization,chrome-proxy,range always;
return 204;
}
}