【问题标题】:A Basic Authentication using Express JS使用 Express JS 的基本身份验证
【发布时间】:2021-07-30 04:02:46
【问题描述】:

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

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 到 localhost 服务器时,我从服务器得到一个空的回复。 找到下面的图片以及如何去做。

【问题讨论】:

    标签: javascript express curl localhost


    【解决方案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!'));
    

    【讨论】:

    • 如果用户不卷曲正确的凭据,我将如何在 if 语句中包含其他条件。我如何考虑这一点
    猜你喜欢
    • 1970-01-01
    • 2019-09-02
    • 2014-09-15
    • 2015-08-12
    • 2014-06-30
    • 1970-01-01
    • 2017-06-13
    • 2013-05-30
    • 2016-06-17
    相关资源
    最近更新 更多