Basic Nodejs Authentication

Asked

Viewed 218 times

2

I’m starting now with Nodejs (I came from PHP), and I’m creating an API for an app of mine, I wonder, how do I make the queries based on Auth Basic, I don’t know very well how it works (I’ve already developed an app for a client, who always needed to send in the header Basic VGVzdDoxMjM=, I’m not sure if it was for all queries, or just for login, but I would also like to restrict the query to my API. If not, just have the url of my API to be able to run a query.

I am using Mysql for the database, follow the example of a query.

   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});
            }
        })
    })

1 answer

3


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() for the request to follow its normal life cycle. Or you pass an error as a parameter within that function so that it is handled by the error middlewars.

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});
        }
    })
})
  • Cool, got it, but how would it work to use Basic? like, can I just go via headers and etc? I don’t need anything else?

  • Yes, if it’s Basic it’s just that. It’s standard here if you want to check it out (https://tools.ietf.org/html/rfc7617)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.