{APIGateway}Amazon Cognito ユーザープールをオーソライザーとして使用して REST API へのアクセスを制御する

 

https://blog.serverworks.co.jp/2021/03/02/201531
https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html

 

-- 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. Cognito構築


-- 2.1 ユーザプールの作成

 

aws cognito-idp create-user-pool \
--pool-name pool01 \
--policies '{
            "PasswordPolicy": {
                "MinimumLength": 8,
                "RequireUppercase": true,
                "RequireLowercase": true,
                "RequireNumbers": true,
                "RequireSymbols": true,
                "TemporaryPasswordValidityDays": 7
            }
        }' \
--auto-verified-attributes ' [
            "email"
        ]'


aws cognito-idp list-user-pools \
--max-results 20

aws cognito-idp describe-user-pool \
--user-pool-id ap-northeast-1_XXXXXXXXX

 

-- 2.2 アプリクライアントの作成

aws cognito-idp create-user-pool-client \
--user-pool-id ap-northeast-1_XXXXXXXXX \
--client-name clinet01 \
--no-generate-secret \
--refresh-token-validity 30 \
--access-token-validity 60 \
--id-token-validity 60 \
--token-validity-units ' {
            "AccessToken": "minutes",
            "IdToken": "minutes",
            "RefreshToken": "days"
        }' \
--explicit-auth-flows '[
            "ALLOW_ADMIN_USER_PASSWORD_AUTH",
            "ALLOW_CUSTOM_AUTH",
            "ALLOW_REFRESH_TOKEN_AUTH",
            "ALLOW_USER_SRP_AUTH"
        ]' \
--read-attributes '[
            "address",
            "birthdate",
            "email",
            "email_verified",
            "family_name",
            "gender",
            "given_name",
            "locale",
            "middle_name",
            "name",
            "nickname",
            "phone_number",
            "phone_number_verified",
            "picture",
            "preferred_username",
            "profile",
            "updated_at",
            "website",
            "zoneinfo"
        ]' \
--write-attributes '[
            "address",
            "birthdate",
            "email",
            "family_name",
            "gender",
            "given_name",
            "locale",
            "middle_name",
            "name",
            "nickname",
            "phone_number",
            "picture",
            "preferred_username",
            "profile",
            "updated_at",
            "website",
            "zoneinfo"
        ]' \
--prevent-user-existence-errors ENABLED

 

 

aws cognito-idp list-user-pool-clients \
--user-pool-id ap-northeast-1_XXXXXXXXX

aws cognito-idp describe-user-pool-client \
--user-pool-id ap-northeast-1_XXXXXXXXX \
--client-id 11111111111111111111111111

 

-- 2.3 ユーザの作成

aws cognito-idp admin-create-user \
--user-pool-id ap-northeast-1_XXXXXXXXX \
--username user01 \
--user-attributes '[
        {
            "Name": "email_verified",
            "Value": "true"
        },
        {
            "Name": "email",
            "Value": "hoge@example.com"
        }
    ]' 

 


aws cognito-idp list-users \
--user-pool-id ap-northeast-1_XXXXXXXXX

aws cognito-idp admin-get-user \
--user-pool-id ap-northeast-1_XXXXXXXXX \
--username user01

 

 


-- 2.4 ユーザにパスワードを設定


aws cognito-idp admin-get-user \
--user-pool-id ap-northeast-1_XXXXXXXXX \
--username user01


aws cognito-idp admin-set-user-password \
--user-pool-id ap-northeast-1_XXXXXXXXX \
--username user01 \
--password 'password' \
--permanent


aws cognito-idp admin-get-user \
--user-pool-id ap-northeast-1_XXXXXXXXX \
--username user01


-- 2.5 IDトークン取得

idtoken=$(aws cognito-idp admin-initiate-auth \
--user-pool-id ap-northeast-1_XXXXXXXXX \
--client-id 11111111111111111111111111 \
--auth-flow ADMIN_NO_SRP_AUTH \
--auth-parameters USERNAME=user01,PASSWORD='password' | jq -r .AuthenticationResult.IdToken)

echo $idtoken

 

 

-- 3. 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

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


-- 5. 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

 


-- 6. 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 2222222222

-- 7. 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:2222222222/*/*/helloworld"


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

 

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

aws apigateway create-authorizer \
--rest-api-id 2222222222 \
--name auth01 \
--type COGNITO_USER_POOLS \
--auth-type cognito_user_pools \
--provider-arns '[
                "arn:aws:cognito-idp:ap-northeast-1:999999999999:userpool/ap-northeast-1_XXXXXXXXX"
            ]' \
--identity-source method.request.header.Authorization \
--authorizer-result-ttl-in-seconds 0


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

aws apigateway get-authorizer \
--rest-api-id 2222222222 \
--authorizer-id 333333

 

 


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


aws apigateway test-invoke-authorizer \
--rest-api-id 2222222222 \
--authorizer-id 333333 \
--headers "{\"Authorization\":\"$idtoken\"}"


aws apigateway test-invoke-authorizer \
--rest-api-id 2222222222 \
--authorizer-id 333333 \
--headers "{\"Authorization\":\"hoge\"}"

 


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

aws apigateway create-resource \
--rest-api-id 2222222222 \
--parent-id 4444444444 \
--path-part "helloworld"


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

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


aws apigateway get-method \
--rest-api-id 2222222222 \
--resource-id 555555 \
--http-method ANY

 

aws apigateway put-method \
--rest-api-id 2222222222 \
--resource-id 555555 \
--http-method ANY \
--authorization-type COGNITO_USER_POOLS \
--authorizer-id 333333 \
--no-api-key-required \
--request-parameters {}

 

aws apigateway put-integration \
--rest-api-id 2222222222 \
--resource-id 555555 \
--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 2222222222 \
--resource-id 555555 \
--http-method ANY \
--status-code 200 \
--response-templates '{"application/json": ""}'


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

 

 


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


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

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


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

aws apigateway create-stage \
--rest-api-id 2222222222 \
--stage-name stage01 \
--deployment-id 666666

 

 

-- 13. APIをテストする

 

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

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

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

 

 

-- 14. クリーンアップ


-- API削除

aws apigateway get-rest-apis

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

 


-- Lambda関数の削除

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

 

 

-- ロールの削除
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


-- ユーザプールの削除

aws cognito-idp list-user-pools \
--max-results 20

aws cognito-idp describe-user-pool \
--user-pool-id ap-northeast-1_XXXXXXXXX


aws cognito-idp delete-user-pool \
--user-pool-id ap-northeast-1_XXXXXXXXX