简体   繁体   中英

Disable authentication middleware for specific verb on specific route

I am using Express/Node and have written some authentication middleware to check JWT on every request.

I would like to disable this middleware for the route (POST '/api/user/')however I want to keep the middleware for the route (GET '/api/user/').

How can I achieve this?

Please see code below.

app.js

// app.js


app.use('/api/userauth', require('./Controllers/api/userauth.js'))
app.use(require('./Middleware/Authenticate.js'));
app.use('/api/user', require('./Controllers/Api/User.js'));
app.use('/api/item', require('./Controllers/Api/Item.js'));

authenticate.js

//authenticate.js middleware


    var token = req.body.token || req.query.token || req.headers['x-access-token'];


    if (token) {
        jwt.verify(token, secretKey.secretKey, function(err, decoded){
            if (err) {
                return res.json({
                    success : false,
                    message : "failed to auth token."
                })
            } else {
                console.log(decoded);
                req.decoded = decoded;
                next();
            }
        })
    } else {
        res.status(403).send({
            success:false,
            message:'no token provided'
        })
    }
}

api/user.js

router.route('/')

.get(function(req,res){
    models.User.findAll({
    }).then(function(users){
        res.json(users);
    })
})

.post(function(req,res){
    models.User.create({
        username : req.body.username,
        password : req.body.password,
        firstname : req.body.firstname,
        lastname : req.body.lastname
    }).then(function(user){
        res.json({
            "Message" : "Succesfully created user: ",
            "User: " : user
        });
    });
});
module.exports = router;

Old issue but here you go!

Instead of using a blank

app.use(require('./Middleware/Authenticate.js'));

for all routes just do this in your sub routers

api/user.js

var authMiddleware = require('./Middleware/Authenticate.js')
router.route('/')

.get(function(req,res){
    models.User.findAll({
    }).then(function(users){
        res.json(users);
    })
})

.post(authMiddleware, function(req,res){
    models.User.create({
        username : req.body.username,
        password : req.body.password,
        firstname : req.body.firstname,
        lastname : req.body.lastname
    }).then(function(user){
        res.json({
            "Message" : "Succesfully created user: ",
            "User: " : user
        });
    });
});
module.exports = router;

Now it's just that route that has the Authenticate Middleware not the get one!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM