首页 > 解决方案 > 基本身份验证 ComparePassword

问题描述

我目前正在为 Node JS 开发“基本身份验证”。它应该接受如下请求:

POST http://localhost:8080/authenticate/
Authorization: Basic YWRtaW46MTIz

AuthenticationService.js首先读取标头,然后将整个内容传递给 Userservice.js

AuthenticationService.js

async function basicAuth(req, res, next) {
    // make authenticate path public
    if (req.path === '/') {
        return next();
    }

    
    if (!req.headers.authorization || req.headers.authorization.indexOf('Basic ') === -1) {
        return res.status(401).json({ message: 'Missing Authorization Header' });
    }

    // verify auth credentials
    const base64Credentials =  req.headers.authorization.split(' ')[1];
    const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
    const [username, password] = credentials.split(':');
    console.log("AuthenticationService "+username+" "+password);
    
    const user = await userService.authenticate({ username, password });
    if (!user) {
        return res.status(401).json({ message: 'Invalid Authentication Credentials' });
    }
    req.user=user
    res.send(user)
next();
}
module.exports = {
    basicAuth
}

用户服务检查是否找到用户并检查密码是否有效,然后才将用户对象发送回身份验证服务。

用户服务.js

async function authenticate({ username, password }) {
    
    
    let user = await User.findOne({userID: username})
        
     user.comparePassword(password.toString(), function(err,isMatch) {
        if (err){
            console.log("error")
            throw err;
        } 
            if(isMatch)
            {
                console.log("Password correct")
                
                
                
            }
            if(!isMatch){
                console.log("Password wrong")
                
                
            }});

if(user){
        return user; 
    }
    else{
        return null;
    } 
    
}

module.exports = {
    
    authenticate
}

.comparePassword-Method位于Usermodel.js内:

UserSchema.methods.comparePassword = function(candidatePassword, cb) {
    bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
        if (err) return cb(err);
        cb(null, isMatch);
    });
};
const User = mongoose.model("User", UserSchema);
module.exports = User;

如何在Userservice.js的范围之外发送isMatch的布尔值,以便我可以根据正确的密码将用户对象发送回AuthenticationService.js ?我该如何改进该代码?

标签: javascriptmongoosecrudbasic-authentication

解决方案


我删除Userservice.js中的身份验证方法,然后调用 crud-method。之后我调用compare-method并在 if/else-block 中传递一个res.send

function basicAuth(req, res, next) {
    
    if (!req.headers.authorization || req.headers.authorization.indexOf('Basic ') === -1) {
        return res.status(401).json({
            message: 'Missing Authorization Header'
        });
    }

    // verify auth credentials
    const base64Credentials = req.headers.authorization.split(' ')[1];
    const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
    const [username, password] = credentials.split(':');
    console.log("AuthenticationService " + username + " " + password);

    userService.findUserById(username, function(error, user) {

        user.comparePassword(password.toString(), function(err, isMatch) {
            if (err) {
                console.log("Fehler")
                throw err;
            }
            /*Passwort richtig*/
            if (isMatch) {

                res.send(user);

            }
            /*Passwort falsch*/
            if (!isMatch) {

                res.status(401).json({
                    message: 'Passwort und userID stimmen nicht überein.'
                });



            }
        });
    })
}

推荐阅读