Over a million developers have joined DZone.

Nodejs: Using Connect’s BasicAuth with Express

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Connect is a middleware framework for Nodejs and is used in several projects like Express. Today I’ll show you a very simple way to use the BasicAuth capabilities of Connect inside of an Express application. You might also want to check out my previous post on using Connect with Express.

Note: BasicAuth is much better off when used in conjunction with SSL – in this article though I’m not going to use SSL for the sake of simplicity.

When you use Express you can easily add in Connect middleware. This makes it very easy to do BasicAuth.

var express = require('express');
 
function authorize(username, password) {
    return 'someone' === username & 'password' === password;
}
 
var app = express.createServer(
    express.basicAuth(authorize)
);
 
app.get('/', function(request, response) {
    response.send('Authorized!');
});
 
console.log('Starting server...')
app.listen(8080);
 

This is one way to do it. There are several other examples out there you can also look at as well as this one to protect specific routes.

Run the above code and attempt to access http://localhost:8080 and you should be prompted for a username and password.

 

From http://www.giantflyingsaucer.com/blog/?p=3530

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}