Implement JWT authentication and protect routes.
Security is a first-class citizen in CanxJS. Let's implement JWT authentication.
First, ensure your auth middleware is set up to verify tokens:
import { Middleware } from "canxjs";
export const AuthMiddleware: Middleware = async (req, res, next) => {
const token = req.header("Authorization");
if (!isValid(token)) {
return res.status(401).json({ error: "Unauthorized" });
}
return next();
};Apply the middleware to routes you want to protect:
app.group("/dashboard", (router) => {
router.middleware(AuthMiddleware);
router.get("/", (req, res) => res.json({ data: "Secret Data" }));
});Always hash passwords before storing them. CanxJS provides a Hash facade:
import { Hash } from "canxjs";
const hashedPassword = await Hash.make("my-secret-password");
if (await Hash.check("input-password", hashedPassword)) {
// Passwords match!
}Have questions?
Join the discussion on GitHub