d4rty d4rty - 2 months ago 9
Ajax Question

How to serve a download of a file which is protected via HTTP authentication

On a server I have several files which are protected via HTTP authentication.

Now I want to create download buttons on my HTML page to download these files. I already read that downloading a file via JavaScript/AJAX isn't possible due to security reasons. See this question.

Furthermore via an "normal" download link/button like this:

<a href="..." download>
it isn't possible to set the HTTP Header to provide HTTP authentication.

Is there any possibility to make a download button/link to a file with HTTP Basic authentication.

Furthermore to give a little bit more detail about my usecase, I don't want to use sessions.

Answer

You can try the username:password syntax in the url:

<a href="username:password@example.com/file.zip">Download</a>

However, do note that browser manufacturers have started removing support for this for security reasons. IE and Chrome no longer support it.

Workaround

As a work-around, you can make the request on your server instead of directly from the HTML in the browser. Just write a simple script that accept a request and fetches the password protected file.

Here's a simple node.js example using express and request:

var express = require('express');
var request = require('request');
var app = express();

app.get('remote-file',function(req,res){
    request.get('username:password@example.com/file.zip').pipe(res);
});

app.listen(80);

Yes, the request module supports username:password syntax.