使用 Express JS 的基本身份验证

时间:2021-05-07 21:23:58

标签: javascript express curl localhost

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

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 到本地主机服务器时,我从服务器收到一个空回复。 找到下面的图片以及如何去做。 enter image description here

1 个答案:

答案 0 :(得分:1)

也许,你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!'));
相关问题