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

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}