Reputation: 175
I'd like to create a middleware that checks the authorization header, decodes the token and sends the decoded data to the actual function, just like you would by adding userData to the request and using next() on an Express server, so the actual function gets back the decoded data on the req and it can then check what content to display to the user (if any).
I'm using Lambda functions on a serverless framework.
This was the function on my Express NodeJS local server:
const authorizerFunc = async (req, res, next) => {
let token;
try {
if (
req.headers.authorization &&
req.headers.authorization.split(" ")[0] === "Bearer"
) {
token = req.headers.authorization.split(" ")[1];
}
if (!token) {
req.userData = { userId: "", username: "" };
next();
return;
}
const decodedToken = jwt.verify(token, process.env.JWT_SECRET_KEY);
console.log("DECODED TOKEN", decodedToken);
req.userData = {
userId: decodedToken.userId,
username: decodedToken.username,
email: decodedToken.email,
};
next();
} catch (err) {
req.userData = { userId: "", username: "" };
next();
return;
}
};
The question is, how do I create a Lambda function that does this and sends the decoded data to the real function?
Edit: is it bad if I decode the auth token directly in the functions at the very beginning? I don't think it would add huge complexity to them.
Upvotes: 0
Views: 1220
Reputation: 503
Well, I don't have an actuall example for the serverless framework, but i can tell what you should do.
Upvotes: 1