LoginSignup
2
0

More than 1 year has passed since last update.

【AWS IAM認可】署名バージョン4で署名する処理手順 for Nodejs

Posted at

前提

  • Cognitoが設定済みであること
  • API GatewayでAWS IAM認可が設定済みであること
  • ログインユーザーのロール(API実行可否)が設定済みであること
  • xxxのところは自環境に合わせて設定すること

下記をインストールする

  • @aws-amplify/ui-vue
  • aws-amplify
  • axios
  • vue

署名のサンプルソース

App.vue
<script setup>
import { Authenticator, translations } from "@aws-amplify/ui-vue";
import "@aws-amplify/ui-vue/styles.css";

import axios from 'axios'

import { Amplify, Auth, Signer, I18n } from 'aws-amplify';
// Cognito設定情報ファイル
import awsconfig from './aws-cognito-config';

import { ref } from 'vue';

Amplify.configure(awsconfig);
// ログイン画面の日本語化
I18n.putVocabularies(translations);
I18n.setLanguage('ja');

const msg = ref('');
const post = async () => {
  // AWS認証情報を取得
  const essentialCredentials = Auth.essentialCredentials(await Auth.currentCredentials());
  // リクエストパラメータ
  const params = {
    method: 'POST',
    url: 'https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/dev/user',
    data: JSON.stringify({
      'name': 'yamada'
    }),
  };

  const credentials = {
    secret_key: essentialCredentials.secretAccessKey,
    access_key: essentialCredentials.accessKeyId,
    session_token: essentialCredentials.sessionToken,
  };
  console.log(credentials);
  
  const serviceInfo = {
    region: awsconfig['aws_cognito_region'],
    service: 'execute-api'
  };

  // リクエストを署名バージョン4で署名
  const signer = Signer.sign(params, credentials, serviceInfo);
  console.log(signer);
  
  axios.post(signer.url, params.data,{
    headers: signer.headers
  }).then(res => {
    msg.value = res;
  }).catch(err => {
    msg.value = err;
    console.log(err);
  });

};
</script>

<template>
  <authenticator>
    <template v-slot="{ user, signOut }">
      <h1>Hello {{ user.username }}!</h1>
      <button @click="signOut">Sign Out</button>
    </template>
  </authenticator>
  <button @click="post">登録・更新</button>
  <div>{{ msg }}</div>
</template>
  • 一応、Cognito設定情報ファイルも残しておく
aws-cognito-config.js
const awsmobile = {
    "aws_project_region": "ap-northeast-1",
    "aws_cognito_identity_pool_id": "ap-northeast-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "aws_cognito_region": "ap-northeast-1",
    "aws_user_pools_id": "ap-northeast-1_xxxxxxxxx",
    "aws_user_pools_web_client_id": "xxxxxxxxxxxxxxxxxxxxxxxxx",
    "oauth": {
        "domain": "xxxxxx.auth.ap-northeast-1.amazoncognito.com",
        "scope": [
            "phone",
            "email",
            "openid",
            "profile",
            "aws.cognito.signin.user.admin"
        ],
        "redirectSignIn": "http://localhost:8080/",
        "redirectSignOut": "http://localhost:8080/",
        "responseType": "code"
    },
    "federationTarget": "COGNITO_USER_POOLS",
    "aws_cognito_username_attributes": [
    ],
    "aws_cognito_social_providers": [
        "GOOGLE"
    ],
    "aws_cognito_signup_attributes": [
    ],
    "aws_cognito_mfa_configuration": "OFF",
    "aws_cognito_mfa_types": [
        "SMS"
    ],
    "aws_cognito_password_protection_settings": {
        "passwordPolicyMinLength": 8,
        "passwordPolicyCharacters": []
    },
    "aws_cognito_verification_mechanisms": [
        "EMAIL"
    ]
};

// redirectが複数指定されていた場合、実行環境のURLより使用するredirectを判定
const { host } = window.location;

if (awsmobile.oauth.redirectSignIn.includes(',')) {
  const filterHost = url => new URL(url).host === host;
  awsmobile.oauth.redirectSignIn = awsmobile.oauth.redirectSignIn
    .split(',')
    .filter(filterHost)
    .shift();
  awsmobile.oauth.redirectSignOut = awsmobile.oauth.redirectSignOut
    .split(',')
    .filter(filterHost)
    .shift();
}

export default awsmobile;
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0