微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 Express JS 的基本身份验证

如何解决使用 Express JS 的基本身份验证

我正在尝试使用 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

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。