使用无服务器,如何从资源中将Lambda函数的授权程序设置为Cognito用户池?

时间:2018-05-03 01:59:56

标签: amazon-web-services aws-lambda yaml serverless-framework serverless

在我的serverless.yml中,我有一个Lambda函数,我想将它的授权者设置为我在下面的参考资料部分声明的Cognito用户池。我已经看过将授权程序设置为aws_iam的示例,但这似乎不对。任何帮助都会很棒:)

我认为我需要将授权人的ARN设置为Pool的ARN,但我该怎么做?或者这是否正确?

2 个答案:

答案 0 :(得分:2)

如另一个答案所述,对ARN进行硬编码是有效的。如此直观地说,您可能会认为这样的事情会起作用:

arn

可悲的是,事实并非如此。看起来无服务器会使您的Ref与几个正则表达式相冲突,以确定您是否指向lambda或用户池。这种方法似乎与使用Fn::JoinFn::GetAttresources

之类的方法很好地配合

截至Serverless 1.27.3(自提出此问题以来已发布),有a workaround of sorts可用。

基本上,您在authorizerId部分声明了授权人,而不是让无服务器自动为您创建它。然后,您使用functions部分中的新service: sls-cognitotest provider: name: aws runtime: nodejs6.10 functions: hello: handler: handler.hello events: - http: method: any path: /api/{proxy+} integration: lambda authorizer: type: COGNITO_USER_POOLS authorizerId: { Ref: MyApiGatewayAuthorizer } resources: Resources: CognitoUserPoolGeneral: Type: AWS::Cognito::UserPool Properties: UserPoolName: general MyApiGatewayAuthorizer: Type: AWS::ApiGateway::Authorizer Properties: AuthorizerResultTtlInSeconds: 10 IdentitySource: method.request.header.Authorization Name: MyCognitoAuthorizer RestApiId: Ref: ApiGatewayRestApi Type: COGNITO_USER_POOLS ProviderARNs: - {"Fn::Join": ["", ["arn:aws:cognito-idp:", {Ref: "AWS::Region"}, ":", {Ref: "AWS::AccountId"}, ":userpool/", Ref: CognitoUserPoolGeneral]]} 键指向此授权人。一个最小的例子:

{{1}}

这不是很好,但它比将用户池ARN硬编码到模板中更好。

答案 1 :(得分:1)

这是你在找什么? https://serverless.com/framework/docs/providers/aws/events/apigateway#http-endpoints-with-custom-authorizers

示例:

>>> $html = '
    <tr><td>AD - Andorra<td>CA - Canada
    <tr><td>AE - United Arab Emirates<td>PR - Puerto Rico
    <tr><td>AF - Afghanistan<td>US - United States of America
    <tr><td>AG - Antigua and Barbuda<td>
';
preg_match_all('/<td>(?:.*?)<td>(.*?)\n/s', $html, $value);
print_r($value);
... ... ... ... ... => """
   \n
   <tr><td>AD - Andorra<td>CA - Canada\n
   <tr><td>AE - United Arab Emirates<td>PR - Puerto Rico\n
   <tr><td>AF - Afghanistan<td>US - United States of America\n
   <tr><td>AG - Antigua and Barbuda<td>\n
"""
>>> => 4
>>> Array
(
    [0] => Array
        (
            [0] => <td>AD - Andorra<td>CA - Canada
            [1] => <td>AE - United Arab Emirates<td>PR - Puerto Rico    
            [2] => <td>AF - Afghanistan<td>US - United States of America
            [3] => <td>AG - Antigua and Barbuda<td> 
        )
    [1] => Array
        (
            [0] => CA - Canada
            [1] => PR - Puerto Rico
            [2] => US - United States of America
            [3] => 
        ) 
)
=> true