Skip to content

Instantly share code, notes, and snippets.

@flesch
Last active July 27, 2022 12:39
Show Gist options
  • Save flesch/7323594 to your computer and use it in GitHub Desktop.
Save flesch/7323594 to your computer and use it in GitHub Desktop.
HTTP Basic Authentication with Express, without express.basicAuth.
var express = require("express");
var app = express();
app.get("/restricted", function(req, res, next){
// Grab the "Authorization" header.
var auth = req.get("authorization");
// On the first request, the "Authorization" header won't exist, so we'll set a Response
// header that prompts the browser to ask for a username and password.
if (!auth) {
res.set("WWW-Authenticate", "Basic realm=\"Authorization Required\"");
// If the user cancels the dialog, or enters the password wrong too many times,
// show the Access Restricted error message.
return res.status(401).send("Authorization Required");
} else {
// If the user enters a username and password, the browser re-requests the route
// and includes a Base64 string of those credentials.
var credentials = new Buffer(auth.split(" ").pop(), "base64").toString("ascii").split(":");
if (credentials[0] === "username" && credentials[1] === "password") {
// The username and password are correct, so the user is authorized.
return res.send("Access Granted!");
} else {
// The user typed in the username or password wrong.
return res.status(403).send("Access Denied (incorrect credentials)");
}
}
});
app.listen(3000, function(){
console.log("-> http://localhost:3000/");
});
@behnammodi
Copy link

change line 25 status code to 401

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment