Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ruby on Jets + Cognitoで認証付きAPIサーバを5分でデプロイする

Y_uuu
January 29, 2020

Ruby on Jets + Cognitoで認証付きAPIサーバを5分でデプロイする

2019/01/29 Fukuoka.rb #167 - 新年LT大会!

Y_uuu

January 29, 2020
Tweet

More Decks by Y_uuu

Other Decks in Programming

Transcript

  1. Jetsのインストール  アプリケーションを作成する ❯ ruby -v ruby 2.5.7p206 (2019-10-01 revision

    67816) [x86_64-darwin19] ❯ gem install jets Successfully installed jets-2.3.12 ❯ jets new fukuoka_rb_api --mode api --no-database Congrats You have successfully created a Jets project.
  2. jets generate scaffold  Scaffoldする ❯ cd fukuoka_rb_api ❯ jets

    generate scaffold Ev title:string url:string --no- migration
  3. DynamoDBに対応(コントローラ)  デフォルトRDB向けの実装になっているので修正 def create @ev = Ev.new #Ev.new(ev_params) if

    @ev.replace(ev_params) #ev.save render json: @ev, status: :created else render json: @ev.errors, status: :unprocessable_entity end end
  4. jets dynamodb:migrate  マイグレーションする ❯ docker run -p 8000:8000 amazon/dynamodb-local

    ❯ jets dynamodb:generate evs ❯ jets dynamodb:migrate dynamodb/migrate/*
  5. イベントを登録してみる  JSONをPOST ❯ curl -X POST -H "Content-Type: application/json"

    -d '{"ev": {"title":" Fukuoka.rb #167 - 新年LT⼤会︕", "url":"https://fukuokarb.connpass.com/event/162983/"}}' http://localhost:8888/evs {"id":"f97b50fd7d6330728ea3eea61ef6889a5035e2bb","title" :" Fukuoka.rb #167 - 新年LT⼤会︕ ","url":"https://fukuokarb.connpass.com/event/162983/","cre ated_at":"2020-01-25T19:41:00Z","updated_at":"2020-01- 25T19:41:00Z"}%
  6. Authorizerを作成  app/authorizers/main_authorizer.rbを作成 class MainAuthorizer < Jets::Authorizer::Base authorizer( name: ʻMyCognitoʼ,

    identity_source: ʻAuthorizationʼ, type: :cognito_user_pools, provider_arns: [ʻ(CognitoのARNを記載)'], ) end
  7. JWT Tokenを取得  aws-cliでcognitoにログイン ❯ aws cognito-idp initiate-auth --auth-flow USER_PASSWORD_AUTH

    --client-id 6nvis8bu0ehri8tsk6d3qkimef --auth-parameters USERNAME=(ユーザ名),PASSWORD=(パスワード) {"ChallengeParameters": {}, "AuthenticationResult": {”IdToken": ”xxxxx",
  8. イベントを登録してみる  JSONをPOST ❯ curl -X POST -H "Authorization: xxxxx"

    -H "Content-Type: application/json" -d '{"ev": {"title":" Fukuoka.rb #167 - 新年LT⼤ 会︕", "url":"https://fukuokarb.connpass.com/event/162983/"}}' https://z6kpk9boza.execute-api.ap-northeast- 1.amazonaws.com/prod/evs {"id":"1fdb21ed1bd9ca05b36b4f5a16fa7acda3ee077e","title":" Fukuoka.rb #167 - 新年LT⼤会︕ ","url":"https://fukuokarb.connpass.com/event/162983/","create d_at":"2020-01-25T20:46:45Z","updated_at":"2020-01- 25T20:46:45Z"}%
  9. イベントを取得してみる  JSONをGET ❯ curl -H "Authorization: xxxxx" https://z6kpk9boza.execute- api.ap-northeast-1.amazonaws.com/prod/evs

    [{"updated_at":"2020-01- 25T20:48:20Z","created_at":"2020-01- 25T20:48:20Z","id":"14ff588afe141e6121238214725d0e3db 51c9eca","url":"https://fukuokarb.connpass.com/event/1629 83/","title":" Fukuoka.rb #167 - 新年LT⼤会︕"}]%