もふもふ技術部

IT技術系mofmofメディア

serverless framework 第5回 authorizer の作成

はじめに

記事についての

こちらの記事は連載企画の第5回です! 応用的な使い方として第2回で作成した Cognito による認証を利用して lambda 関数に authorizer を作成します。

記事一覧

  1. セットアップ&チュートリアル
  2. cognito を利用した認証機能の作成
  3. dynamodb を利用した CRUD の作成
  4. serverless-offline を利用したローカル環境の作成
  5. 応用的な使い方(cognito を利用した authorizer の作成) <-- 現在

内容

準備 & おさらい

  1. Cognito の用意
resources:
  Resources:
    CognitoUserPool:
      Type: AWS::Cognito::UserPool
      Properties:
        UserPoolName: ${self:app}-user-pool
        UsernameAttributes:
          - email
        AutoVerifiedAttributes:
          - email

    CognitoUserPoolClient:
      Type: AWS::Cognito::UserPoolClient
      Properties:
        ClientName: ${self:app}-user-pool-client
        UserPoolId:
          Ref: CognitoUserPool
        ExplicitAuthFlows:
          - ALLOW_USER_PASSWORD_AUTH
          - ALLOW_REFRESH_TOKEN_AUTH
  1. lambda 関数の用意

handler.js

module.exports.get = async (event) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      result: "success",
    }),
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Credentials": "true",
    },
  };
};

serverless.yml

functions:
  get:
    handler: handler.get
    events:
      - httpApi:
          path: /get
          method: get
  1. 一度確認
serverless deploy

また、ClientId を控えておいてください

  • lambda 関数の実行確認
curl [エンドポイント]/get

本編

authorizer の作成

providerに以下を追加

provider:
  ...
  httpApi:
    authorizers:
      MyJwtAuthorizer: #1
        type: jwt
        identitySource: $request.header.Authorization
        audience:
          - Ref: CognitoUserPoolClient #2
        issuerUrl:
          Fn::Join: #3
            - ""
            - - "https://cognito-idp."
              - "us-east-1"
              - ".amazonaws.com/"
              - Ref: CognitoUserPool

#1: 任意の authorizer 名を指定できる #2: Ref <Resource名> 定義されている特定の Resource から ID を取得することができる。今回は UserPoolClientId を取得している。 #3: Fn::Join 値を結合して利用することができる。Refのように参照して取得するものがあり場合 1 行で記述することができない場合に用いる

lambda 関数に authorizer を紐付け

functionsを以下を追加

functions:
  ...
  getAuth:
    handler: handler.get
    events:
      - httpApi:
          path: /getAuth
          method: get
          authorizer:
            name: MyJwtAuthorizer # #1で作成したauthrozier名を指定

再度デプロイをし、authorizer が動いていることを確認する

serverless deploy
curl [エンドポイント]/get
#=> {"result":"success"}
curl [エンドポイント]/getAuth
#=> {"message":"Unauthorized"}

accessToken により関数を実行

第 2 回の cognito の作成と同様の手順で accessToken を取得し、以下のコマンドを実行

curl -H 'Authorization: [accessToken]' [エンドポイント]/getAuth
#=> {"result":"success"}

以上で cognito を利用した authorizer の作成は終了です。

まとめ

authorizer の作成には結構時間がかかってしまいました。http と httpApi では作成方法が違うようで http の場合は色々と検索にかかるのに httpApi はなかなか出てきませんでした。結果、公式のドキュメントがわかりやすかったです笑。

追記

Ref や Fn については cloudformation のドキュメントの下の方に書いてあります!


参考

https://www.serverless.com/framework/docs/providers/aws/events/http-api https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html

会社の紹介

株式会社 mofmof では一緒に働いてくれるエンジニアを募集しています。 興味のある方は是非こちらのページよりお越しください! https://www.mof-mof.co.jp/ https://www.mof-mof.co.jp/recruit/