Skip to content

Instantly share code, notes, and snippets.

@kwhinnery
Created May 26, 2014 13:48
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save kwhinnery/eefd33883e49cde32854 to your computer and use it in GitHub Desktop.
Save kwhinnery/eefd33883e49cde32854 to your computer and use it in GitHub Desktop.
HTTP Basic Authentication with Express 4 using the http-auth module
var express = require('express'),
auth = require('http-auth');
// Configure basic auth
var basic = auth.basic({
realm: 'SUPER SECRET STUFF'
}, function(username, password, callback) {
callback(username == 'admin' && password == 'f00lpr00f');
});
// Set up express app
var app = express();
// Create middleware that can be used to protect routes with basic auth
var authMiddleware = auth.connect(basic);
// Configure an unprotected route
app.get('/', function(request, response) {
response.send('This is the secret route: <a href="/secret">shhhhhhh!</a>');
});
// Protected route
app.get('/secret', authMiddleware, function(request, response) {
response.send('you made it!');
});
app.listen(3000);
@osnysantos
Copy link

osnysantos commented Sep 22, 2016

I'm using this code but even typing the correct user/pass it keep asking me again.

'use strict';

var express = require('express');
var app = express();
var auth = require('http-auth');

var basic = auth.basic({
  realm: 'SUPER SECRET STUFF'
}, function(username, password, callback) {
  callback(username == 'username' && password == 'password');
});

app.use(auth.connect(basic));

app.use("/", express.static('www'));

app.listen(4001, function() {
  console.log('Node app is running on port', app.get('port'));
});

In my case I want to protect my static files that live on www folder, I'm using this code to achieve this:

app.use("/", express.static('www'));

Do you know why it's now working properly @kwhinnery?

@SamDecrock
Copy link

Works perfect! Thanks

@sekcompsci
Copy link

If you want to log out?

@Juni4567
Copy link

Gives the following error:

TypeError: auth.connect is not a function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment