express-使用HTTP头在Node.js中进行基本身份验证

2021-09-27  本文已影响0人  一只飞
const express           =require('express');
const app = express();

const configJson = {
    servePort:4000,
    username:'admin',
    password:'admin',
};

app.all("*",function(req,res,next){
    //设置允许跨域的域名,*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin",'*');
    //允许的header类型
    res.header("Access-Control-Allow-Headers","content-type,x-requested-with,x-csrf-token,x-token");
    //跨域允许的请求方式
    res.header("Access-Control-Allow-Methods","DEvarE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200);  //让options尝试请求快速结束
    else
        next();
});
function authentication(req, res, next) {
    var authheader = req.headers.authorization;
    if (!authheader) {
        var err = new Error('身份未认证');
        res.setHeader('WWW-Authenticate', 'Basic');
        err.status = 401;
        return next(err)
    }
    var auth = new Buffer.from(authheader.split(' ')[1],
    'base64').toString().split(':');
    var user = auth[0];
    var pass = auth[1];
    if (user == configJson.username && pass == configJson.password) {
        console.log('身份认证成功');
        // If Authorized user
        next();
    } else {
        var err = new Error('身份未认证');
        res.setHeader('WWW-Authenticate', 'Basic');
        err.status = 401;
        return next(err);
    }
 
}
app.use(authentication);
app.get("/index",(req,res)=>{
    res.sendFile(__dirname+"/"+"flv.html"); 
})

let server = app.listen(configJson.servePort, function () {
    let host = server.address().address;
    let port = server.address().port;
    console.log("启动 config web 服务: http://%s:%s", host, port);
});

参考:https://www.geeksforgeeks.org/basic-authentication-in-node-js-using-http-header/

上一篇下一篇

猜你喜欢

热点阅读