I am trying to implement Auth0 on the backend of my ToDo list app but getting an “UnauthorizedError: No authorization token was found” error when trying to add a task.
Server.js:
const cors = require("cors");
const dotenv = require("dotenv");
const express = require("express");
const path = __dirname + '/app/views/';
const { tasksRouter } = require("./app/routes/task.routes");
const {checkJwt} = require("./app/middleware/check-jwt.middleware");
dotenv.config();
if (!(process.env.PORT && process.env.CLIENT_ORIGIN_URL)) {
throw new Error(
"Missing required environment variables. Check docs for more info."
);
}
const PORT = parseInt(process.env.PORT, 10);
const CLIENT_ORIGIN_URL = process.env.CLIENT_ORIGIN_URL;
const app = express();
app.use(express.json());
app.use(express.static(path));
app.use((req, res, next) => {
res.contentType("application/json; charset=utf-8");
next();
});
app.use(
cors({
origin: "*"
})
);
app.use(express.urlencoded({ extended: true })); /* bodyParser.urlencoded() is deprecated */
// simple route
app.get('/', function (req,res) {
res.sendFile(path + "index.html");
});
app.get('/profile', checkJwt, function(req, res) {
});
//require("./app/routes/task.routes.js")(app);
app.use('/api/tasks', tasksRouter);
// set port, listen for requests
//const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
Task router:
const express = require("express");
const { checkJwt } = require("../middleware/check-jwt.middleware");
const tasks = require("../controllers/task.controller.js");
const tasksRouter = express.Router();
// Create a new Task
tasksRouter.post("/", checkJwt, tasks.create);
// Retrieve all Tasks
tasksRouter.get("/", checkJwt, tasks.findAll);
// Retrieve all published Tasks
tasksRouter.get("/completed", checkJwt, tasks.findAllCompleted);
// Retrieve a single Task with id
tasksRouter.get("/:id", checkJwt, tasks.findOne);
// Update a Task with id
tasksRouter.put("/:id", checkJwt, tasks.update);
// Delete a Task with id
tasksRouter.delete("/:id", checkJwt, tasks.delete);
// Delete all Tasks
tasksRouter.delete("/", checkJwt, tasks.deleteAll);
module.exports = { tasksRouter };
CheckJwt Middleware:
const { expressjwt: expressJwt } = require('express-jwt');
const jwksRsa = require("jwks-rsa");
const dotenv = require("dotenv");
dotenv.config();
const checkJwt = expressJwt({
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,
}),
// Validate the audience and the issuer.
audience: process.env.AUTH0_AUDIENCE,
issuer: `https://${process.env.AUTH0_DOMAIN}/`,
algorithms: ["RS256"],
});
module.exports = {
checkJwt,
};
The page loads and operates as normal until I try to add a task at “/add”, when I get the unauthorized error. Any ideas?