Basic HTTP authentication with Node and Express 4

后端 未结 9 2089
萌比男神i
萌比男神i 2020-11-29 15:48

It looks like implementing basic HTTP authentication with Express v3 was trivial:

app.use(express.basicAuth(\'username\', \'password\'));

V

9条回答
  •  忘掉有多难
    2020-11-29 16:40

    There seems to be multiple modules to do that, some are deprecated.

    This one looks active:
    https://github.com/jshttp/basic-auth

    Here's a use example:

    // auth.js
    
    var auth = require('basic-auth');
    
    var admins = {
      'art@vandelay-ind.org': { password: 'pa$$w0rd!' },
    };
    
    
    module.exports = function(req, res, next) {
    
      var user = auth(req);
      if (!user || !admins[user.name] || admins[user.name].password !== user.pass) {
        res.set('WWW-Authenticate', 'Basic realm="example"');
        return res.status(401).send();
      }
      return next();
    };
    
    
    
    
    // app.js
    
    var auth = require('./auth');
    var express = require('express');
    
    var app = express();
    
    // ... some not authenticated middlewares
    
    app.use(auth);
    
    // ... some authenticated middlewares
    

    Make sure you put the auth middleware in the correct place, any middleware before that will not be authenticated.

提交回复
热议问题