Basic HTTP authentication with Node and Express 4

后端 未结 9 2068
萌比男神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:46

    TL;DR:

    express.basicAuth is gone
    basic-auth-connect is deprecated
    basic-auth doesn't have any logic
    http-auth is an overkill
    express-basic-auth is what you want

    More info:

    Since you're using Express then you can use the express-basic-auth middleware.

    See the docs:

    • https://www.npmjs.com/package/express-basic-auth

    Example:

    const app = require('express')();
    const basicAuth = require('express-basic-auth');
     
    app.use(basicAuth({
        users: { admin: 'supersecret123' },
        challenge: true // <--- needed to actually show the login dialog!
    }));
    
    0 讨论(0)
  • 2020-11-29 16:54

    A lot of the middleware was pulled out of the Express core in v4, and put into separate modules. The basic auth module is here: https://github.com/expressjs/basic-auth-connect

    Your example would just need to change to this:

    var basicAuth = require('basic-auth-connect');
    app.use(basicAuth('username', 'password'));
    
    0 讨论(0)
  • 2020-11-29 16:54

    I used the code for the original basicAuth to find the answer:

    app.use(function(req, res, next) {
        var user = auth(req);
    
        if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
            res.statusCode = 401;
            res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
            res.end('Unauthorized');
        } else {
            next();
        }
    });
    
    0 讨论(0)
提交回复
热议问题