I'm trying to make a set of tools to access my database. Most are to do with accessing data by my webapps, but I also need a page of my express powered site with a password for the site owner to provide an online tool for editing the database; all other routes will not require auth.
With express 3, basic-auth made adding such a password easy, but its functionality has been reduced with the middleware in Express 4 and with most of the online tutorials out of date. The new version of basic-auth will process authentication header info, but how do I trigger the login popup in the browser?
The code below is little more than boilerplate, so some hints on the world's simplest login would be welcome.
express = require('express')
app = express()
auth = require 'basic-auth'
port = Number(process.env.PORT || 9778);
app.listen port, () ->
console.log "Listening on port: " + port
app.use '/editor', (req, res) ->
user = auth req
if (user == "....") ...
console.log user
app.get '/editor', (req, res) ->
# if authenticated send 'editor.html' else....
res.send 401, "Need password"
At present I an adding authentication to access a page and then allowing that page to post to the CRUD node. I think I should really move to a proper REST API and require authentication on CUD?
According to the Basic Authentication spec, the server can request authentication by sending a WWW-Authenticate header with a 401 status code. The following worked for me:
res.set({
'WWW-Authenticate': 'Basic realm="simple-admin"'
}).send(401);
I put the in my own middleware which looks something like this:
var auth = require('basic-auth');
module.exports = function(req, res, next){
var user = auth(req);
if(validAuth){ // Here you need some logic to validate authentication
next();
} else {
res.set({
'WWW-Authenticate': 'Basic realm="simple-admin"'
}).send(401);
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With