本文介绍了具有自定义授权者和CORS间歇性的AWS API Gateway 200然后是403然后是200 ...奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一个带有自定义授权者的1 Amazon Api Gateway设置(授权者基本上只是返回允许的任何内容)

I have an 1 Amazon Api Gateway setup with a custom authorizer (the authorizer basically just returns allow for anything)

我启用了CORS,并且正在 jQuery 网页上运行.

I enabled CORS, and this is running from jQuery webpage.

我有两种方法

  1. /车辆(返回汽车清单)
  2. /预订(返回预订详细信息)

我看到的行为是第一个请求正常,我看到它拉了 OPTIONS ,然后执行 GET 请求.然后,我按了 OPTIONS 的另一种方法,然后get返回了 403 ,但是如果我再次启动请求(在同一资源上),我得到了 200

The behavior I am seeing, is the first request goes fine, I see it pull the OPTIONS, then perform a GET request. Then, I hit the other method the OPTIONS works, then the get returns a 403, but if I launch the request again (On the same resource), I get a 200

我正在使用Cloudformation,但是当我使用无服务器框架时,我注意到了相同的行为.

I'm using Cloudformation, but I noticed the same behaviour when I was using the Serverless Framework.

下面是我的理智的一些屏幕截图,希望其他人已经看到了这种陌生感.

Below are some screen shots for my sanity and hopefully someone else has seen this strangeness.

下面是我的Cloudformation YAML模板的一部分,我正在学习中.

Below is a portion of my Cloudformation YAML template, I'm learning this as I do it.

 HelloAPI:
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Sub ${Environment}
      DefinitionBody:
        swagger: 2.0
        info:
          title:
            Ref: AWS::StackName
        securityDefinitions:
          test-authorizer:
            type: apiKey
            name: Authorization
            in: header
            x-amazon-apigateway-authtype: custom
            x-amazon-apigateway-authorizer:
              type: token
              authorizerUri:
                Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${AuthorizerFunc.Arn}/invocations
              authorizerResultTtlInSeconds: 5
        paths:
          /vehicles:
            get:
              x-amazon-apigateway-integration:
                httpMethod: POST
                type: aws_proxy
                uri:
                  !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${VehiclesLambda.Arn}/invocations
              responses: {}
              security:
                - test-authorizer: []
            options:
              tags:
              - "CORS"
              summary: "CORS support"
              description: "Enable CORS by returning correct headers\n"
              consumes:
              - "application/json"
              produces:
              - "application/json"
              parameters: []
              responses:
                "200":
                  description: "Default response for CORS method"
                  headers:
                    Access-Control-Allow-Headers:
                      type: "string"
                    Access-Control-Allow-Methods:
                      type: "string"
                    Access-Control-Allow-Origin:
                      type: "string"
              x-amazon-apigateway-integration:
                type: "mock"
                requestTemplates:
                  application/json: "{\n  \"statusCode\" : 200\n}\n"
                responses:
                  default:
                    statusCode: "200"
                    responseParameters:
                      method.response.header.Access-Control-Allow-Headers: "'X-Amz-Date,Authorization,X-Api-Key'"
                      method.response.header.Access-Control-Allow-Methods: "'*'"
                      method.response.header.Access-Control-Allow-Origin: "'*'"
                    responseTemplates:
                      application/json: "{}\n"
          /bookings:
            get:
              x-amazon-apigateway-integration:
                httpMethod: POST
                type: aws_proxy
                uri:
                  !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${BookingsLambda.Arn}/invocations
              responses: {}
              security:
                - test-authorizer: []
            options:
              tags:
              - "CORS"
              summary: "CORS support"
              description: "Enable CORS by returning correct headers\n"
              consumes:
              - "application/json"
              produces:
              - "application/json"
              parameters: []
              responses:
                "200":
                  description: "Default response for CORS method"
                  headers:
                    Access-Control-Allow-Headers:
                      type: "string"
                    Access-Control-Allow-Methods:
                      type: "string"
                    Access-Control-Allow-Origin:
                      type: "string"
              x-amazon-apigateway-integration:
                type: "mock"
                requestTemplates:
                  application/json: "{\n  \"statusCode\" : 200\n}\n"
                responses:
                  default:
                    statusCode: "200"
                    responseParameters:
                      method.response.header.Access-Control-Allow-Headers: "'X-Amz-Date,Authorization,X-Api-Key'"
                      method.response.header.Access-Control-Allow-Methods: "'*'"
                      method.response.header.Access-Control-Allow-Origin: "'*'"
                    responseTemplates:
                      application/json: "{}\n"

这是我的一切授权人:

'use strict';

const generatePolicy = function(principalId, effect, resource) {
    const authResponse = {};
    authResponse.principalId = principalId;
    if (effect && resource) {
        const policyDocument = {};
        policyDocument.Version = '2012-10-17';
        policyDocument.Statement = [];
        const statementOne = {};
        statementOne.Action = 'execute-api:Invoke';
        statementOne.Effect = effect;
        statementOne.Resource = resource;
        policyDocument.Statement[0] = statementOne;
        authResponse.policyDocument = policyDocument;
    }
    return authResponse;
};

exports.handler = (event, context, callback) => {

    console.log("Hit Authorizer")
    console.log(event)


    callback(null, generatePolicy('user123', 'Allow', event.methodArn));

};

还有其他人看到过这个,或者知道如何调试它吗?

Anyone else seen this, or know how to debug it ?

我把它放在一个测试站点上,只是有人希望看到我所看到的.

I put this on a test site, just it some one wants to see what I am seeing.

https://s3.amazonaws.com/stackoverflowisgreat2/index.html

推荐答案

在自定义授权者代码的

statementOne.Resource = resource;

将您的资源更改为以下格式:"arn:aws:execute-api:us-west-2:123456789012:ymy8tbxw7b/*/GET/".

change your resources to this format "arn:aws:execute-api:us-west-2:123456789012:ymy8tbxw7b/*/GET/".

在您的情况下,允许所有这些操作:

In your case to allow all that would be:

statementOne.Resource = arn:aws:execute-api:us-west-2:123456789012:ymy8tbxw7b/*/*/

这是AWS了解您的授权者的方式.因为在自定义授权器中,您可以从请求标头中获取用户,组等信息,然后根据您的授权数据库验证信息,并确定允许谁或什么来继续请求类型POST/GET/OPTION,但API网关不会在您以AWS格式提供有效答案之前,不知道您的决定

This is how AWS understands your authorizer. Because in custom authorizer you can get information from the request header like user, group, etc and then validate the info against your authorization database and decide who or what is allowed to continue the request type POST/GET/OPTION, but API gateway won't know your decision until you provide it with a valid answer in AWS format

{
  "principalId": "yyyyyyyy", // The principal user identification associated with the token sent by the client.
  "policyDocument": {
    "Version": "2012-10-17",
    "Statement": [
      {
        "Action": "execute-api:Invoke",
        "Effect": "Allow|Deny",
        "Resource": "arn:aws:execute-api:{regionId}:{accountId}:{appId}/{stage}/{httpVerb}/[{resource}/[child-resources]]"
      }
    ]
  },
  "context": {
    "stringKey": "value",
    "numberKey": "1",
    "booleanKey": "true"
  },
  "usageIdentifierKey": "{api-key}"  # Optional
}

您可以访问此页面以了解更多信息:

You can visit this page to understand more about it:

https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-output.html

这篇关于具有自定义授权者和CORS间歇性的AWS API Gateway 200然后是403然后是200 ...奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 23:23