📜 ⬆️ ⬇️

How basic authentication in ExpressJS works

Express.JS has built-in middleware for authorization. If you really want to block access to the application, all you need to do is add one line to the express-application setup:
app.use(express.basicAuth('username', 'password')); 

Also middleware supports an alternative option - with a callback:
 app.use(express.basicAuth(function(user, pass, next) { var result = (user === 'testUser' && pass === 'testPass'); next(null /* error */, result); })); 

And if you need to restrict access only to certain urls, the middleware can be used not globally, but only within the framework of the router. That is so:
 var auth = express.basicAuth(function(user, pass, next) { var result = (user === 'testUser' && pass === 'testPass'); next(null, result); }); app.get('/home', auth, function(req, res) { res.send('Hello World'); }); 

If you do not climb under the hood - this can be finished. Those who are on the Venn diagram between the circles “I’m wondering what’s inside” and “I don’t know how the basic apache authorization works,” I invite you to the cat.

basicAutn inherited express as a legacy of connect . It is set up quite simply - when the browser requests a page from the server, the server informs the browser about the need for authorization using the WWW-Authenticate header:
  res.statusCode = 401; res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"'); res.end('Unauthorized'); 

In response to this, the browser draws a login and password entry form, and, waiting for the user to finish with the input, sends a second request to the server. This time, the request will already contain the Authorization:Basic dXNlcm5hbWU6cGFzc3dvcmQ= , where dXNlcm5hbWU6cGFzc3dvcmQ= is nothing more than the string 'username: password'. This is easily seen:
 var str = new Buffer('dXNlcm5hbWU6cGFzc3dvcmQ=', 'base64').toString() console.log(str) //  'username:password' 

Now the browser will attach this line to each request, and basicAuth will diligently check whether the user data is correct in the request. This mechanism is not secure, but if you need to quickly and simply restrict access to the project - this is quite suitable.

The source code for what happens inside basicAuth can be found in the connect documentation.

')

Source: https://habr.com/ru/post/201924/


All Articles