src/data/question-groups/full-stack/content/api-security.md
Rather than overlapping each other, authorization and authentication reference two very distinct stages of security within your app.
On one side, we have authentication, in charge of verifying the user identity. You can use tokens (e.g., JWT, OAuth) or sessions for this.
Example: Validate a JWT sent in headers:
const token = req.headers['authorization'];
jwt.verify(token, secretKey, (err, decoded) => { ... });
Once authenticated, users need to be authorized to access the resources. For this to work, you’ll need to define roles and permissions for your users.
Middleware example:
app.use((req, res, next) => {
if (req.user.role !== 'admin') return res.status(403).send('Forbidden');
next();
});