AWS API Gateway / Lambda自定义授权者中的AuthorizerConfigurationException

时间:2020-03-04 21:38:27

标签: typescript amazon-web-services aws-lambda aws-api-gateway serverless-framework

我正在使用AWS Lambda上的无服务器框架构建REST服务。我创建了一个自定义授权方,该授权方被称为在我的lambda的所有调用之前。当我运行无服务器离线时,一切正常。部署时,AP网关出现错误。我已经启用了登录API网关的功能,但是没有任何内容写入日志中。

这是我的serverless.yml文件:

provider:
  name: aws
  runtime: nodejs12.x
  stage: ${opt:stage, "dev"}
  region: eu-west-1

functions:

  authorize:
    handler: src/handlers/authorization.authorize

  listAlerts:
    handler: src/handlers/alert-handler.listAlerts
    events:
      - http:
          path: /alerts
          method: GET
          authorizer: ${self:custom.authorization.authorize}

custom:
  stage: ${opt:stage, self:provider.stage}
  authorization:
    authorize:
      name: authorize
      type: TOKEN
      identitySource: method.request.header.Authorization
      identityValidationExpression: Bearer (.*)
plugins:
  - serverless-plugin-typescript
  - serverless-offline
package:
    include:
    - src/**.*

我的授权处理程序如下所示。该方法获取我的身份验证令牌并使用JOSE对其进行验证,然后为用户和某些角色返回principalId:

import jwksClient from "jwks-rsa";
import { JWT } from "jose";


export const authorize = async (event: CustomAuthorizerEvent): Promise<CustomAuthorizerResult> => {
    const prefix = "bearer ";
    if (!event.authorizationToken?.toLowerCase().startsWith(prefix)) {
        return Promise.reject("Unauthorized");
    }
    const token = event.authorizationToken?.substring(prefix.length);
    const signingKey = await getCachedSigningKey()
    const jwt = JWT.verify(token, signingKey);
    if ((typeof jwt) !== "object") {
        throw "Unauthorized";
    }
    const userId = jwt["sub"];
    const expires = Number(jwt["exp"]);
    const roles = jwt["assumed-roles"] as string[];
    if (Date.now() > expires * 1000 ) {
        throw "Unauthorized";
    }
    const principalId = userId;
    const policyDocument: PolicyDocument = {
        Version: "2012-10-17",
        Statement: [
            {
                Action: "execute-api:Invoke",
                Effect: "Allow",
                Resource: event.methodArn,
            }
        ]
    };

    return {
        principalId,
        policyDocument,
        context: {
            userId,
            roles
        }
    };
};

如果执行serverless offline start,则在端口3000上启动模拟的API网关。我称该API:

❯ http :3000/alerts/5480e8a1-e3d4-432d-985e-9542c91a49ce Authorization:"Bearer eyJraWQiO.......LHA12jM2UEXFy76dhKUj_iX6SXQQ"
HTTP/1.1 200 OK
Connection: keep-alive
Date: Wed, 04 Mar 2020 21:29:07 GMT
accept-ranges: bytes
access-control-allow-origin: *
cache-control: no-cache
content-length: 174
content-type: application/json; charset=utf-8

{
    "id": "5480e8a1-e3d4-432d-985e-9542c91a49ce",
    "message": "test",
    "subjects": [
        {
            "id": "6ee2c07d-6486-4601-9b4b-05f61c0d0caf",
            "referenceId": "5480e8a1-e3d4-432d-985e-9542c91a49ce"
        }
    ]
}

因此,它在本地工作,并且我的处理程序记录了userId和角色。然后,我使用serverless deplpy部署到AWS,没有任何警告。我尝试调用我的API网关端点:

❯ http https://og8...<bla-bla>..kcc.execute-api.eu-west-1.amazonaws.com/dev/alerts/alerts/ Authorization:"Bearer eyJraWQiOiJkZXYiL.....VOPI2LHA12jM2UEXFy76dhKUj_iX6SXQQ"
HTTP/1.1 500 Internal Server Error
Connection: keep-alive
Content-Length: 16
Content-Type: application/json
Date: Wed, 04 Mar 2020 21:32:22 GMT
Via: 1.1 e31ab4c27d99cec62ef37e2607db9b45.cloudfront.net (CloudFront)
X-Amz-Cf-Id: kfIhCZHCGoL3OcjPSX4QWdtK1Qequ2vJe9RNst4wBEf_d90fJLjWgQ==
X-Amz-Cf-Pop: ARN1-C1
X-Cache: Error from cloudfront
x-amz-apigw-id: I4mu_HOFjoEF6SQ=
x-amzn-ErrorType: AuthorizerConfigurationException
x-amzn-RequestId: 3cb89b9a-26db-4890-8edb-6aedcc51c09e

{
    "message": null
}

发票不会立即返回,但是会超时。发生了什么事?

2 个答案:

答案 0 :(得分:0)

  1. 您的配置中没有这样的路由/ alerts / 5480e8a1-e3d4-432d-985e-9542c91a49c
  2. 请打开API GW控制台并使用Test调试问题 enter image description here

答案 1 :(得分:0)

好,回答我自己的问题,上面有多个问题:

  • 无法调用异步函数。 const signingKey = await getCachedSigningKey()将失败(这可能是因为缺乏在VPC外部执行HTTP的权限)。
  • 上下文只能包含简单的映射。我试图在此处设置一个数组(x),但这是不允许的。仅限简单值。

如果最终的解决方案可以帮助任何人,则如下所示:

import { CustomAuthorizerEvent, CustomAuthorizerResult, PolicyDocument } from "aws-lambda";
import { JWT } from "jose";

export enum Role {
    User = "ROLE_USER",
    Admin = "ROLE_ADMIN",
}

export const getAuthorizerForRoles = (requiredRoles: Role[]) => async (event: CustomAuthorizerEvent): Promise<CustomAuthorizerResult> => {
    try {
        const prefix = "bearer ";
        if (!event.authorizationToken?.toLowerCase().startsWith(prefix)) {
            throw new Error(`Token does not start with ${prefix.trim()}`);
        }
        const token = event.authorizationToken?.substring(prefix.length);
            const signingKey = process.env.AUTH_SIGNING_KEY;
        const issuer = process.env.AUTH_ISSUER;
        if (!signingKey || !issuer) {
            throw new Error(`Auth properties not configure correct`);
        }
        const jwt = JWT.verify(token, signingKey, {
            issuer,
        });
        if ((typeof jwt) !== "object") {
            throw new Error(`The JWT has a unexpected structure`);
        }
        const userId = jwt["sub"];
        const expiresEpochMilliSec = Number(jwt["exp"]) * 1000;
        const expires = new Date(expiresEpochMilliSec);
        const assumedRoles = jwt["assumed-roles"] as string[];
        requiredRoles.forEach((requiredRole) => {
            if (!assumedRoles.includes(requiredRole)) {
                throw new Error(`The token does not contain the required role ${requiredRole}`);
            }
        });
        if (Date.now() > expires.valueOf()) {
            throw new Error(`The expired at ${expires}`);
        }
        const principalId = userId;
        const policyDocument: PolicyDocument = {
            Version: "2012-10-17",
            Statement: [
                {
                    Action: "execute-api:Invoke",
                    Effect: "Allow",
                    Resource: event.methodArn,
                }
            ]
        };

        const authResponse: CustomAuthorizerResult = {
            principalId,
            policyDocument,
            context: {
                userId,
                roles: assumedRoles.join(","),
            }
        };
        return authResponse;
    } catch (error) {
        console.log(error);
        throw "Unauthorized";
    }
};

export const authorizeUser = getAuthorizerForRoles([Role.User]);

export const authorizeAdmin = getAuthorizerForRoles([Role.Admin]);

与往常一样,来自AWS的文档和日志消息几乎没有。