Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Nodejs: Using Connect’s BasicAuth with Express

DZone's Guide to

Nodejs: Using Connect’s BasicAuth with Express

· Web Dev Zone ·
Free Resource

Code something amazing with the IBM library of open source blockchain patterns. Content provided by IBM.

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

Start coding something amazing with our library of open source Cloud code patterns. Content provided by IBM.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}