Complete a 3 Question Survey and Earn a re:Post Badge
Help improve AWS Support Official channel in re:Post and share your experience - complete a quick three-question survey to earn a re:Post badge!
캐싱이 활성화된 Lambda Authorizer를 사용하는 API Gateway 프록시 리소스가 HTTP 403 "User is not authorized to access this resource" 오류를 반환하는 이유는 무엇입니까?
캐싱이 활성화된 AWS Lambda Authorizer를 사용하는 Amazon API Gateway 프록시 리소스가 다음과 같은 HTTP 403 오류 메시지를 반환합니다. "User is not authorized to access this resource".
간략한 설명
참고: API Gateway는 다양한 이유로 403 User is not authorized to access this resource 오류를 반환할 수 있습니다. 이 문서에서는 캐싱만 활성화된 Lambda Authorizer를 사용하는 API Gateway 프록시 리소스와 관련된 403 오류를 다룹니다. 다른 유형의 403 오류의 문제 해결에 대한 자세한 내용은 API Gateway에서 발생하는 HTTP 403 오류 문제를 해결하려면 어떻게 해야 합니까?를 참조하십시오.
Lambda Authorizer의 출력은 AWS Identity and Access Management(IAM) 정책을 API Gateway에 반환합니다. IAM 정책에는 다음과 같은 형식의 명시적 API Gateway API "Resource" 요소가 포함되어 있습니다.
"arn:aws:execute-api:<region>:<account>:<API_id>/<stage>/<http-method>/[<resource-path-name>/[<child-resources-path>]"
Lambda Authorizer에서 권한 부여 캐싱이 활성화되면 반환된 IAM 정책이 캐싱됩니다. 그러면 캐싱된 IAM 정책이 캐시의 지정된 TTL(Time-To-Live) 기간 내에 이루어지는 모든 추가 API 요청에 적용됩니다.
API에 그리디 경로 변수가 {proxy+}인 프록시 리소스가 있는 경우 첫 번째 권한 부여가 성공합니다. 캐시의 TTL 기간 내에 다른 경로에 대한 추가 API 요청이 있으면 실패하고 다음 오류를 반환합니다.
"message": "User is not authorized to access this resource"
추가 요청이 실패하는 이유는 지정한 경로가 캐싱된 IAM 정책에 정의된 명시적 API Gateway API "Resource" 요소와 일치하지 않기 때문입니다.
문제를 해결하려면 Lambda Authorizer 함수의 코드를 수정하여 출력에 와일드카드(*/*) 리소스를 대신 반환하도록 하면 됩니다. 자세한 내용은 Lambda 작업의 리소스 및 조건을 참조하십시오.
참고: Authorizer 캐싱을 활성화하려면 Authorizer가 API Gateway의 모든 메서드에 적용할 수 있는 정책을 반환해야 합니다. 모든 리소스를 허용하려면 Lambda Authorizer 함수의 코드가 출력에 와일드카드(*/*) 리소스를 반환해야 합니다. 동일한 리소스 경로에서 동일한 요청을 두 번 수행하지 않는 한, 캐시 정책은 동일한 리소스 경로가 캐시될 것으로 예상합니다.
해결 방법
참고: 이 문서의 예시 Lambda Authorizer 함수 코드 조각을 사용 사례에 맞게 수정하십시오.
다음 예시 설정에서 Lambda 함수는 메서드의 Amazon 리소스 이름(ARN)( "event.methodArn")에서 API Gateway의 id 값을 추출합니다. 그런 다음 함수는 메서드 ARN의 경로를 API의 id 값 및 와일드카드(*/*)와 결합하여 와일드카드 "Resource" 변수를 정의합니다.
와일드카드 "Resource" 변수를 반환하는 토큰 기반 Lambda Authorizer 함수 코드의 예
exports.handler = function(event, context, callback) { var token = event.authorizationToken; var tmp = event.methodArn.split(':'); var apiGatewayArnTmp = tmp[5].split('/'); // Create wildcard resource var resource = tmp[0] + ":" + tmp[1] + ":" + tmp[2] + ":" + tmp[3] + ":" + tmp[4] + ":" + apiGatewayArnTmp[0] + '/*/*'; switch (token) { case 'allow': callback(null, generatePolicy('user', 'Allow', resource)); break; case 'deny': callback(null, generatePolicy('user', 'Deny', resource)); break; case 'unauthorized': callback("Unauthorized"); // Return a 401 Unauthorized response break; default: callback("Error: Invalid token"); // Return a 500 Invalid token response } }; // Help function to generate an IAM policy var generatePolicy = function(principalId, effect, resource) { var authResponse = {}; authResponse.principalId = principalId; if (effect && resource) { var policyDocument = {}; policyDocument.Version = '2012-10-17'; policyDocument.Statement = []; var statementOne = {}; statementOne.Action = 'execute-api:Invoke'; statementOne.Effect = effect; statementOne.Resource = resource; policyDocument.Statement[0] = statementOne; authResponse.policyDocument = policyDocument; } // Optional output with custom properties of the String, Number or Boolean type. authResponse.context = { "stringKey": "stringval", "numberKey": 123, "booleanKey": true }; return authResponse; }
와일드카드 "Resource" 변수를 반환하는 요청 파라미터 기반 Lambda Authorizer 함수 코드의 예
exports.handler = function(event, context, callback) { // Retrieve request parameters from the Lambda function input: var headers = event.headers; var queryStringParameters = event.queryStringParameters; var pathParameters = event.pathParameters; var stageVariables = event.stageVariables; // Parse the input for the parameter values var tmp = event.methodArn.split(':'); var apiGatewayArnTmp = tmp[5].split('/'); // Create wildcard resource var resource = tmp[0] + ":" + tmp[1] + ":" + tmp[2] + ":" + tmp[3] + ":" + tmp[4] + ":" + apiGatewayArnTmp[0] + '/*/*'; console.log("resource: " + resource); // if (apiGatewayArnTmp[3]) { // resource += apiGatewayArnTmp[3]; // } // Perform authorization to return the Allow policy for correct parameters and // the 'Unauthorized' error, otherwise. var authResponse = {}; var condition = {}; condition.IpAddress = {}; if (headers.headerauth1 === "headerValue1" && queryStringParameters.QueryString1 === "queryValue1" && stageVariables.StageVar1 === "stageValue1") { callback(null, generateAllow('me', resource)); } else { callback("Unauthorized"); } } // Help function to generate an IAM policy var generatePolicy = function(principalId, effect, resource) { // Required output: console.log("Resource in generatePolicy(): " + resource); var authResponse = {}; authResponse.principalId = principalId; if (effect && resource) { var policyDocument = {}; policyDocument.Version = '2012-10-17'; // default version policyDocument.Statement = []; var statementOne = {}; statementOne.Action = 'execute-api:Invoke'; // default action statementOne.Effect = effect; statementOne.Resource = resource; console.log("***Resource*** " + resource); policyDocument.Statement[0] = statementOne; console.log("***Generated Policy*** "); console.log(policyDocument); authResponse.policyDocument = policyDocument; } // Optional output with custom properties of the String, Number or Boolean type. authResponse.context = { "stringKey": "stringval", "numberKey": 123, "booleanKey": true }; return authResponse; } var generateAllow = function(principalId, resource) { return generatePolicy(principalId, 'Allow', resource); } var generateDeny = function(principalId, resource) { return generatePolicy(principalId, 'Deny', resource); }
Lambda 함수 코드를 편집하는 방법에 대한 자세한 내용은 .zip 파일 아카이브로 정의된 Lambda 함수 배포를 참조하십시오.
관련 정보

관련 콘텐츠
- 질문됨 일 년 전lg...
- 질문됨 3달 전lg...
- 질문됨 2년 전lg...
- 질문됨 일 년 전lg...