Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serverless authorizer async await not working

I've been working with Node 6 with my Serverless application, and I decided to migrate to async/await, since version 8.x was released.

Altough, I'm having an issue with the authorizer function. Since I removed the callback parameter and just returning the value, it stopped to work. If I send something to the callback parameter, it keeps working fine, but it's not async/await-like. It's not working even if I throw an exception.

module.exports.handler = async (event, context) => {

    if (typeof event.authorizationToken === 'undefined') {
        throw new InternalServerError('Unauthorized');
    }

    const decodedToken = getDecodedToken(event.authorizationToken);
    const isTokenValid = await validateToken(decodedToken);

    if (!isTokenValid) {
        throw new InternalServerError('Unauthorized');
    } else {
        return generatePolicy(decodedToken);
    }
};

Any suggestions of how to proceed?

Thank y'all!

like image 581
Kiwanax Avatar asked Nov 01 '25 04:11

Kiwanax


1 Answers

I faced the same problem here. It seems authorizers dont support async/await yet. One solution would be get your entire async/await function and call inside the handler. Something like this:

const auth = async event => {
    if (typeof event.authorizationToken === 'undefined') {
        throw new InternalServerError('Unauthorized');
    }

    const decodedToken = getDecodedToken(event.authorizationToken);
    const isTokenValid = await validateToken(decodedToken);

    if (!isTokenValid) {
        throw new InternalServerError('Unauthorized');
    } else {
        return generatePolicy(decodedToken);
    }
}
module.exports.handler = (event, context, cb) => {
    auth(event)
      .then(result => {
         cb(null, result);
      })
      .catch(err => {
         cb(err);
      })
};
like image 103
Tulio Faria Avatar answered Nov 03 '25 22:11

Tulio Faria



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!