Basic Authentication Nodejs

2
I'm starting now with NodeJS (I came from PHP), and I'm creating an API for a my app, I would like to know, how do I make queries based on Auth Basic, I'm not really sure how it works an app for a client, which I always needed to send in the header Basic VGVzdDoxMjM= , I'm not sure if it was for all the queries, or just for the login, but I would also like to restrict the query to my API. person to have the url of my API to be able to execute a query .

I'm using Mysql for the bank, follow the example of one queried.

   router.get("/menu", function(req, res){
        let query = "SELECT * FROM ??";
        let table = ["menu"];
        query = mysql.format(query, table);
        connection.query(query, function(err, rows){
            if(err){
                res.json({"Error": true, "Message": "Erro ao executar query do Mysql"});
            }else{
                res.json({"Error": false, "Message": "Sucesso", "Cardapio": rows});
            }
        })
    })
    
asked by anonymous 29.08.2017 / 00:01

1 answer

2

If you want this authentication to occur before any query, you must create a route that is compatible (through regular expression, for example) with the request uri and place it at the beginning of your route file. After that, you run your authentication and call next() so that the request follows its normal life cycle. Or it passes an error as a parameter within this function so that it is handled by the error middleware.

router.use('*', function(req, res, next) {
    var authKey = req.headers['Authorization'];

    // Executa sua validação
    ...

    // Se tudo ok, segue para a sua rota normalmente
    next();

    // Senão, você pode criar um erro e passar
    // como parâmetro para ser devidamente tratado
    var err = new Error('Not Authorized');
    err.status = 401;
    next(err);
});

router.get("/menu", function(req, res){
    let query = "SELECT * FROM ??";
    let table = ["menu"];
    query = mysql.format(query, table);
    connection.query(query, function(err, rows){
        if(err){
            res.json({"Error": true, "Message": "Erro ao executar query do Mysql"});
        }else{
            res.json({"Error": false, "Message": "Sucesso", "Cardapio": rows});
        }
    })
})
    
29.08.2017 / 00:36