DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > Nodejs: Using Connect’s BasicAuth with Express

Nodejs: Using Connect’s BasicAuth with Express

Chad Lung user avatar by
Chad Lung
·
Jan. 26, 12 · Web Dev Zone · Interview
Like (0)
Save
Tweet
5.16K Views

Join the DZone community and get the full member experience.

Join For Free

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

Express

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Dynamically Provisioning Persistent Volumes with Kubernetes
  • Modern Application Security Requires Defense in Depth
  • The Importance of Semantics for Data Lakehouses
  • Java: Why Core-to-Core Latency Matters

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo