{APIGateway}API Gateway Lambda オーソライザーを使用する




https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html

https://dev.classmethod.jp/articles/lambda-authorizer-toke-request/

https://qiita.com/favolabo/items/369631ca7696fad9307a

 

Lambda オーソライザーには 2 種類あります。

トークンベース の Lambda オーソライザー (TOKEN オーソライザー)
・リクエストパラメータベースの Lambda オーソライザー (REQUEST オーソライザー) 


シンプルなTOKEN オーソライザーをためす


-- 1. コマンド等のインストール

-- 1.1 aws cli version 2 インストール

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

aws --version

-- 1.2 jqインストール
sudo yum -y install jq

 

-- 2. IAMロール作成
vim role01.json

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

aws iam create-role \
--role-name role01 \
--assume-role-policy-document file://role01.json

-- 3. ポリシーをロールにアタッチ
aws iam attach-role-policy \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole \
--role-name role01


-- 4. Lambda関数作成(バックエンド用)

vim test01.js

console.log('Loading hello world function');
exports.handler = async (event) => {
    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    console.log("response: " + JSON.stringify(response))
    return response;
};

 

chmod 755 test01.js
zip test01.zip test01.js

aws lambda create-function \
--function-name func01 \
--zip-file fileb://test01.zip \
--handler test01.handler \
--runtime nodejs14.x \
--role arn:aws:iam::999999999999:role/role01

 

aws lambda list-functions | grep func01

aws lambda get-function --function-name func01


-- 5. Lambda関数作成(Lambdaオーソライザー用)


vim test02.js

 

exports.handler =  function(event, context, callback) {
    var token = event.authorizationToken;
    switch (token) {
        case 'allow':
            callback(null, generatePolicy('user', 'Allow', event.methodArn));
            break;
        case 'deny':
            callback(null, generatePolicy('user', 'Deny', event.methodArn));
            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
    };
    console.log("authResponse: " + JSON.stringify(authResponse))
    return authResponse;
}

 

chmod 755 test02.js
zip test02.zip test02.js

aws lambda create-function \
--function-name func02 \
--zip-file fileb://test02.zip \
--handler test02.handler \
--runtime nodejs14.x \
--role arn:aws:iam::999999999999:role/role01

 


aws lambda list-functions | grep func02

aws lambda get-function --function-name func02

 

-- 6. オーソライザー用Lambda関数のテスト

aws lambda invoke \
--function-name func02 \
--payload '{
  "authorizationToken": "allow",
  "methodArn": "hoge"
}' \
response.txt \
--cli-binary-format raw-in-base64-out

cat response.txt | jq -r .

 

aws lambda invoke \
--function-name func02 \
--payload '{
  "authorizationToken": "deny",
  "methodArn": "hoge"
}' \
response.txt \
--cli-binary-format raw-in-base64-out

cat response.txt | jq -r .

 

 

-- 7. API を作成する

aws apigateway create-rest-api \
--name api01 \
--description "api01" \
--endpoint-configuration '{"types": ["REGIONAL"]}'

aws apigateway get-rest-apis

aws apigateway get-rest-api \
--rest-api-id 1111111111


-- 8. オーソライザーを作成する

aws apigateway create-authorizer \
--rest-api-id 1111111111 \
--name auth01 \
--type TOKEN \
--auth-type custom \
--authorizer-uri arn:aws:apigateway:ap-northeast-1:lambda:path/2015-03-31/functions/arn:aws:lambda:ap-northeast-1:999999999999:function:func02/invocations \
--identity-source method.request.header.authorizationToken \
--authorizer-result-ttl-in-seconds 0


aws apigateway get-authorizers \
--rest-api-id 1111111111

aws apigateway get-authorizer \
--rest-api-id 1111111111 \
--authorizer-id 222222


-- 9. Lambda関数に権限を追加する

aws lambda add-permission \
--function-name func01 \
--statement-id apigw01 \
--action lambda:InvokeFunction \
--principal apigateway.amazonaws.com \
--source-arn "arn:aws:execute-api:ap-northeast-1:999999999999:1111111111/*/*/helloworld"


aws lambda get-policy \
--function-name func01 | jq -r .Policy  | jq .


aws lambda add-permission \
--function-name func02 \
--statement-id apigw02 \
--action lambda:InvokeFunction \
--principal apigateway.amazonaws.com \
--source-arn "arn:aws:execute-api:ap-northeast-1:999999999999:1111111111/authorizers/*"


aws lambda get-policy \
--function-name func02 | jq -r .Policy  | jq .

 

 

-- 10. オーソライザーをテストする

aws apigateway test-invoke-authorizer \
--rest-api-id 1111111111 \
--authorizer-id 222222 \
--headers '{"authorizationToken": "allow"}'

aws apigateway test-invoke-authorizer \
--rest-api-id 1111111111 \
--authorizer-id 222222 \
--headers '{"authorizationToken": "deny"}'

 


-- 11. API でリソースを作成する
aws apigateway get-resources \
--rest-api-id 1111111111

aws apigateway create-resource \
--rest-api-id 1111111111 \
--parent-id 3333333333 \
--path-part "helloworld"


-- 12. リソースに ANYメソッドを作成する

※authorization-typeとauthorizer-idにオーソライザーの値をセットする


aws apigateway get-method \
--rest-api-id 1111111111 \
--resource-id 444444 \
--http-method ANY

 

aws apigateway put-method \
--rest-api-id 1111111111 \
--resource-id 444444 \
--http-method ANY \
--authorization-type CUSTOM \
--authorizer-id 222222 \
--no-api-key-required \
--request-parameters {}

 

aws apigateway put-integration \
--rest-api-id 1111111111 \
--resource-id 444444 \
--http-method ANY \
--type AWS_PROXY \
--integration-http-method POST \
--content-handling CONVERT_TO_TEXT \
--uri "arn:aws:apigateway:ap-northeast-1:lambda:path/2015-03-31/functions/arn:aws:lambda:ap-northeast-1:999999999999:function:func01/invocations"

 


aws apigateway put-integration-response \
--rest-api-id 1111111111 \
--resource-id 444444 \
--http-method ANY \
--status-code 200 \
--response-templates '{"application/json": ""}'


aws apigateway put-method-response \
--rest-api-id 1111111111 \
--resource-id 444444 \
--http-method ANY \
--status-code 200 \
--response-models '{"application/json": "Empty"}'

 

 


-- 13. API をデプロイする


aws apigateway get-deployments \
--rest-api-id 1111111111

aws apigateway get-stages \
--rest-api-id 1111111111


aws apigateway create-deployment \
--rest-api-id 1111111111

aws apigateway create-stage \
--rest-api-id 1111111111 \
--stage-name stage01 \
--deployment-id 555555

 

 

-- 14. APIをテストする

 

curl -v -X POST \
-H 'content-type: application/json' \
'https://1111111111.execute-api.ap-northeast-1.amazonaws.com/stage01/helloworld'

curl -v -X POST \
-H 'content-type: application/json' \
-H 'authorizationToken: allow' \
'https://1111111111.execute-api.ap-northeast-1.amazonaws.com/stage01/helloworld'

curl -v -X POST \
-H 'content-type: application/json' \
-H 'authorizationToken: deny' \
'https://1111111111.execute-api.ap-northeast-1.amazonaws.com/stage01/helloworld'

 


-- 15. クリーンアップ

 


-- API削除

aws apigateway get-rest-apis

aws apigateway delete-rest-api \
--rest-api-id 1111111111

 


-- Lambda関数の削除(バックエンド用)

aws lambda get-function --function-name func01
aws lambda delete-function --function-name func01

-- Lambda関数の削除(Lambdaオーソライザー用)

aws lambda get-function --function-name func02
aws lambda delete-function --function-name func02

 

 

-- ロールの削除
aws iam list-roles | grep role01

aws iam detach-role-policy \
--role-name role01 \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

aws iam delete-role --role-name role01