Home > Blockchain >  How to create a NodeJS Authorization middleware on a serverless framework?
How to create a NodeJS Authorization middleware on a serverless framework?

Time:06-02

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.

CodePudding user response:

Well, I don't have an actuall example for the serverless framework, but i can tell what you should do.

  1. Create an Lambda Function to act as a Amazon API Gateway Lambda authorizer - you can see the documentation here - https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-output.html
  2. make sure you do the validation logic what you have defined, and also return the context object in the response - which you can define your user data
  3. add the Amazon API Gateway Lambda authorizer to the API Gateway - https://docs.aws.amazon.com/apigateway/latest/developerguide/configure-api-gateway-lambda-authorization-with-console.html
  4. If the authorization successful your rest api lambda can access the context object with the user data, which you customize in step 2
  • Related