0
0

CloudFront FunctionsでBasic認証を実装する

Posted at

CloudFront に Basic 認証を設定するとき、いつもは Lambda@Edge を使っていましたが、CloudFront Functions という機能を知り、こちらでも Basic 認証を実装できるので実際に試してみました。Basic 認証の username と password の設定には、CloudFront Functions と連携できる CloudFront KeyValueStore を使用しました。CloudFront KeyValueStore を利用すれば、username や password をコード内にハードコーディングする必要がないので、設定情報とコードを分離させることができ、柔軟に対応することができるようになります。

この記事では、CloudFront Functions の始め方、CloudFrontKeyValueStore とCloudFront Functions の紐づけ等は記載せず、CloudFront Functions での Basic 認証の実装の部分だけ説明します。

Basic 認証の実装

CloudFront Functions から CloudFront KeyValueStore の値を取り出すために、ヘルパーメソッドが用意されています。

このヘルパーメソッドを使用することで、簡単に CloudFront Functions から CloudFront KeyValueStore のキー値を取り出すことができます。CloudFront KeyValueStore のキー値を利用して Basic 認証の処理を実装したのが下記になります。

import cf from 'cloudfront';

const kvsId = '<KEY_VALUE_STORE_ID>';

// This fails if the key value store is not associated with the function
const kvsHandle = cf.kvs(kvsId)

async function handler(event) {
    const request = event.request;
    const headers = request.headers;
    const method = request.method;

    let username = '';
    let password = '';
    try {
        username = await kvsHandle.get('username');
        password = await kvsHandle.get('password');
    } catch (err) {
        console.log(`Kvs key lookup failed: ${err}`);
        throw err;
    }

    const authorization = `Basic ${(`${username}:${password}`).toString('base64')}`;  
    const origin = '*';

    // Preflight requests skip basic authentication
    if (method === "OPTIONS") {
        return {
            statusCode: 204,
            statusDescription: "NoContent",
            headers: {
                "access-control-allow-origin": { value: origin }
            }
        };
    }

    // Handling of authentication fail
    if (headers.authorization === undefined ||
        headers.authorization.value !== authorization) {
        return {
            statusCode: 401,
            statusDescription: 'Unauthorized',
            headers: {
                'www-authenticate': {value: 'Basic'}
            }
        };
    }

    return event.request;
}

関数のテスト

実装したプログラムは CloudFront Functions のテストタブからテストすることができます。何もテスト設定していない状態でテストすると、実行結果のステータスは 401 Unauthorized になります。Basic 認証を通過するために、ヘッダーに Authorization: Basic <username:password を base64 でエンコードした値>を設定します。username と password を base64 でエンコードした値を作成するためには、以下のようなコマンドで作成が可能です。
usernamepasswordは実際の値に置き換えてください。

$echo "Basic $(echo -n 'username:passoword' | base64)"

出力された文字列をヘッダーの値に入力してテストを実行します。正しく動けば実行結果のステータスは「成功」が表示されます。

0
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
0
0