For security of access to your API, one of the most common alternatives is to use token. The token would be a code generated by your application in the login process. This code should be returned in the header of all requests (Bearer Token). Before executing a route, it would be checked using a "middleware", which is a chunk of code executed before meeting the request. If it exists, or if it exists but its contents are not valid, then the route is not executed.
Through the token, you can validate if that user is allowed to access the route
Here’s an example of route and token validation with JWT
Route archive:
const express = require("express");
const validate = require("express-validation");
const handle = require("express-async-handler");
const routes = express.Router();
const authMiddleware = require("./app/middlewares/auth");
const UsuarioController = require("./app/controllers/UsuarioController");
const FerramentasController = require("./app/controllers/FerramentasController");
routes.post("/login", validate(validatorLogin), handle(UsuarioController.login));
routes.post(
"/usuario",
handle(UsuarioController.cadastrar)
);
routes.get("/ferramentas", handle(FerramentasController.listar));
routes.get("/ferramentas/:id", handle(FerramentasController.detalhe));
//As rotas a partir daqui exigem autenticação
routes.use(authMiddleware);
routes.post(
"/ferramentas",
handle(FerramentasController.cadastrar)
);
routes.delete("/ferramentas/:id", handle(FerramentasController.remover));
module.exports = routes;
Here is an example of how the "authMiddleware" would be responsible for validating the token before executing the route:
const jwt = require("jsonwebtoken");
const authConfig = require("../../config/auth");
const { promisify } = require("util");
module.exports = async (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader) {
res.status("401").json({ error: "Token não informado" });
}
const [, token] = authHeader.split(" "); // Quebra o header num array e pega o segundo elemento (token sem o Bearer)
try {
//Transforma uma funcao que usa callbacks numa promisse
const decoded = await promisify(jwt.verify)(token, authConfig.secret);
req.userID = decoded.id; // Adiciona em todas as requisicoes que utilizaram este middleware o ID do usuário
return next(); // Middleware tem sempre req, res e next
} catch (error) {
res.status("401").json({ error: "Token inválido" });
}
};
Within the route, you will be able to validate req.userid recovered by middleware, and validate whether the user is allowed to use that route.
Regarding blocking Web or Mobile access, you might think about creating a custom header (header). So in addition to the token being valid, the header should also have a certain information for the route to run.
Here’s a tutorial on how to implement a JWT token
https://www.luiztools.com.br/post/autenticacao-json-web-token-jwt-em-nodejs/
Many thanks I will read very carefully and try to apply!
– Joao Spirit