Access blob storage using basic authentication

This node.js snippet will start a web server which uses basic authentication (username and password) to provide access to blob storage (i.e. private containers). You should enter the storage name and access key as the username and password.

WARNING: Be careful when disclosing your storage account key, basic authentication is not encrypted.

var http = require('http');
var azure = require('azure');

http.createServer(function (request, response) {
    if (request.headers.authorization) {
        var userAndPassword = decodeBasicAuth(request);
        var blobService = azure.createBlobService(userAndPassword.username, userAndPassword.password, "blob.core.windows.net").withFilter(new azure.ExponentialRetryPolicyFilter());
        var path = request.url.split('/');

        if (path.length >= 3) {
            getBlob(path[1], request.url.substring(path[1].length + 2), response, blobService);
        }
        else {
            getBlob("$root", request.url.substring(1), response, blobService);
        }
    }
    else {
        response.writeHead(401, {"WWW-Authenticate": 'Basic realm="Azure Storage"'});
        response.end();
    }
}).listen(80);

function decodeBasicAuth(request) {
    if (request.headers.authorization) {
        var encodedheader = request.headers.authorization.replace("Basic ", "");
        var decodedheader = new Buffer(encodedheader, 'base64').toString('ascii');
        var userAndPassword = decodedheader.split(":");
        return { username: userAndPassword[0], password: userAndPassword[1] };
    }
    return {};
}

function getBlob(container, blob, response, blobService) {
    blobService.getBlobToStream(container, blob, response, function(error){
        if(!error){
            response.writeHead(200);
            response.end();
        }
        else {
            response.writeHead(404);
            response.end(error);
        }
    });
}
Advertisements