node.js basic auth in express.js
The first 2 lines import express node module and create an express app instance.
The 3rd line import the basic-auth node module.
The auth function takes 3 parameters, req for request object, res for response object and a callback function next which is called upon successful authentication.
The first app.get()
calls the get function from the express app instance. It gives 3 arguments, the first one is an url path, the second one is the auth function defined above, and the third is a function to handle the incoming request. When a get request is made to localhost:3030/auth, it first calls the auth function, if the auth function returns the callback function next, it will then go on to execute the function that was passed in as the thrid parameter in the app.get()
. If the auth function identifies the credentials are not valid, it sends a 401 not found and no callback is returned.
var express = require("express"); var app = express(); var basicAuth = require('basic-auth'); var auth = function (req, res, next) { var user = basicAuth(req); if (!user || !user.name || !user.pass) { res.set('WWW-Authenticate', 'Basic realm=Authorization Required'); res.sendStatus(401); return; } if (user.name === 'amy' && user.pass === 'passwd123') { next(); } else { res.set('WWW-Authenticate', 'Basic realm=Authorization Required'); res.sendStatus(401); return; } } app.get("/auth", auth, function (req, res) { res.send("This page is authenticated!") }); app.listen(3030); console.log("app running on localhost:3030");
To run the code. Install express and basic-auth node modules from npm and start the app.js
sudo npm install express sudo npm install basic-auth node app.js
To make the get request from a browser, just go to the url localhost:3030/auth
To make the get request using the curl command from command line window.
curl --user amy:passwd1232 http://localhost:3030/auth
To make the request using node request, install the node request module sudo npm install request
and save the following to a file get_request.js and run it with node a_request.js
var request = require('request'); var headerOption = { "url": "http://localhost:3030/auth/", "headers": { "Authorization" : "Basic " + new Buffer("amy:passwd123").toString("base64") } }; request(headerOption, function (error, response, body) { //console.log("Error: ", error); //console.log("Response:", response); console.log("Body:", body); } );
The express function all, app.all() can be used to which url path need the authentication.
app.all("*", auth);
will make all the endpoints to require authentication.
app.all("/admin/*");
will make all the endpoints starting with localhost:3030/admin/ to require authentication.
app.all("/auth", auth);
will make the endpoint localhost:3030/auth to require authentication.
var express = require("express"); var app = express(); var basicAuth = require('basic-auth'); var auth = function (req, res, next) { var user = basicAuth(req); if (!user || !user.name || !user.pass) { res.set('WWW-Authenticate', 'Basic realm=Authorization Required'); res.sendStatus(401); } if (user.name === 'amy' && user.pass === 'passwd123') { next(); } else { res.set('WWW-Authenticate', 'Basic realm=Authorization Required'); res.sendStatus(401); } } //This line add the authentication requirement to all pages starting with localhost:3030/admin/ app.all("/admin/*", auth); app.get("/auth", auth, function (req, res) { res.send("This page is authenticated!") }); app.get("/admin/adminPage1", function (req, res) { res.send("Admin page1 is authenticated!"); }); app.get("/admin/adminPage2", function (req, res) { res.send("Admin page2 is authenticated!"); }); app.get("/page1", function (req, res) { res.send("Page1 is publicly available!"); }); app.get("/page2", function (req, res) { res.send("Page2 is publicly available!"); }); app.listen(3030); console.log("app running at localhost:3030");
Save the above to app.js and run it with node app.js
and try make some requests using curl or in a browser.
curl http://localhost:3030/page1 curl http://localhost:3030/page2 curl http://localhost:3030/auth curl http://localhost:3030/admin/adminPage1 curl http://localhost:3030/admin/adminPage2 curl --user amy:passwd123 http://localhost:3030/auth curl --user amy:passwd123 http://localhost:3030/admin/adminPage1 curl --user amy:passwd123 http://localhost:3030/admin/adminPage2
Search within Codexpedia
Search the entire web