【问题标题】:Serverless Custom Authorizer results to undefined无服务器自定义授权器结果未定义
【发布时间】:2020-05-28 16:56:45
【问题描述】:

我按照在线教程和示例了解如何为我的 lambda 函数实现自定义授权器。不幸的是,我在访问我的函数中的授权者上下文时遇到了麻烦。执行console.log(event.requestContext.authorizer); 只会导致undefined。我错过了什么吗?这是一些sn-p。

# serverless.yml

...
myAuthorizer:
  handler: src/functions/myAuthorizer/index.handler

someFunction:
  handler: src/functions/someFunction/index.handler
  events:
    - http:
        method: GET
        path: /hello-world
        authorizer:
          name: myAuthorizer
          identitySource: method.request.header.Authorization
// myAuthorizer.ts

export async function handler(
  event: AWSLambda.CustomAuthorizerEvent,
  context: AWSLambda.Context
): Promise<AWSLambda.AuthResponse> {

  const user = {id: 1, email: 'user@test.com'};

  // some logic...

  return {
    principalId: user.id,
    policyDocument: {
      Version: '2012-10-17',
      Statement: [
        {
          Action: '*',
          Effect: 'Allow',
          Resource: '*',
        },
      ],
    },
    context: { user },
  };
}

// someFunction.ts

export async function handler(
  event: AWSLambda.APIGatewayEvent,
  context: AWSLambda.Context
): Promise<AWSLambda.APIGatewayProxyResult> {

  console.log(event.requestContext.authorizer); // <-- this is undefined
  console.log(Object.keys(event.requestContext)); // <-- no "authorizer" property
  return {
    statusCode: 200,
    body: JSON.stringify({hello: 'world'}),
  };
}

提前致谢!

【问题讨论】:

    标签: javascript aws-lambda serverless-framework aws-serverless


    【解决方案1】:

    myAuthorizer 处理函数中,使用callback 样式而不是async/await 样式。

    export async function handler(
      event: AWSLambda.CustomAuthorizerEvent,
      context: AWSLambda.Context
    ): Promise<void> { // change to void
    
      const user = { id: 1, email: 'user@test.com' };
    
      // some logic...
    
      context.succeed({ // instead of return policy object
        principalId: user.id,
        policyDocument: {
          Version: '2012-10-17',
          Statement: [
            {
              Action: '*',
              Effect: 'Allow',
              Resource: '*',
            },
          ],
        },
        context: { user },
      });
    }
    

    【讨论】:

    • 但是你知道为什么回调起作用而不是async/await吗?在任何情况下,他们都应该在文档的某处明确提及这一点。 :(
    • 对不起,我不知道 :( ,我遇到了同样的问题,我就是这样做的。也许 async/awaitLambda 环境下可以正常工作,但不适用于本地env, callback stype 为两个 envs 工作。
    • 是的。不过,他们欠我们一个解释。 :) 再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 2013-03-17
    • 2015-01-23
    • 2021-03-13
    • 2022-07-30
    相关资源
    最近更新 更多