使用Node JS在api中检查用户名和密码的几种方法?

时间:2018-12-27 07:50:52

标签: javascript node.js

我有一个测试API。在此api中,我在解析后从“ curl -u username:password”获取用户名和密码。但是我不想解析每个api中的用户名和密码。我们可以通过任何方式做到这一点吗? 示例:

    app.get('/test',function(req,res){
        var header=req.headers['authorization']||'',        
        token=header.split(/\s+/).pop()||'',            // and the encoded auth token
        auth=new Buffer.from(token, 'base64').toString(),    // convert from base64
        parts=auth.split(/:/),                          // split on colon
        username=parts[0],
        password=parts[1];
"'+password+'"')
        if(username=="username" && password=="password"){
            res.status(200).json({
                "data":"/v1/test"
            });
        }else
        res.status(422).json({
            "error":"Invalid Username Password"
        });

    });*

1 个答案:

答案 0 :(得分:3)

您可以尝试表达中间件。

const checkUsernameAndPassword = (req, res, next) => {
    var header=req.headers['authorization']||'',        
        token=header.split(/\s+/).pop()||'',            // and the encoded auth token
        auth=new Buffer.from(token, 'base64').toString(),    // convert from base64
        parts=auth.split(/:/),                          // split on colon
        username=parts[0],
        password=parts[1];
"'+password+'"')
        if(username=="username" && password=="password"){
            return next();
        } else {
            return res.status(422).json({
                "error":"Invalid Username Password"
            });
        }
};

app.get('/test', checkUsernameAndPassword, function(req,res){
    return res.status(200).json({ "data":"/v1/test" });
});