使用 Express JS 的基本身份验证

A Basic Authentication using Express JS

我正在尝试使用 Express JS 对用户名和密码进行基本身份验证。我面临的问题是,我想在 app.use() 函数中使用 if 语句,但它似乎不会 return 任何东西。找到下面的代码片段,输出得到

const express = require('express');
const app = express();
const basicAuth = require('express-basic-auth');

app.get('/protected', (req,res)=>{
app.use(basicAuth({authorizer: myAuthorizer}))

function myAuthorizer(username, password){
    const userMatches = basicAuth.safeCompare(username, 'admin')
    const passwordMatches = basicAuth.safeCompare(password, 'admin')

    if(userMatches == 'admin' && passwordMatches == 'admin'){
        res.send("Welcome, authenticated client");
    }else{
        res.send("401 Not authorized");
    }
}});
app.listen(8080, ()=> console.log('Web Server Running on port 8080!'));

当我对本地主机服务器执行 curl 操作时,我从服务器收到空回复。 找到下面的图片以及如何去做。

也许,你should study Middlewares

const express = require('express');
const app = express();
const basicAuth = require('express-basic-auth');

function myAuthorizer(username, password) {
    const userMatches = basicAuth.safeCompare(username, 'admin')
    const passwordMatches = basicAuth.safeCompare(password, 'admin')

    return userMatches && passwordMatches
}

app.use(basicAuth({ authorizer: myAuthorizer }))

app.get('/protected', (req, res) => {
    
    res.send("Welcome, authenticated client");

});

app.listen(8080, () => console.log('Web Server Running on port 8080!'));