├── LICENSE ├── NOTICE.txt ├── README.md └── blueprints ├── dotnet └── src │ ├── APIGatewayAuthorizerHandler.Tests │ ├── APIGatewayAuthorizerHandler.Tests.csproj │ └── IntegrationTests.cs │ ├── APIGatewayAuthorizerHandler.sln │ └── APIGatewayAuthorizerHandler │ ├── APIGatewayAuthorizerHandler.csproj │ ├── AuthPolicyBuilder.cs │ ├── Error │ └── UnauthorizedException.cs │ ├── Function.cs │ └── Model │ ├── ApiGatewayArn.cs │ ├── ApiOptions.cs │ ├── Auth │ ├── AuthPolicy.cs │ ├── Condition.cs │ ├── ConditionKey.cs │ ├── ConditionOperator.cs │ ├── Effect.cs │ ├── PolicyDocument.cs │ └── Statement.cs │ ├── HttpVerb.cs │ └── TokenAuthorizerContext.cs ├── go └── main.go ├── java └── src │ ├── example │ └── APIGatewayAuthorizerHandler.java │ └── io │ ├── AuthPolicy.java │ └── TokenAuthorizerContext.java ├── nodejs └── index.js ├── python └── api-gateway-authorizer-python.py └── rust └── main.rs /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /NOTICE.txt: -------------------------------------------------------------------------------- 1 | Amazon API Gateway - Custom Authorizer Blueprints for AWS Lambda 2 | Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Amazon API Gateway - Custom Authorizer Blueprints for AWS Lambda 2 | We've added blueprints and examples in 3 languages for Lambda-based custom Authorizers for use in API Gateway. 3 | 4 | ## Java 5 | Not available in the Lambda console. Use the AuthPolicy object to generate and serialize IAM policies for your custom authorizer. See javadoc comments for more details. 6 | 7 | ## NodeJS 8 | Also available in the Lambda console, the NodeJS blueprint makes it easy to generate IAM policies, including Conditions. 9 | 10 | ## Python 11 | Also available in the Lambda console, the Python blueprint includes the AuthPolicy class, which makes generating IAM policies simple and easy to understand. 12 | 13 | ## Go 14 | Not available in the Lambda console. Use the AuthorizerResponse object to generate IAM policies for your custom authorizer. See comments for more details. 15 | 16 | ## Rust 17 | Not available in the Lambda console. Using `awslabs/aws-lambda-rust-runtime`. Use the APIGatewayPolicyBuilder object to generate IAM policies for your custom authorizer. See comments for more details. 18 | 19 | ## Docs ## 20 | For more details, see public documentation for: 21 | - API Gateway Custom Authorizers -- [Blog Post](https://aws.amazon.com/blogs/compute/introducing-custom-authorizers-in-amazon-api-gateway/) -- [Developer Guide](http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html) 22 | - IAM Policy Language -- [API Gateway Developer Guide](http://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html) -- [Policy Language Reference](http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies.html) -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler.Tests/APIGatewayAuthorizerHandler.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp1.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler.Tests/IntegrationTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using Amazon.Lambda.TestUtilities; 3 | using APIGatewayAuthorizerHandler.Model; 4 | using Newtonsoft.Json; 5 | using Xunit; 6 | 7 | namespace APIGatewayAuthorizerHandler.Tests 8 | { 9 | public class IntegrationTests 10 | { 11 | [Fact] 12 | public void CallingFunctionWithAnyTokenReturnDenyAllPolicy() 13 | { 14 | var function = new Function(); 15 | var request = SampleRequest(); 16 | var lambdaContext = new TestLambdaContext(); 17 | var result = function.FunctionHandler(request, lambdaContext); 18 | 19 | Assert.Equal(result.PrincipalId, "user|a1b2c3d4"); 20 | var firstStatement = result.PolicyDocument.Statement.First(); 21 | Assert.Equal("Deny", firstStatement.Effect); 22 | Assert.Equal("arn:aws:execute-api:ap-southeast-2:123123123123:123sdfasdf12/prod/*/*", firstStatement.Resource); 23 | } 24 | 25 | private static TokenAuthorizerContext SampleRequest(string type = "TOKEN", 26 | string token = "Allow", 27 | string region = "ap-southeast-2", 28 | string accoundId = "123123123123", 29 | string restApiId = "123sdfasdf12", 30 | string stage = "prod", 31 | string verb = "GET") 32 | { 33 | string json = $@"{{ ""Type"": ""{type}"", ""AuthorizationToken"": ""{token}"", ""MethodArn"": ""arn:aws:execute-api:{region}:{accoundId}:{restApiId}/{stage}/{verb}/"" }}"; 34 | return JsonConvert.DeserializeObject(json); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26430.14 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "APIGatewayAuthorizerHandler", "APIGatewayAuthorizerHandler\APIGatewayAuthorizerHandler.csproj", "{7DCDDA7A-75BA-4B90-92D0-EE6232D7CF60}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "APIGatewayAuthorizerHandler.Tests", "APIGatewayAuthorizerHandler.Tests\APIGatewayAuthorizerHandler.Tests.csproj", "{D6521E85-858B-4831-82AB-57DC0A75BE98}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {7DCDDA7A-75BA-4B90-92D0-EE6232D7CF60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {7DCDDA7A-75BA-4B90-92D0-EE6232D7CF60}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {7DCDDA7A-75BA-4B90-92D0-EE6232D7CF60}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {7DCDDA7A-75BA-4B90-92D0-EE6232D7CF60}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {D6521E85-858B-4831-82AB-57DC0A75BE98}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {D6521E85-858B-4831-82AB-57DC0A75BE98}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {D6521E85-858B-4831-82AB-57DC0A75BE98}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {D6521E85-858B-4831-82AB-57DC0A75BE98}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler/APIGatewayAuthorizerHandler.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp1.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler/AuthPolicyBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text.RegularExpressions; 5 | using APIGatewayAuthorizerHandler.Model; 6 | using APIGatewayAuthorizerHandler.Model.Auth; 7 | 8 | namespace APIGatewayAuthorizerHandler 9 | { 10 | /// 11 | /// Receives a set of allowed and denied methods and generates a valid AWS policy for the API Gateway authorizer. 12 | /// 13 | public class AuthPolicyBuilder 14 | { 15 | /// 16 | /// The policy version used for the evaluation. This should always be "2012-10-17" 17 | /// 18 | private const string PolicyVersion = "2012-10-17"; 19 | 20 | /// 21 | /// The regular expression used to validate resource paths for the policy 22 | /// 23 | private readonly Regex _pathRegex = new Regex("^[/.a-zA-Z0-9-\\*]+$"); 24 | 25 | // these are the values exctracted from the API Options passed into the construction 26 | // these options default to a "*" if the input option was empty 27 | private readonly string _restApiId; 28 | private readonly string _region; 29 | private readonly string _stage; 30 | 31 | /// 32 | /// The AWS account id the policy will be generated for. This is used to create the method ARNs. 33 | /// 34 | public string AwsAccountId { get; } 35 | 36 | /// 37 | /// The principal used for the policy, this should be a unique identifier for the end user. 38 | /// 39 | public string PrincipalId { get; } 40 | 41 | // these are the internal lists of allowed and denied methods. These are lists 42 | // of objects and each object has 2 properties: A resource ARN and a nullable 43 | // conditions statement. 44 | // the build method processes these lists and generates the approriate 45 | // statements for the final policy 46 | private struct Method 47 | { 48 | internal string ArnResource; 49 | internal IDictionary> Conditions; 50 | } 51 | private readonly List _allowMethods = new List(); 52 | private readonly List _denyMethods = new List(); 53 | 54 | /// The calling user principal 55 | /// The AWS account ID of the API owner 56 | /// API Gateway RestApi Id, a region for the RestApi, and a stage that calls should be allowed/denied for 57 | public AuthPolicyBuilder(string principalId, string awsAccountId, ApiOptions apiOptions) 58 | { 59 | PrincipalId = principalId; 60 | AwsAccountId = awsAccountId; 61 | 62 | // Replace the placeholder value with a default API Gateway API id to be used in the policy. 63 | // Beware of using '*' since it will not simply mean any API Gateway API id, because stars will greedily expand over '/' or other separators. 64 | // See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html for more details. 65 | _restApiId = string.IsNullOrWhiteSpace(apiOptions?.RestApiId) ? "<>" : apiOptions.RestApiId; 66 | 67 | // Replace the placeholder value with a default region to be used in the policy. 68 | // Beware of using '*' since it will not simply mean any region, because stars will greedily expand over '/' or other separators. 69 | // See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html for more details. 70 | _region = string.IsNullOrWhiteSpace(apiOptions?.Region) ? "<>" : apiOptions.Region; 71 | 72 | // Replace the placeholder value with a default stage to be used in the policy. 73 | // Beware of using '*' since it will not simply mean any stage, because stars will greedily expand over '/' or other separators. 74 | // See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html for more details. 75 | _stage = string.IsNullOrWhiteSpace(apiOptions?.Stage) ? "<>" : apiOptions.Stage; 76 | } 77 | 78 | public void DenyAllMethods(ICollection conditions = null) 79 | { 80 | AddMethod(Effect.Deny, HttpVerb.All, "*", conditions); 81 | } 82 | 83 | public void DenyMethod(HttpVerb verb, string resource, ICollection conditions = null) 84 | { 85 | AddMethod(Effect.Deny, verb, resource, conditions); 86 | } 87 | 88 | public void AllowAllMethods(ICollection conditions = null) 89 | { 90 | AddMethod(Effect.Allow, HttpVerb.All, "*", conditions); 91 | } 92 | 93 | public void AllowMethod(HttpVerb verb, string resource, ICollection conditions = null) 94 | { 95 | AddMethod(Effect.Allow, verb, resource, conditions); 96 | } 97 | 98 | public AuthPolicy Build() 99 | { 100 | var statements = new List(); 101 | foreach (var method in _allowMethods) 102 | { 103 | statements.Add(new Statement 104 | { 105 | Effect = Effect.Allow.ToString(), 106 | Resource = method.ArnResource, 107 | Action = "execute-api:Invoke", 108 | Condition = method.Conditions 109 | }); 110 | } 111 | foreach (var method in _denyMethods) 112 | { 113 | statements.Add(new Statement 114 | { 115 | Effect = Effect.Deny.ToString(), 116 | Resource = method.ArnResource, 117 | Action = "execute-api:Invoke", 118 | Condition = method.Conditions 119 | }); 120 | } 121 | 122 | return new AuthPolicy 123 | { 124 | PrincipalId = PrincipalId, 125 | PolicyDocument = new PolicyDocument 126 | { 127 | Version = PolicyVersion, 128 | Statement = statements 129 | } 130 | }; 131 | } 132 | 133 | private void AddMethod(Effect effect, HttpVerb verb, string resource, ICollection conditions = null) 134 | { 135 | if (verb == null) 136 | throw new ArgumentNullException(nameof(verb)); 137 | if (resource == null) 138 | throw new ArgumentNullException(nameof(resource)); 139 | 140 | if (!_pathRegex.IsMatch(resource)) 141 | throw new Exception($"Invalid resource path: {resource}. Path should match {_pathRegex}"); 142 | 143 | string cleanedResource = resource.First() == '/' ? resource.Substring(1) : resource; 144 | 145 | ApiGatewayArn arn = new ApiGatewayArn 146 | { 147 | RestApiId = _restApiId, 148 | Region = _region, 149 | Stage = _stage, 150 | AwsAccountId = AwsAccountId, 151 | Verb = verb.ToString(), 152 | Resource = cleanedResource 153 | }; 154 | 155 | switch (effect) 156 | { 157 | case Effect.Deny: 158 | _denyMethods.Add(new Method 159 | { 160 | ArnResource = arn.ToString(), 161 | Conditions = ConditionsToDictionary(conditions) 162 | }); 163 | return; 164 | case Effect.Allow: 165 | _allowMethods.Add(new Method 166 | { 167 | ArnResource = arn.ToString(), 168 | Conditions = ConditionsToDictionary(conditions) 169 | }); 170 | return; 171 | } 172 | } 173 | 174 | private IDictionary> ConditionsToDictionary(ICollection conditions = null) 175 | { 176 | if (conditions == null) 177 | return null; 178 | 179 | if (conditions.GroupBy(x => x.Operator).Any(x => x.Count() > 1)) 180 | throw new Exception($"Condition Operators Must be Unique per Statement"); 181 | 182 | return conditions.ToDictionary(condition => condition.Operator, condition => condition.KeyPairs); 183 | } 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler/Error/UnauthorizedException.cs: -------------------------------------------------------------------------------- 1 | namespace APIGatewayAuthorizerHandler.Error 2 | { 3 | internal class UnauthorizedException : System.Exception 4 | { 5 | public UnauthorizedException() : base("Unauthorized") 6 | { 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler/Function.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at 5 | * 6 | * http://aws.amazon.com/apache2.0/ 7 | * 8 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 9 | */ 10 | 11 | // Author: Caleb Petrick 12 | 13 | using System; 14 | using Amazon.Lambda.Core; 15 | using APIGatewayAuthorizerHandler.Error; 16 | using APIGatewayAuthorizerHandler.Model; 17 | using APIGatewayAuthorizerHandler.Model.Auth; 18 | using Newtonsoft.Json; 19 | 20 | namespace APIGatewayAuthorizerHandler 21 | { 22 | public class Function 23 | { 24 | /// 25 | /// A simple function that takes the token authorizer and returns a policy based on the authentication token included. 26 | /// 27 | /// token authorization received by api-gateway event sources 28 | /// 29 | /// IAM Auth Policy 30 | [LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] 31 | public AuthPolicy FunctionHandler(TokenAuthorizerContext input, ILambdaContext context) 32 | { 33 | try 34 | { 35 | context.Logger.LogLine($"{nameof(input.AuthorizationToken)}: {input.AuthorizationToken}"); 36 | context.Logger.LogLine($"{nameof(input.MethodArn)}: {input.MethodArn}"); 37 | 38 | // validate the incoming token 39 | // and produce the principal user identifier associated with the token 40 | 41 | // this could be accomplished in a number of ways: 42 | // 1. Call out to OAuth provider 43 | // 2. Decode a JWT token inline 44 | // 3. Lookup in a self-managed DB 45 | var principalId = "user|a1b2c3d4"; 46 | 47 | // you can send a 401 Unauthorized response to the client by failing like so: 48 | // throw new Exception("Unauthorized"); 49 | 50 | // if the token is valid, a policy must be generated which will allow or deny access to the client 51 | 52 | // if access is denied, the client will receive a 403 Access Denied response 53 | // if access is allowed, API Gateway will proceed with the backend integration configured on the method that was called 54 | 55 | // build apiOptions for the AuthPolicy 56 | var methodArn = ApiGatewayArn.Parse(input.MethodArn); 57 | var apiOptions = new ApiOptions(methodArn.Region, methodArn.RestApiId, methodArn.Stage); 58 | 59 | // this function must generate a policy that is associated with the recognized principal user identifier. 60 | // depending on your use case, you might store policies in a DB, or generate them on the fly 61 | 62 | // keep in mind, the policy is cached for 5 minutes by default (TTL is configurable in the authorizer) 63 | // and will apply to subsequent calls to any method/resource in the RestApi 64 | // made with the same token 65 | 66 | // the example policy below denies access to all resources in the RestApi 67 | var policyBuilder = new AuthPolicyBuilder(principalId, methodArn.AwsAccountId, apiOptions); 68 | policyBuilder.DenyAllMethods(); 69 | // policyBuilder.AllowMethod(HttpVerb.GET, "/users/username"); 70 | 71 | // finally, build the policy 72 | var authResponse = policyBuilder.Build(); 73 | 74 | // new! -- add additional key-value pairs 75 | // these are made available by APIGW like so: $context.authorizer. 76 | // additional context is cached 77 | authResponse.Context.Add("key", "value"); // $context.authorizer.key -> value 78 | authResponse.Context.Add("number", 1); 79 | authResponse.Context.Add("bool", true); 80 | 81 | return authResponse; 82 | } 83 | catch (Exception ex) 84 | { 85 | if (ex is UnauthorizedException) 86 | throw; 87 | 88 | // log the exception and return a 401 89 | context.Logger.LogLine(ex.ToString()); 90 | throw new UnauthorizedException(); 91 | } 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler/Model/ApiGatewayArn.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | namespace APIGatewayAuthorizerHandler.Model 4 | { 5 | /// 6 | /// Provided a POCO to simplify working with the MethodArn format. 7 | /// 8 | public class ApiGatewayArn 9 | { 10 | public string Partition { get; set; } = "aws"; 11 | public string Service { get; set; } = "execute-api"; 12 | public string Region { get; set; } 13 | public string AwsAccountId { get; set; } 14 | public string RestApiId { get; set; } 15 | public string Stage { get; set; } 16 | public string Verb { get; set; } 17 | public string Resource { get; set; } 18 | 19 | public override string ToString() 20 | { 21 | return $"arn:{Partition}:{Service}:{Region}:{AwsAccountId}:{RestApiId}/{Stage}/{Verb}/{Resource}"; 22 | } 23 | 24 | public static ApiGatewayArn Parse(string value) 25 | { 26 | var result = new ApiGatewayArn(); 27 | string[] arnSplit = value.Split(':'); 28 | 29 | result.Partition = arnSplit[1]; 30 | result.Service = arnSplit[2]; 31 | 32 | result.Region = arnSplit[3]; 33 | result.AwsAccountId = arnSplit[4]; 34 | 35 | string[] pathSplit = arnSplit[5].Split('/'); 36 | result.RestApiId = pathSplit[0]; 37 | result.Stage = pathSplit[1]; 38 | result.Verb = pathSplit[2]; 39 | 40 | if (pathSplit.Length > 3) 41 | { 42 | result.Resource = string.Join("/", pathSplit.Skip(3)); 43 | } 44 | 45 | return result; 46 | } 47 | 48 | public static bool TryParse(string value, out ApiGatewayArn methodArn) 49 | { 50 | try 51 | { 52 | methodArn = Parse(value); 53 | return true; 54 | } 55 | catch 56 | { 57 | methodArn = null; 58 | return false; 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler/Model/ApiOptions.cs: -------------------------------------------------------------------------------- 1 | namespace APIGatewayAuthorizerHandler.Model 2 | { 3 | public class ApiOptions 4 | { 5 | public string Region { get; set; } 6 | public string RestApiId { get; set; } 7 | public string Stage { get; set; } 8 | 9 | public ApiOptions() 10 | { 11 | } 12 | 13 | public ApiOptions(string region, string restApiId, string stage) 14 | { 15 | Region = region; 16 | RestApiId = restApiId; 17 | Stage = stage; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler/Model/Auth/AuthPolicy.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using Newtonsoft.Json; 4 | 5 | namespace APIGatewayAuthorizerHandler.Model.Auth 6 | { 7 | public class AuthPolicy 8 | { 9 | [JsonProperty(PropertyName = "principalId")] 10 | public string PrincipalId { get; set; } 11 | [JsonProperty(PropertyName = "policyDocument")] 12 | public PolicyDocument PolicyDocument { get; set; } 13 | 14 | [JsonProperty(PropertyName = "context", NullValueHandling = NullValueHandling.Ignore)] 15 | 16 | public IDictionary Context { get; set; } = new Dictionary(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler/Model/Auth/Condition.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace APIGatewayAuthorizerHandler.Model.Auth 4 | { 5 | public class Condition 6 | { 7 | public ConditionOperator Operator { get; set; } 8 | public IDictionary KeyPairs { get; set; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler/Model/Auth/ConditionKey.cs: -------------------------------------------------------------------------------- 1 | namespace APIGatewayAuthorizerHandler.Model.Auth 2 | { 3 | public class ConditionKey 4 | { 5 | private readonly string _key; 6 | 7 | public ConditionKey(string key) 8 | { 9 | _key = key; 10 | } 11 | 12 | public override string ToString() 13 | { 14 | return _key; 15 | } 16 | 17 | public static ConditionKey CurrentTime => new ConditionKey("aws:CurrentTime"); 18 | public static ConditionKey EpochTime => new ConditionKey("aws:EpochTime"); 19 | public static ConditionKey MultiFactorAuthAge => new ConditionKey("aws:MultiFactorAuthAge"); 20 | public static ConditionKey MultiFactorAuthPresent => new ConditionKey("aws:MultiFactorAuthPresent"); 21 | public static ConditionKey Referer => new ConditionKey("aws:Referer"); 22 | public static ConditionKey SecureTransport => new ConditionKey("aws:SecureTransport"); 23 | public static ConditionKey SourceArn => new ConditionKey("aws:SourceArn"); 24 | public static ConditionKey SourceIp => new ConditionKey("aws:SourceIp"); 25 | public static ConditionKey TokenIssueTime => new ConditionKey("aws:TokenIssueTime"); 26 | public static ConditionKey UserAgent => new ConditionKey("aws:UserAgent"); 27 | public static ConditionKey PrincipalType => new ConditionKey("aws:PrincipalType"); 28 | public static ConditionKey SourceVpc => new ConditionKey("aws:SourceVpc"); 29 | public static ConditionKey SourceVpce => new ConditionKey("aws:SourceVpce"); 30 | public static ConditionKey Userid => new ConditionKey("aws:userid"); 31 | public static ConditionKey Username => new ConditionKey("aws:username"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler/Model/Auth/ConditionOperator.cs: -------------------------------------------------------------------------------- 1 | namespace APIGatewayAuthorizerHandler.Model.Auth 2 | { 3 | public enum ConditionOperator 4 | { 5 | ArnEquals, 6 | ArnNotEquals, 7 | ArnLike, 8 | ArnNotLike, 9 | BinaryEquals, 10 | BinaryNotEquals, 11 | StringEquals, 12 | StringNotEquals, 13 | StringEqualsIgnoreCase, 14 | StringNotEqualsIgnoreCase, 15 | StringLike, 16 | StringNotLike, 17 | Null, 18 | NumericEquals, 19 | NumericNotEquals, 20 | NumericLessThan, 21 | NumericLessThanEquals, 22 | NumericGreaterThan, 23 | NumericGreaterThanEquals, 24 | DateEquals, 25 | DateNotEquals, 26 | DateLessThan, 27 | DateLessThanEquals, 28 | DateGreaterThan, 29 | DateGreaterThanEquals, 30 | Bool, 31 | IpAddress, 32 | NotIpAddress 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler/Model/Auth/Effect.cs: -------------------------------------------------------------------------------- 1 | namespace APIGatewayAuthorizerHandler.Model.Auth 2 | { 3 | public enum Effect 4 | { 5 | Deny, 6 | Allow 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler/Model/Auth/PolicyDocument.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System.Collections.Generic; 3 | 4 | namespace APIGatewayAuthorizerHandler.Model.Auth 5 | { 6 | public class PolicyDocument 7 | { 8 | [JsonProperty(PropertyName = "Version")] 9 | public string Version { get; set; } 10 | [JsonProperty(PropertyName = "Statement")] 11 | public IEnumerable Statement { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler/Model/Auth/Statement.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System.Collections.Generic; 3 | 4 | namespace APIGatewayAuthorizerHandler.Model.Auth 5 | { 6 | public class Statement 7 | { 8 | [JsonProperty(PropertyName = "Action")] 9 | public string Action { get; set; } 10 | [JsonProperty(PropertyName = "Effect")] 11 | public string Effect { get; set; } = "Deny"; // Default to Deny to ensure Allows are explicitly set 12 | [JsonProperty(PropertyName = "Resource")] 13 | public string Resource { get; set; } 14 | [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] 15 | public IDictionary> Condition { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler/Model/HttpVerb.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | 3 | namespace APIGatewayAuthorizerHandler.Model 4 | { 5 | /// 6 | /// A set of existing HTTP verbs supported by API Gateway. 7 | /// This class is here to avoid spelling mistakes in the policy. 8 | /// 9 | public sealed class HttpVerb 10 | { 11 | private readonly string _verb; 12 | 13 | private HttpVerb(string verb) 14 | { 15 | _verb = verb; 16 | } 17 | 18 | public override string ToString() 19 | { 20 | return _verb; 21 | } 22 | 23 | public static HttpVerb Get => new HttpVerb("GET"); 24 | public static HttpVerb Post => new HttpVerb("POST"); 25 | public static HttpVerb Put => new HttpVerb("PUT"); 26 | public static HttpVerb Patch => new HttpVerb("PATCH"); 27 | public static HttpVerb Head => new HttpVerb("HEAD"); 28 | public static HttpVerb Delete => new HttpVerb("DELETE"); 29 | public static HttpVerb Options => new HttpVerb("OPTIONS"); 30 | public static HttpVerb All => new HttpVerb("*"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /blueprints/dotnet/src/APIGatewayAuthorizerHandler/Model/TokenAuthorizerContext.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace APIGatewayAuthorizerHandler.Model 4 | { 5 | public class TokenAuthorizerContext 6 | { 7 | [JsonProperty(PropertyName = "Type")] 8 | public string Type { get; set; } 9 | [JsonProperty(PropertyName = "AuthorizationToken")] 10 | public string AuthorizationToken { get; set; } 11 | [JsonProperty(PropertyName = "MethodArn")] 12 | public string MethodArn { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /blueprints/go/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). 4 | // You may not use this file except in compliance with the License. 5 | // A copy of the License is located at 6 | // 7 | // http://aws.amazon.com/apache2.0/ 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed 10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package main 15 | 16 | import ( 17 | "context" 18 | "log" 19 | "strings" 20 | 21 | "github.com/aws/aws-lambda-go/events" 22 | "github.com/aws/aws-lambda-go/lambda" 23 | ) 24 | 25 | func handleRequest(ctx context.Context, event events.APIGatewayCustomAuthorizerRequest) (events.APIGatewayCustomAuthorizerResponse, error) { 26 | // Do not print the auth token unless absolutely necessary 27 | + // log.Println("Client token: " + event.AuthorizationToken) 28 | log.Println("Method ARN: " + event.MethodArn) 29 | 30 | // validate the incoming token 31 | // and produce the principal user identifier associated with the token 32 | 33 | // this could be accomplished in a number of ways: 34 | // 1. Call out to OAuth provider 35 | // 2. Decode a JWT token inline 36 | // 3. Lookup in a self-managed DB 37 | principalID := "user|a1b2c3d4" 38 | 39 | // you can send a 401 Unauthorized response to the client by failing like so: 40 | // return events.APIGatewayCustomAuthorizerResponse{}, errors.New("Unauthorized") 41 | 42 | // if the token is valid, a policy must be generated which will allow or deny access to the client 43 | 44 | // if access is denied, the client will recieve a 403 Access Denied response 45 | // if access is allowed, API Gateway will proceed with the backend integration configured on the method that was called 46 | 47 | // this function must generate a policy that is associated with the recognized principal user identifier. 48 | // depending on your use case, you might store policies in a DB, or generate them on the fly 49 | 50 | // keep in mind, the policy is cached for 5 minutes by default (TTL is configurable in the authorizer) 51 | // and will apply to subsequent calls to any method/resource in the RestApi 52 | // made with the same token 53 | 54 | //the example policy below denies access to all resources in the RestApi 55 | tmp := strings.Split(event.MethodArn, ":") 56 | apiGatewayArnTmp := strings.Split(tmp[5], "/") 57 | awsAccountID := tmp[4] 58 | 59 | resp := NewAuthorizerResponse(principalID, awsAccountID) 60 | resp.Region = tmp[3] 61 | resp.APIID = apiGatewayArnTmp[0] 62 | resp.Stage = apiGatewayArnTmp[1] 63 | resp.DenyAllMethods() 64 | // resp.AllowMethod(Get, "/pets/*") 65 | 66 | // new! -- add additional key-value pairs associated with the authenticated principal 67 | // these are made available by APIGW like so: $context.authorizer. 68 | // additional context is cached 69 | resp.Context = map[string]interface{}{ 70 | "stringKey": "stringval", 71 | "numberKey": 123, 72 | "booleanKey": true, 73 | } 74 | 75 | return resp.APIGatewayCustomAuthorizerResponse, nil 76 | } 77 | 78 | func main() { 79 | lambda.Start(handleRequest) 80 | } 81 | 82 | type HttpVerb int 83 | 84 | const ( 85 | Get HttpVerb = iota 86 | Post 87 | Put 88 | Delete 89 | Patch 90 | Head 91 | Options 92 | All 93 | ) 94 | 95 | func (hv HttpVerb) String() string { 96 | switch hv { 97 | case Get: 98 | return "GET" 99 | case Post: 100 | return "POST" 101 | case Put: 102 | return "PUT" 103 | case Delete: 104 | return "DELETE" 105 | case Patch: 106 | return "PATCH" 107 | case Head: 108 | return "HEAD" 109 | case Options: 110 | return "OPTIONS" 111 | case All: 112 | return "*" 113 | } 114 | return "" 115 | } 116 | 117 | type Effect int 118 | 119 | const ( 120 | Allow Effect = iota 121 | Deny 122 | ) 123 | 124 | func (e Effect) String() string { 125 | switch e { 126 | case Allow: 127 | return "Allow" 128 | case Deny: 129 | return "Deny" 130 | } 131 | return "" 132 | } 133 | 134 | type AuthorizerResponse struct { 135 | events.APIGatewayCustomAuthorizerResponse 136 | 137 | // The region where the API is deployed. By default this is set to '*' 138 | Region string 139 | 140 | // The AWS account id the policy will be generated for. This is used to create the method ARNs. 141 | AccountID string 142 | 143 | // The API Gateway API id. By default this is set to '*' 144 | APIID string 145 | 146 | // The name of the stage used in the policy. By default this is set to '*' 147 | Stage string 148 | } 149 | 150 | func NewAuthorizerResponse(principalID string, AccountID string) *AuthorizerResponse { 151 | return &AuthorizerResponse{ 152 | APIGatewayCustomAuthorizerResponse: events.APIGatewayCustomAuthorizerResponse{ 153 | PrincipalID: principalID, 154 | PolicyDocument: events.APIGatewayCustomAuthorizerPolicy{ 155 | Version: "2012-10-17", 156 | }, 157 | }, 158 | // Replace the placeholder value with a default region to be used in the policy. 159 | // Beware of using '*' since it will not simply mean any region, because stars will greedily expand over '/' or other separators. 160 | // See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html for more details. 161 | Region: "<>", 162 | AccountID: AccountID, 163 | 164 | // Replace the placeholder value with a default API Gateway API id to be used in the policy. 165 | // Beware of using '*' since it will not simply mean any API Gateway API id, because stars will greedily expand over '/' or other separators. 166 | // See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html for more details. 167 | APIID: "<>", 168 | 169 | // Replace the placeholder value with a default stage to be used in the policy. 170 | // Beware of using '*' since it will not simply mean any stage, because stars will greedily expand over '/' or other separators. 171 | // See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html for more details. 172 | Stage: "<>", 173 | } 174 | } 175 | 176 | func (r *AuthorizerResponse) addMethod(effect Effect, verb HttpVerb, resource string) { 177 | resourceArn := "arn:aws:execute-api:" + 178 | r.Region + ":" + 179 | r.AccountID + ":" + 180 | r.APIID + "/" + 181 | r.Stage + "/" + 182 | verb.String() + "/" + 183 | strings.TrimLeft(resource, "/") 184 | 185 | s := events.IAMPolicyStatement{ 186 | Effect: effect.String(), 187 | Action: []string{"execute-api:Invoke"}, 188 | Resource: []string{resourceArn}, 189 | } 190 | 191 | r.PolicyDocument.Statement = append(r.PolicyDocument.Statement, s) 192 | } 193 | 194 | func (r *AuthorizerResponse) AllowAllMethods() { 195 | r.addMethod(Allow, All, "*") 196 | } 197 | 198 | func (r *AuthorizerResponse) DenyAllMethods() { 199 | r.addMethod(Deny, All, "*") 200 | } 201 | 202 | func (r *AuthorizerResponse) AllowMethod(verb HttpVerb, resource string) { 203 | r.addMethod(Allow, verb, resource) 204 | } 205 | 206 | func (r *AuthorizerResponse) DenyMethod(verb HttpVerb, resource string) { 207 | r.addMethod(Deny, verb, resource) 208 | } 209 | -------------------------------------------------------------------------------- /blueprints/java/src/example/APIGatewayAuthorizerHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at 5 | * 6 | * http://aws.amazon.com/apache2.0/ 7 | * 8 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 9 | */ 10 | package example; 11 | 12 | import io.AuthPolicy; 13 | import io.TokenAuthorizerContext; 14 | 15 | import com.amazonaws.services.lambda.runtime.Context; 16 | import com.amazonaws.services.lambda.runtime.RequestHandler; 17 | 18 | /** 19 | * Handles IO for a Java Lambda function as a custom authorizer for API Gateway 20 | * 21 | * @author Jack Kohn 22 | * 23 | */ 24 | public class APIGatewayAuthorizerHandler implements RequestHandler { 25 | 26 | @Override 27 | public AuthPolicy handleRequest(TokenAuthorizerContext input, Context context) { 28 | 29 | String token = input.getAuthorizationToken(); 30 | 31 | // validate the incoming token 32 | // and produce the principal user identifier associated with the token 33 | 34 | // this could be accomplished in a number of ways: 35 | // 1. Call out to OAuth provider 36 | // 2. Decode a JWT token in-line 37 | // 3. Lookup in a self-managed DB 38 | String principalId = "xxxx"; 39 | 40 | // if the client token is not recognized or invalid 41 | // you can send a 401 Unauthorized response to the client by failing like so: 42 | // throw new RuntimeException("Unauthorized"); 43 | 44 | // if the token is valid, a policy should be generated which will allow or deny access to the client 45 | 46 | // if access is denied, the client will receive a 403 Access Denied response 47 | // if access is allowed, API Gateway will proceed with the back-end integration configured on the method that was called 48 | 49 | String methodArn = input.getMethodArn(); 50 | String[] arnPartials = methodArn.split(":"); 51 | String region = arnPartials[3]; 52 | String awsAccountId = arnPartials[4]; 53 | String[] apiGatewayArnPartials = arnPartials[5].split("/"); 54 | String restApiId = apiGatewayArnPartials[0]; 55 | String stage = apiGatewayArnPartials[1]; 56 | String httpMethod = apiGatewayArnPartials[2]; 57 | String resource = ""; // root resource 58 | if (apiGatewayArnPartials.length == 4) { 59 | resource = apiGatewayArnPartials[3]; 60 | } 61 | 62 | // this function must generate a policy that is associated with the recognized principal user identifier. 63 | // depending on your use case, you might store policies in a DB, or generate them on the fly 64 | 65 | // keep in mind, the policy is cached for 5 minutes by default (TTL is configurable in the authorizer) 66 | // and will apply to subsequent calls to any method/resource in the RestApi 67 | // made with the same token 68 | 69 | // the example policy below denies access to all resources in the RestApi 70 | return new AuthPolicy(principalId, AuthPolicy.PolicyDocument.getDenyAllPolicy(region, awsAccountId, restApiId, stage)); 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /blueprints/java/src/io/AuthPolicy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at 5 | * 6 | * http://aws.amazon.com/apache2.0/ 7 | * 8 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 9 | */ 10 | package io; 11 | 12 | import java.util.ArrayList; 13 | import java.util.Collections; 14 | import java.util.HashMap; 15 | import java.util.List; 16 | import java.util.Map; 17 | 18 | /** 19 | * AuthPolicy receives a set of allowed and denied methods and generates a valid 20 | * AWS policy for the API Gateway authorizer. The constructor receives the calling 21 | * user principal, the AWS account ID of the API owner, and an apiOptions object. 22 | * The apiOptions can contain an API Gateway RestApi Id, a region for the RestApi, and a 23 | * stage that calls should be allowed/denied for. For example 24 | * 25 | * new AuthPolicy(principalId, AuthPolicy.PolicyDocument.getDenyAllPolicy(region, awsAccountId, restApiId, stage)); 26 | * 27 | * @author Jack Kohn 28 | */ 29 | public class AuthPolicy { 30 | 31 | // IAM Policy Constants 32 | public static final String VERSION = "Version"; 33 | public static final String STATEMENT = "Statement"; 34 | public static final String EFFECT = "Effect"; 35 | public static final String ACTION = "Action"; 36 | public static final String NOT_ACTION = "NotAction"; 37 | public static final String RESOURCE = "Resource"; 38 | public static final String NOT_RESOURCE = "NotResource"; 39 | public static final String CONDITION = "Condition"; 40 | 41 | String principalId; 42 | transient AuthPolicy.PolicyDocument policyDocumentObject; 43 | Map policyDocument; 44 | 45 | public AuthPolicy(String principalId, AuthPolicy.PolicyDocument policyDocumentObject) { 46 | this.principalId = principalId; 47 | this.policyDocumentObject = policyDocumentObject; 48 | } 49 | 50 | public AuthPolicy() { 51 | } 52 | 53 | public String getPrincipalId() { 54 | return principalId; 55 | } 56 | 57 | public void setPrincipalId(String principalId) { 58 | this.principalId = principalId; 59 | } 60 | 61 | /** 62 | * IAM Policies use capitalized field names, but Lambda by default will serialize object members using camel case 63 | * 64 | * This method implements a custom serializer to return the IAM Policy as a well-formed JSON document, with the correct field names 65 | * 66 | * @return IAM Policy as a well-formed JSON document 67 | */ 68 | public Map getPolicyDocument() { 69 | Map serializablePolicy = new HashMap<>(); 70 | serializablePolicy.put(VERSION, policyDocumentObject.Version); 71 | Statement[] statements = policyDocumentObject.getStatement(); 72 | Map[] serializableStatementArray = new Map[statements.length]; 73 | for (int i = 0; i < statements.length; i++) { 74 | Map serializableStatement = new HashMap<>(); 75 | AuthPolicy.Statement statement = statements[i]; 76 | serializableStatement.put(EFFECT, statement.Effect); 77 | serializableStatement.put(ACTION, statement.Action); 78 | serializableStatement.put(RESOURCE, statement.getResource()); 79 | serializableStatement.put(CONDITION, statement.getCondition()); 80 | serializableStatementArray[i] = serializableStatement; 81 | } 82 | serializablePolicy.put(STATEMENT, serializableStatementArray); 83 | return serializablePolicy; 84 | } 85 | 86 | public void setPolicyDocument(PolicyDocument policyDocumentObject) { 87 | this.policyDocumentObject = policyDocumentObject; 88 | } 89 | 90 | /** 91 | * PolicyDocument represents an IAM Policy, specifically for the execute-api:Invoke action 92 | * in the context of a API Gateway Authorizer 93 | * 94 | * Initialize the PolicyDocument with 95 | * the region where the RestApi is configured, 96 | * the AWS Account ID that owns the RestApi, 97 | * the RestApi identifier 98 | * and the Stage on the RestApi that the Policy will apply to 99 | */ 100 | public static class PolicyDocument { 101 | 102 | static final String EXECUTE_API_ARN_FORMAT = "arn:aws:execute-api:%s:%s:%s/%s/%s/%s"; 103 | 104 | String Version = "2012-10-17"; // override if necessary 105 | 106 | private Statement allowStatement; 107 | private Statement denyStatement; 108 | private List statements; 109 | 110 | // context metadata 111 | transient String region; 112 | transient String awsAccountId; 113 | transient String restApiId; 114 | transient String stage; 115 | 116 | /** 117 | * Creates a new PolicyDocument with the given context, 118 | * and initializes two base Statement objects for allowing and denying access to API Gateway methods 119 | * 120 | * @param region the region where the RestApi is configured 121 | * @param awsAccountId the AWS Account ID that owns the RestApi 122 | * @param restApiId the RestApi identifier 123 | * @param stage and the Stage on the RestApi that the Policy will apply to 124 | */ 125 | public PolicyDocument(String region, String awsAccountId, String restApiId, String stage) { 126 | this.region = region; 127 | this.awsAccountId = awsAccountId; 128 | this.restApiId = restApiId; 129 | this.stage = stage; 130 | allowStatement = Statement.getEmptyInvokeStatement("Allow"); 131 | denyStatement = Statement.getEmptyInvokeStatement("Deny"); 132 | this.statements = new ArrayList<>(); 133 | statements.add(allowStatement); 134 | statements.add(denyStatement); 135 | } 136 | 137 | public String getVersion() { 138 | return Version; 139 | } 140 | 141 | public void setVersion(String version) { 142 | Version = version; 143 | } 144 | 145 | public AuthPolicy.Statement[] getStatement() { 146 | return statements.toArray(new AuthPolicy.Statement[statements.size()]); 147 | } 148 | 149 | public void allowMethod(HttpMethod httpMethod, String resourcePath) { 150 | addResourceToStatement(allowStatement, httpMethod, resourcePath); 151 | } 152 | 153 | public void denyMethod(HttpMethod httpMethod, String resourcePath) { 154 | addResourceToStatement(denyStatement, httpMethod, resourcePath); 155 | } 156 | 157 | public void addStatement(AuthPolicy.Statement statement) { 158 | statements.add(statement); 159 | } 160 | 161 | private void addResourceToStatement(Statement statement, HttpMethod httpMethod, String resourcePath) { 162 | // resourcePath must start with '/' 163 | // to specify the root resource only, resourcePath should be an empty string 164 | if (resourcePath.equals("/")) { 165 | resourcePath = ""; 166 | } 167 | String resource = resourcePath.startsWith("/") ? resourcePath.substring(1) : resourcePath; 168 | String method = httpMethod == HttpMethod.ALL ? "*" : httpMethod.toString(); 169 | statement.addResource(String.format(EXECUTE_API_ARN_FORMAT, region, awsAccountId, restApiId, stage, method, resource)); 170 | } 171 | 172 | // Static methods 173 | 174 | /** 175 | * Generates a new PolicyDocument with a single statement that allows the requested method/resourcePath 176 | * 177 | * @param region API Gateway region 178 | * @param awsAccountId AWS Account that owns the API Gateway RestApi 179 | * @param restApiId RestApi identifier 180 | * @param stage Stage name 181 | * @param method HttpMethod to allow 182 | * @param resourcePath Resource path to allow 183 | * @return new PolicyDocument that allows the requested method/resourcePath 184 | */ 185 | public static PolicyDocument getAllowOnePolicy(String region, String awsAccountId, String restApiId, String stage, HttpMethod method, String resourcePath) { 186 | AuthPolicy.PolicyDocument policyDocument = new AuthPolicy.PolicyDocument(region, awsAccountId, restApiId, stage); 187 | policyDocument.allowMethod(method, resourcePath); 188 | return policyDocument; 189 | 190 | } 191 | 192 | 193 | /** 194 | * Generates a new PolicyDocument with a single statement that denies the requested method/resourcePath 195 | * 196 | * @param region API Gateway region 197 | * @param awsAccountId AWS Account that owns the API Gateway RestApi 198 | * @param restApiId RestApi identifier 199 | * @param stage Stage name 200 | * @param method HttpMethod to deny 201 | * @param resourcePath Resource path to deny 202 | * @return new PolicyDocument that denies the requested method/resourcePath 203 | */ 204 | public static PolicyDocument getDenyOnePolicy(String region, String awsAccountId, String restApiId, String stage, HttpMethod method, String resourcePath) { 205 | AuthPolicy.PolicyDocument policyDocument = new AuthPolicy.PolicyDocument(region, awsAccountId, restApiId, stage); 206 | policyDocument.denyMethod(method, resourcePath); 207 | return policyDocument; 208 | 209 | } 210 | 211 | public static AuthPolicy.PolicyDocument getAllowAllPolicy(String region, String awsAccountId, String restApiId, String stage) { 212 | return getAllowOnePolicy(region, awsAccountId, restApiId, stage, HttpMethod.ALL, "*"); 213 | } 214 | 215 | public static PolicyDocument getDenyAllPolicy(String region, String awsAccountId, String restApiId, String stage) { 216 | return getDenyOnePolicy(region, awsAccountId, restApiId, stage, HttpMethod.ALL, "*"); 217 | } 218 | } 219 | 220 | public enum HttpMethod { 221 | GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS, ALL 222 | } 223 | 224 | static class Statement { 225 | 226 | String Effect; 227 | String Action; 228 | Map> Condition; 229 | 230 | private List resourceList; 231 | 232 | public Statement() { 233 | 234 | } 235 | 236 | public Statement(String effect, String action, List resourceList, Map> condition) { 237 | this.Effect = effect; 238 | this.Action = action; 239 | this.resourceList = resourceList; 240 | this.Condition = condition; 241 | } 242 | 243 | public static Statement getEmptyInvokeStatement(String effect) { 244 | return new Statement(effect, "execute-api:Invoke", new ArrayList<>(), new HashMap<>()); 245 | } 246 | 247 | public String getEffect() { 248 | return Effect; 249 | } 250 | 251 | public void setEffect(String effect) { 252 | this.Effect = effect; 253 | } 254 | 255 | public String getAction() { 256 | return Action; 257 | } 258 | 259 | public void setAction(String action) { 260 | this.Action = action; 261 | } 262 | 263 | public String[] getResource() { 264 | return resourceList.toArray(new String[resourceList.size()]); 265 | } 266 | 267 | public void addResource(String resource) { 268 | resourceList.add(resource); 269 | } 270 | 271 | public Map> getCondition() { 272 | return Condition; 273 | } 274 | 275 | public void addCondition(String operator, String key, Object value) { 276 | Condition.put(operator, Collections.singletonMap(key, value)); 277 | } 278 | 279 | } 280 | 281 | } 282 | -------------------------------------------------------------------------------- /blueprints/java/src/io/TokenAuthorizerContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at 5 | * 6 | * http://aws.amazon.com/apache2.0/ 7 | * 8 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 9 | */ 10 | package io; 11 | 12 | /** 13 | * Object representation of input to an implementation of an API Gateway custom authorizer 14 | * of type TOKEN 15 | * 16 | * @author Jack Kohn 17 | */ 18 | public class TokenAuthorizerContext { 19 | 20 | String type; 21 | String authorizationToken; 22 | String methodArn; 23 | 24 | /** 25 | * JSON input is deserialized into this object representation 26 | * @param type Static value - TOKEN 27 | * @param authorizationToken - Incoming bearer token sent by a client 28 | * @param methodArn - The API Gateway method ARN that a client requested 29 | */ 30 | public TokenAuthorizerContext(String type, String authorizationToken, String methodArn) { 31 | this.type = type; 32 | this.authorizationToken = authorizationToken; 33 | this.methodArn = methodArn; 34 | } 35 | 36 | public TokenAuthorizerContext() { 37 | 38 | } 39 | 40 | public String getType() { 41 | return type; 42 | } 43 | 44 | public void setType(String type) { 45 | this.type = type; 46 | } 47 | 48 | public String getAuthorizationToken() { 49 | return authorizationToken; 50 | } 51 | 52 | public void setAuthorizationToken(String authorizationToken) { 53 | this.authorizationToken = authorizationToken; 54 | } 55 | 56 | public String getMethodArn() { 57 | return methodArn; 58 | } 59 | 60 | public void setMethodArn(String methodArn) { 61 | this.methodArn = methodArn; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /blueprints/nodejs/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at 5 | * 6 | * http://aws.amazon.com/apache2.0/ 7 | * 8 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 9 | */ 10 | console.log('Loading function'); 11 | 12 | exports.handler = function(event, context, callback) { 13 | // Do not print the auth token unless absolutely necessary 14 | // console.log('Client token: ' + event.authorizationToken); 15 | console.log('Method ARN: ' + event.methodArn); 16 | 17 | // validate the incoming token 18 | // and produce the principal user identifier associated with the token 19 | 20 | // this could be accomplished in a number of ways: 21 | // 1. Call out to OAuth provider 22 | // 2. Decode a JWT token inline 23 | // 3. Lookup in a self-managed DB 24 | var principalId = 'user|a1b2c3d4' 25 | 26 | // you can send a 401 Unauthorized response to the client by failing like so: 27 | // callback("Unauthorized", null); 28 | 29 | // if the token is valid, a policy must be generated which will allow or deny access to the client 30 | 31 | // if access is denied, the client will receive a 403 Access Denied response 32 | // if access is allowed, API Gateway will proceed with the backend integration configured on the method that was called 33 | 34 | // build apiOptions for the AuthPolicy 35 | var apiOptions = {}; 36 | var tmp = event.methodArn.split(':'); 37 | var apiGatewayArnTmp = tmp[5].split('/'); 38 | var awsAccountId = tmp[4]; 39 | apiOptions.region = tmp[3]; 40 | apiOptions.restApiId = apiGatewayArnTmp[0]; 41 | apiOptions.stage = apiGatewayArnTmp[1]; 42 | var method = apiGatewayArnTmp[2]; 43 | var resource = '/'; // root resource 44 | if (apiGatewayArnTmp[3]) { 45 | resource += apiGatewayArnTmp.slice(3, apiGatewayArnTmp.length).join('/'); 46 | } 47 | 48 | // this function must generate a policy that is associated with the recognized principal user identifier. 49 | // depending on your use case, you might store policies in a DB, or generate them on the fly 50 | 51 | // keep in mind, the policy is cached for 5 minutes by default (TTL is configurable in the authorizer) 52 | // and will apply to subsequent calls to any method/resource in the RestApi 53 | // made with the same token 54 | 55 | // the example policy below denies access to all resources in the RestApi 56 | var policy = new AuthPolicy(principalId, awsAccountId, apiOptions); 57 | policy.denyAllMethods(); 58 | // policy.allowMethod(AuthPolicy.HttpVerb.GET, "/users/username"); 59 | 60 | // finally, build the policy 61 | var authResponse = policy.build(); 62 | 63 | // new! -- add additional key-value pairs 64 | // these are made available by APIGW like so: $context.authorizer. 65 | // additional context is cached 66 | authResponse.context = { 67 | key : 'value', // $context.authorizer.key -> value 68 | number : 1, 69 | bool: true 70 | }; 71 | // authResponse.context.arr = ['foo']; <- this is invalid, APIGW will not accept it 72 | // authResponse.context.obj = {'foo':'bar'}; <- also invalid 73 | 74 | callback(null, authResponse); 75 | }; 76 | 77 | /** 78 | * AuthPolicy receives a set of allowed and denied methods and generates a valid 79 | * AWS policy for the API Gateway authorizer. The constructor receives the calling 80 | * user principal, the AWS account ID of the API owner, and an apiOptions object. 81 | * The apiOptions can contain an API Gateway RestApi Id, a region for the RestApi, and a 82 | * stage that calls should be allowed/denied for. For example 83 | * { 84 | * restApiId: "xxxxxxxxxx", 85 | * region: "us-east-1", 86 | * stage: "dev" 87 | * } 88 | * 89 | * var testPolicy = new AuthPolicy("[principal user identifier]", "[AWS account id]", apiOptions); 90 | * testPolicy.allowMethod(AuthPolicy.HttpVerb.GET, "/users/username"); 91 | * testPolicy.denyMethod(AuthPolicy.HttpVerb.POST, "/pets"); 92 | * context.succeed(testPolicy.build()); 93 | * 94 | * @class AuthPolicy 95 | * @constructor 96 | */ 97 | function AuthPolicy(principal, awsAccountId, apiOptions) { 98 | /** 99 | * The AWS account id the policy will be generated for. This is used to create 100 | * the method ARNs. 101 | * 102 | * @property awsAccountId 103 | * @type {String} 104 | */ 105 | this.awsAccountId = awsAccountId; 106 | 107 | /** 108 | * The principal used for the policy, this should be a unique identifier for 109 | * the end user. 110 | * 111 | * @property principalId 112 | * @type {String} 113 | */ 114 | this.principalId = principal; 115 | 116 | /** 117 | * The policy version used for the evaluation. This should always be "2012-10-17" 118 | * 119 | * @property version 120 | * @type {String} 121 | * @default "2012-10-17" 122 | */ 123 | this.version = "2012-10-17"; 124 | 125 | /** 126 | * The regular expression used to validate resource paths for the policy 127 | * 128 | * @property pathRegex 129 | * @type {RegExp} 130 | * @default '^\/[/.a-zA-Z0-9-\*]+$' 131 | */ 132 | this.pathRegex = new RegExp('^[/.a-zA-Z0-9-\*]+$'); 133 | 134 | // these are the internal lists of allowed and denied methods. These are lists 135 | // of objects and each object has 2 properties: A resource ARN and a nullable 136 | // conditions statement. 137 | // the build method processes these lists and generates the approriate 138 | // statements for the final policy 139 | this.allowMethods = []; 140 | this.denyMethods = []; 141 | 142 | if (!apiOptions || !apiOptions.restApiId) { 143 | // Replace the placeholder value with a default API Gateway API id to be used in the policy. 144 | // Beware of using '*' since it will not simply mean any API Gateway API id, because stars will greedily expand over '/' or other separators. 145 | // See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html for more details. 146 | this.restApiId = "<>"; 147 | } else { 148 | this.restApiId = apiOptions.restApiId; 149 | } 150 | if (!apiOptions || !apiOptions.region) { 151 | // Replace the placeholder value with a default region to be used in the policy. 152 | // Beware of using '*' since it will not simply mean any region, because stars will greedily expand over '/' or other separators. 153 | // See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html for more details. 154 | this.region = "<>"; 155 | } else { 156 | this.region = apiOptions.region; 157 | } 158 | if (!apiOptions || !apiOptions.stage) { 159 | // Replace the placeholder value with a default stage to be used in the policy. 160 | // Beware of using '*' since it will not simply mean any stage, because stars will greedily expand over '/' or other separators. 161 | // See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html for more details. 162 | this.stage = "<>"; 163 | } else { 164 | this.stage = apiOptions.stage; 165 | } 166 | }; 167 | 168 | /** 169 | * A set of existing HTTP verbs supported by API Gateway. This property is here 170 | * only to avoid spelling mistakes in the policy. 171 | * 172 | * @property HttpVerb 173 | * @type {Object} 174 | */ 175 | AuthPolicy.HttpVerb = { 176 | GET : "GET", 177 | POST : "POST", 178 | PUT : "PUT", 179 | PATCH : "PATCH", 180 | HEAD : "HEAD", 181 | DELETE : "DELETE", 182 | OPTIONS : "OPTIONS", 183 | ALL : "*" 184 | }; 185 | 186 | AuthPolicy.prototype = (function() { 187 | /** 188 | * Adds a method to the internal lists of allowed or denied methods. Each object in 189 | * the internal list contains a resource ARN and a condition statement. The condition 190 | * statement can be null. 191 | * 192 | * @method addMethod 193 | * @param {String} The effect for the policy. This can only be "Allow" or "Deny". 194 | * @param {String} he HTTP verb for the method, this should ideally come from the 195 | * AuthPolicy.HttpVerb object to avoid spelling mistakes 196 | * @param {String} The resource path. For example "/pets" 197 | * @param {Object} The conditions object in the format specified by the AWS docs. 198 | * @return {void} 199 | */ 200 | var addMethod = function(effect, verb, resource, conditions) { 201 | if (verb != "*" && !AuthPolicy.HttpVerb.hasOwnProperty(verb)) { 202 | throw new Error("Invalid HTTP verb " + verb + ". Allowed verbs in AuthPolicy.HttpVerb"); 203 | } 204 | 205 | if (!this.pathRegex.test(resource)) { 206 | throw new Error("Invalid resource path: " + resource + ". Path should match " + this.pathRegex); 207 | } 208 | 209 | var cleanedResource = resource; 210 | if (resource.substring(0, 1) == "/") { 211 | cleanedResource = resource.substring(1, resource.length); 212 | } 213 | var resourceArn = "arn:aws:execute-api:" + 214 | this.region + ":" + 215 | this.awsAccountId + ":" + 216 | this.restApiId + "/" + 217 | this.stage + "/" + 218 | verb + "/" + 219 | cleanedResource; 220 | 221 | if (effect.toLowerCase() == "allow") { 222 | this.allowMethods.push({ 223 | resourceArn: resourceArn, 224 | conditions: conditions 225 | }); 226 | } else if (effect.toLowerCase() == "deny") { 227 | this.denyMethods.push({ 228 | resourceArn: resourceArn, 229 | conditions: conditions 230 | }) 231 | } 232 | }; 233 | 234 | /** 235 | * Returns an empty statement object prepopulated with the correct action and the 236 | * desired effect. 237 | * 238 | * @method getEmptyStatement 239 | * @param {String} The effect of the statement, this can be "Allow" or "Deny" 240 | * @return {Object} An empty statement object with the Action, Effect, and Resource 241 | * properties prepopulated. 242 | */ 243 | var getEmptyStatement = function(effect) { 244 | effect = effect.substring(0, 1).toUpperCase() + effect.substring(1, effect.length).toLowerCase(); 245 | var statement = {}; 246 | statement.Action = "execute-api:Invoke"; 247 | statement.Effect = effect; 248 | statement.Resource = []; 249 | 250 | return statement; 251 | }; 252 | 253 | /** 254 | * This function loops over an array of objects containing a resourceArn and 255 | * conditions statement and generates the array of statements for the policy. 256 | * 257 | * @method getStatementsForEffect 258 | * @param {String} The desired effect. This can be "Allow" or "Deny" 259 | * @param {Array} An array of method objects containing the ARN of the resource 260 | * and the conditions for the policy 261 | * @return {Array} an array of formatted statements for the policy. 262 | */ 263 | var getStatementsForEffect = function(effect, methods) { 264 | var statements = []; 265 | 266 | if (methods.length > 0) { 267 | var statement = getEmptyStatement(effect); 268 | 269 | for (var i = 0; i < methods.length; i++) { 270 | var curMethod = methods[i]; 271 | if (curMethod.conditions === null || curMethod.conditions.length === 0) { 272 | statement.Resource.push(curMethod.resourceArn); 273 | } else { 274 | var conditionalStatement = getEmptyStatement(effect); 275 | conditionalStatement.Resource.push(curMethod.resourceArn); 276 | conditionalStatement.Condition = curMethod.conditions; 277 | statements.push(conditionalStatement); 278 | } 279 | } 280 | 281 | if (statement.Resource !== null && statement.Resource.length > 0) { 282 | statements.push(statement); 283 | } 284 | } 285 | 286 | return statements; 287 | }; 288 | 289 | return { 290 | constructor: AuthPolicy, 291 | 292 | /** 293 | * Adds an allow "*" statement to the policy. 294 | * 295 | * @method allowAllMethods 296 | */ 297 | allowAllMethods: function() { 298 | addMethod.call(this, "allow", "*", "*", null); 299 | }, 300 | 301 | /** 302 | * Adds a deny "*" statement to the policy. 303 | * 304 | * @method denyAllMethods 305 | */ 306 | denyAllMethods: function() { 307 | addMethod.call(this, "deny", "*", "*", null); 308 | }, 309 | 310 | /** 311 | * Adds an API Gateway method (Http verb + Resource path) to the list of allowed 312 | * methods for the policy 313 | * 314 | * @method allowMethod 315 | * @param {String} The HTTP verb for the method, this should ideally come from the 316 | * AuthPolicy.HttpVerb object to avoid spelling mistakes 317 | * @param {string} The resource path. For example "/pets" 318 | * @return {void} 319 | */ 320 | allowMethod: function(verb, resource) { 321 | addMethod.call(this, "allow", verb, resource, null); 322 | }, 323 | 324 | /** 325 | * Adds an API Gateway method (Http verb + Resource path) to the list of denied 326 | * methods for the policy 327 | * 328 | * @method denyMethod 329 | * @param {String} The HTTP verb for the method, this should ideally come from the 330 | * AuthPolicy.HttpVerb object to avoid spelling mistakes 331 | * @param {string} The resource path. For example "/pets" 332 | * @return {void} 333 | */ 334 | denyMethod : function(verb, resource) { 335 | addMethod.call(this, "deny", verb, resource, null); 336 | }, 337 | 338 | /** 339 | * Adds an API Gateway method (Http verb + Resource path) to the list of allowed 340 | * methods and includes a condition for the policy statement. More on AWS policy 341 | * conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition 342 | * 343 | * @method allowMethodWithConditions 344 | * @param {String} The HTTP verb for the method, this should ideally come from the 345 | * AuthPolicy.HttpVerb object to avoid spelling mistakes 346 | * @param {string} The resource path. For example "/pets" 347 | * @param {Object} The conditions object in the format specified by the AWS docs 348 | * @return {void} 349 | */ 350 | allowMethodWithConditions: function(verb, resource, conditions) { 351 | addMethod.call(this, "allow", verb, resource, conditions); 352 | }, 353 | 354 | /** 355 | * Adds an API Gateway method (Http verb + Resource path) to the list of denied 356 | * methods and includes a condition for the policy statement. More on AWS policy 357 | * conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition 358 | * 359 | * @method denyMethodWithConditions 360 | * @param {String} The HTTP verb for the method, this should ideally come from the 361 | * AuthPolicy.HttpVerb object to avoid spelling mistakes 362 | * @param {string} The resource path. For example "/pets" 363 | * @param {Object} The conditions object in the format specified by the AWS docs 364 | * @return {void} 365 | */ 366 | denyMethodWithConditions : function(verb, resource, conditions) { 367 | addMethod.call(this, "deny", verb, resource, conditions); 368 | }, 369 | 370 | /** 371 | * Generates the policy document based on the internal lists of allowed and denied 372 | * conditions. This will generate a policy with two main statements for the effect: 373 | * one statement for Allow and one statement for Deny. 374 | * Methods that includes conditions will have their own statement in the policy. 375 | * 376 | * @method build 377 | * @return {Object} The policy object that can be serialized to JSON. 378 | */ 379 | build: function() { 380 | if ((!this.allowMethods || this.allowMethods.length === 0) && 381 | (!this.denyMethods || this.denyMethods.length === 0)) { 382 | throw new Error("No statements defined for the policy"); 383 | } 384 | 385 | var policy = {}; 386 | policy.principalId = this.principalId; 387 | var doc = {}; 388 | doc.Version = this.version; 389 | doc.Statement = []; 390 | 391 | doc.Statement = doc.Statement.concat(getStatementsForEffect.call(this, "Allow", this.allowMethods)); 392 | doc.Statement = doc.Statement.concat(getStatementsForEffect.call(this, "Deny", this.denyMethods)); 393 | 394 | policy.policyDocument = doc; 395 | 396 | return policy; 397 | } 398 | }; 399 | 400 | })(); 401 | -------------------------------------------------------------------------------- /blueprints/python/api-gateway-authorizer-python.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at 5 | 6 | http://aws.amazon.com/apache2.0/ 7 | 8 | or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 9 | """ 10 | from __future__ import print_function 11 | 12 | import re 13 | 14 | 15 | def lambda_handler(event, context): 16 | """Do not print the auth token unless absolutely necessary """ 17 | #print("Client token: " + event['authorizationToken']) 18 | print("Method ARN: " + event['methodArn']) 19 | """validate the incoming token""" 20 | """and produce the principal user identifier associated with the token""" 21 | 22 | """this could be accomplished in a number of ways:""" 23 | """1. Call out to OAuth provider""" 24 | """2. Decode a JWT token inline""" 25 | """3. Lookup in a self-managed DB""" 26 | principalId = "user|a1b2c3d4" 27 | 28 | """you can send a 401 Unauthorized response to the client by failing like so:""" 29 | """raise Exception('Unauthorized')""" 30 | 31 | """if the token is valid, a policy must be generated which will allow or deny access to the client""" 32 | 33 | """if access is denied, the client will recieve a 403 Access Denied response""" 34 | """if access is allowed, API Gateway will proceed with the backend integration configured on the method that was called""" 35 | 36 | """this function must generate a policy that is associated with the recognized principal user identifier.""" 37 | """depending on your use case, you might store policies in a DB, or generate them on the fly""" 38 | 39 | """keep in mind, the policy is cached for 5 minutes by default (TTL is configurable in the authorizer)""" 40 | """and will apply to subsequent calls to any method/resource in the RestApi""" 41 | """made with the same token""" 42 | 43 | """the example policy below denies access to all resources in the RestApi""" 44 | tmp = event['methodArn'].split(':') 45 | apiGatewayArnTmp = tmp[5].split('/') 46 | awsAccountId = tmp[4] 47 | 48 | policy = AuthPolicy(principalId, awsAccountId) 49 | policy.restApiId = apiGatewayArnTmp[0] 50 | policy.region = tmp[3] 51 | policy.stage = apiGatewayArnTmp[1] 52 | policy.denyAllMethods() 53 | """policy.allowMethod(HttpVerb.GET, "/pets/*")""" 54 | 55 | # Finally, build the policy 56 | authResponse = policy.build() 57 | 58 | # new! -- add additional key-value pairs associated with the authenticated principal 59 | # these are made available by APIGW like so: $context.authorizer. 60 | # additional context is cached 61 | context = { 62 | 'key': 'value', # $context.authorizer.key -> value 63 | 'number' : 1, 64 | 'bool' : True 65 | } 66 | # context['arr'] = ['foo'] <- this is invalid, APIGW will not accept it 67 | # context['obj'] = {'foo':'bar'} <- also invalid 68 | 69 | authResponse['context'] = context 70 | 71 | return authResponse 72 | 73 | class HttpVerb: 74 | GET = "GET" 75 | POST = "POST" 76 | PUT = "PUT" 77 | PATCH = "PATCH" 78 | HEAD = "HEAD" 79 | DELETE = "DELETE" 80 | OPTIONS = "OPTIONS" 81 | ALL = "*" 82 | 83 | class AuthPolicy(object): 84 | awsAccountId = "" 85 | """The AWS account id the policy will be generated for. This is used to create the method ARNs.""" 86 | principalId = "" 87 | """The principal used for the policy, this should be a unique identifier for the end user.""" 88 | version = "2012-10-17" 89 | """The policy version used for the evaluation. This should always be '2012-10-17'""" 90 | pathRegex = "^[/.a-zA-Z0-9-\*]+$" 91 | """The regular expression used to validate resource paths for the policy""" 92 | 93 | """these are the internal lists of allowed and denied methods. These are lists 94 | of objects and each object has 2 properties: A resource ARN and a nullable 95 | conditions statement. 96 | the build method processes these lists and generates the approriate 97 | statements for the final policy""" 98 | allowMethods = [] 99 | denyMethods = [] 100 | 101 | 102 | restApiId = "<>" 103 | """ Replace the placeholder value with a default API Gateway API id to be used in the policy. 104 | Beware of using '*' since it will not simply mean any API Gateway API id, because stars will greedily expand over '/' or other separators. 105 | See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html for more details. """ 106 | 107 | region = "<>" 108 | """ Replace the placeholder value with a default region to be used in the policy. 109 | Beware of using '*' since it will not simply mean any region, because stars will greedily expand over '/' or other separators. 110 | See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html for more details. """ 111 | 112 | stage = "<>" 113 | """ Replace the placeholder value with a default stage to be used in the policy. 114 | Beware of using '*' since it will not simply mean any stage, because stars will greedily expand over '/' or other separators. 115 | See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html for more details. """ 116 | 117 | def __init__(self, principal, awsAccountId): 118 | self.awsAccountId = awsAccountId 119 | self.principalId = principal 120 | self.allowMethods = [] 121 | self.denyMethods = [] 122 | 123 | def _addMethod(self, effect, verb, resource, conditions): 124 | """Adds a method to the internal lists of allowed or denied methods. Each object in 125 | the internal list contains a resource ARN and a condition statement. The condition 126 | statement can be null.""" 127 | if verb != "*" and not hasattr(HttpVerb, verb): 128 | raise NameError("Invalid HTTP verb " + verb + ". Allowed verbs in HttpVerb class") 129 | resourcePattern = re.compile(self.pathRegex) 130 | if not resourcePattern.match(resource): 131 | raise NameError("Invalid resource path: " + resource + ". Path should match " + self.pathRegex) 132 | 133 | if resource[:1] == "/": 134 | resource = resource[1:] 135 | 136 | resourceArn = ("arn:aws:execute-api:" + 137 | self.region + ":" + 138 | self.awsAccountId + ":" + 139 | self.restApiId + "/" + 140 | self.stage + "/" + 141 | verb + "/" + 142 | resource) 143 | 144 | if effect.lower() == "allow": 145 | self.allowMethods.append({ 146 | 'resourceArn' : resourceArn, 147 | 'conditions' : conditions 148 | }) 149 | elif effect.lower() == "deny": 150 | self.denyMethods.append({ 151 | 'resourceArn' : resourceArn, 152 | 'conditions' : conditions 153 | }) 154 | 155 | def _getEmptyStatement(self, effect): 156 | """Returns an empty statement object prepopulated with the correct action and the 157 | desired effect.""" 158 | statement = { 159 | 'Action': 'execute-api:Invoke', 160 | 'Effect': effect[:1].upper() + effect[1:].lower(), 161 | 'Resource': [] 162 | } 163 | 164 | return statement 165 | 166 | def _getStatementForEffect(self, effect, methods): 167 | """This function loops over an array of objects containing a resourceArn and 168 | conditions statement and generates the array of statements for the policy.""" 169 | statements = [] 170 | 171 | if len(methods) > 0: 172 | statement = self._getEmptyStatement(effect) 173 | 174 | for curMethod in methods: 175 | if curMethod['conditions'] is None or len(curMethod['conditions']) == 0: 176 | statement['Resource'].append(curMethod['resourceArn']) 177 | else: 178 | conditionalStatement = self._getEmptyStatement(effect) 179 | conditionalStatement['Resource'].append(curMethod['resourceArn']) 180 | conditionalStatement['Condition'] = curMethod['conditions'] 181 | statements.append(conditionalStatement) 182 | 183 | statements.append(statement) 184 | 185 | return statements 186 | 187 | def allowAllMethods(self): 188 | """Adds a '*' allow to the policy to authorize access to all methods of an API""" 189 | self._addMethod("Allow", HttpVerb.ALL, "*", []) 190 | 191 | def denyAllMethods(self): 192 | """Adds a '*' allow to the policy to deny access to all methods of an API""" 193 | self._addMethod("Deny", HttpVerb.ALL, "*", []) 194 | 195 | def allowMethod(self, verb, resource): 196 | """Adds an API Gateway method (Http verb + Resource path) to the list of allowed 197 | methods for the policy""" 198 | self._addMethod("Allow", verb, resource, []) 199 | 200 | def denyMethod(self, verb, resource): 201 | """Adds an API Gateway method (Http verb + Resource path) to the list of denied 202 | methods for the policy""" 203 | self._addMethod("Deny", verb, resource, []) 204 | 205 | def allowMethodWithConditions(self, verb, resource, conditions): 206 | """Adds an API Gateway method (Http verb + Resource path) to the list of allowed 207 | methods and includes a condition for the policy statement. More on AWS policy 208 | conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition""" 209 | self._addMethod("Allow", verb, resource, conditions) 210 | 211 | def denyMethodWithConditions(self, verb, resource, conditions): 212 | """Adds an API Gateway method (Http verb + Resource path) to the list of denied 213 | methods and includes a condition for the policy statement. More on AWS policy 214 | conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition""" 215 | self._addMethod("Deny", verb, resource, conditions) 216 | 217 | def build(self): 218 | """Generates the policy document based on the internal lists of allowed and denied 219 | conditions. This will generate a policy with two main statements for the effect: 220 | one statement for Allow and one statement for Deny. 221 | Methods that includes conditions will have their own statement in the policy.""" 222 | if ((self.allowMethods is None or len(self.allowMethods) == 0) and 223 | (self.denyMethods is None or len(self.denyMethods) == 0)): 224 | raise NameError("No statements defined for the policy") 225 | 226 | policy = { 227 | 'principalId' : self.principalId, 228 | 'policyDocument' : { 229 | 'Version' : self.version, 230 | 'Statement' : [] 231 | } 232 | } 233 | 234 | policy['policyDocument']['Statement'].extend(self._getStatementForEffect("Allow", self.allowMethods)) 235 | policy['policyDocument']['Statement'].extend(self._getStatementForEffect("Deny", self.denyMethods)) 236 | 237 | return policy 238 | -------------------------------------------------------------------------------- /blueprints/rust/main.rs: -------------------------------------------------------------------------------- 1 | #![allow(dead_code)] 2 | #[macro_use] 3 | extern crate lambda_runtime as lambda; 4 | #[macro_use] 5 | extern crate serde_derive; 6 | #[macro_use] 7 | extern crate log; 8 | extern crate simple_logger; 9 | 10 | use lambda::error::HandlerError; 11 | 12 | use serde_json::json; 13 | use std::error::Error; 14 | 15 | static POLICY_VERSION: &str = "2012-10-17"; // override if necessary 16 | 17 | fn my_handler( 18 | event: APIGatewayCustomAuthorizerRequest, 19 | _ctx: lambda::Context, 20 | ) -> Result { 21 | info!("Client token: {}", event.authorization_token); 22 | info!("Method ARN: {}", event.method_arn); 23 | 24 | // validate the incoming token 25 | // and produce the principal user identifier associated with the token 26 | 27 | // this could be accomplished in a number of ways: 28 | // 1. Call out to OAuth provider 29 | // 2. Decode a JWT token inline 30 | // 3. Lookup in a self-managed DB 31 | let principal_id = "user|a1b2c3d4"; 32 | 33 | // you can send a 401 Unauthorized response to the client by failing like so: 34 | // Err(HandlerError{ msg: "Unauthorized".to_string(), backtrace: None }); 35 | 36 | // if the token is valid, a policy must be generated which will allow or deny access to the client 37 | 38 | // if access is denied, the client will recieve a 403 Access Denied response 39 | // if access is allowed, API Gateway will proceed with the backend integration configured on the method that was called 40 | 41 | // this function must generate a policy that is associated with the recognized principal user identifier. 42 | // depending on your use case, you might store policies in a DB, or generate them on the fly 43 | 44 | // keep in mind, the policy is cached for 5 minutes by default (TTL is configurable in the authorizer) 45 | // and will apply to subsequent calls to any method/resource in the RestApi 46 | // made with the same token 47 | 48 | //the example policy below denies access to all resources in the RestApi 49 | let tmp: Vec<&str> = event.method_arn.split(":").collect(); 50 | let api_gateway_arn_tmp: Vec<&str> = tmp[5].split("/").collect(); 51 | let aws_account_id = tmp[4]; 52 | let region = tmp[3]; 53 | let rest_api_id = api_gateway_arn_tmp[0]; 54 | let stage = api_gateway_arn_tmp[1]; 55 | 56 | let policy = APIGatewayPolicyBuilder::new(region, aws_account_id, rest_api_id, stage) 57 | .deny_all_methods() 58 | .build(); 59 | 60 | // new! -- add additional key-value pairs associated with the authenticated principal 61 | // these are made available by APIGW like so: $context.authorizer. 62 | // additional context is cached 63 | Ok(APIGatewayCustomAuthorizerResponse { 64 | principal_id: principal_id.to_string(), 65 | policy_document: policy, 66 | context: json!({ 67 | "stringKey": "stringval", 68 | "numberKey": 123, 69 | "booleanKey": true 70 | }), 71 | }) 72 | } 73 | 74 | fn main() -> Result<(), Box> { 75 | simple_logger::init_with_level(log::Level::Info)?; 76 | lambda!(my_handler); 77 | 78 | Ok(()) 79 | } 80 | 81 | #[derive(Serialize, Deserialize)] 82 | #[serde(rename_all = "camelCase")] 83 | struct APIGatewayCustomAuthorizerRequest { 84 | #[serde(rename = "type")] 85 | _type: String, 86 | authorization_token: String, 87 | method_arn: String, 88 | } 89 | 90 | #[derive(Serialize, Deserialize)] 91 | #[allow(non_snake_case)] 92 | struct APIGatewayCustomAuthorizerPolicy { 93 | Version: String, 94 | Statement: Vec, 95 | } 96 | 97 | #[derive(Serialize, Deserialize)] 98 | #[serde(rename_all = "camelCase")] 99 | struct APIGatewayCustomAuthorizerResponse { 100 | principal_id: String, 101 | policy_document: APIGatewayCustomAuthorizerPolicy, 102 | context: serde_json::Value, 103 | } 104 | 105 | #[derive(Serialize, Deserialize)] 106 | #[allow(non_snake_case)] 107 | struct IAMPolicyStatement { 108 | Action: Vec, 109 | Effect: Effect, 110 | Resource: Vec, 111 | } 112 | 113 | struct APIGatewayPolicyBuilder { 114 | region: String, 115 | aws_account_id: String, 116 | rest_api_id: String, 117 | stage: String, 118 | policy: APIGatewayCustomAuthorizerPolicy, 119 | } 120 | 121 | #[derive(Serialize, Deserialize)] 122 | enum Method { 123 | #[serde(rename = "GET")] 124 | Get, 125 | #[serde(rename = "POST")] 126 | Post, 127 | #[serde(rename = "*PUT")] 128 | Put, 129 | #[serde(rename = "DELETE")] 130 | Delete, 131 | #[serde(rename = "PATCH")] 132 | Patch, 133 | #[serde(rename = "HEAD")] 134 | Head, 135 | #[serde(rename = "OPTIONS")] 136 | Options, 137 | #[serde(rename = "*")] 138 | All, 139 | } 140 | 141 | #[derive(Serialize, Deserialize)] 142 | enum Effect { 143 | Allow, 144 | Deny, 145 | } 146 | 147 | impl APIGatewayPolicyBuilder { 148 | pub fn new( 149 | region: &str, 150 | account_id: &str, 151 | api_id: &str, 152 | stage: &str, 153 | ) -> APIGatewayPolicyBuilder { 154 | Self { 155 | region: region.to_string(), 156 | aws_account_id: account_id.to_string(), 157 | rest_api_id: api_id.to_string(), 158 | stage: stage.to_string(), 159 | policy: APIGatewayCustomAuthorizerPolicy { 160 | Version: POLICY_VERSION.to_string(), 161 | Statement: vec![], 162 | }, 163 | } 164 | } 165 | 166 | pub fn add_method>( 167 | mut self, 168 | effect: Effect, 169 | method: Method, 170 | resource: T, 171 | ) -> Self { 172 | let resource_arn = format!( 173 | "arn:aws:execute-api:{}:{}:{}/{}/{}/{}", 174 | &self.region, 175 | &self.aws_account_id, 176 | &self.rest_api_id, 177 | &self.stage, 178 | serde_json::to_string(&method).unwrap(), 179 | resource.into().trim_start_matches("/") 180 | ); 181 | 182 | let stmt = IAMPolicyStatement { 183 | Effect: effect, 184 | Action: vec!["execute-api:Invoke".to_string()], 185 | Resource: vec![resource_arn], 186 | }; 187 | 188 | self.policy.Statement.push(stmt); 189 | self 190 | } 191 | 192 | pub fn allow_all_methods(self) -> Self { 193 | self.add_method(Effect::Allow, Method::All, "*") 194 | } 195 | 196 | pub fn deny_all_methods(self) -> Self { 197 | self.add_method(Effect::Deny, Method::All, "*") 198 | } 199 | 200 | pub fn allow_method(self, method: Method, resource: String) -> Self { 201 | self.add_method(Effect::Allow, method, resource) 202 | } 203 | 204 | pub fn deny_method(self, method: Method, resource: String) -> Self { 205 | self.add_method(Effect::Deny, method, resource) 206 | } 207 | 208 | // Creates and executes a new child thread. 209 | pub fn build(self) -> APIGatewayCustomAuthorizerPolicy { 210 | self.policy 211 | } 212 | } 213 | --------------------------------------------------------------------------------