0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CloudFront FunctionsのKeyValueStoreを使ってBasic認証

Posted at

CloudFront Functionsに追加されたKeyValueStoreのKeyにユーザー名、Valueにパスワードを保存しておいて複数のBasic認証ユーザーを作成して認証できるようにしたコードの共有です。

CloudFront Functionsの関数を作ったら「Associated KeyValueStore」で作成したKeyValueStoreを関連づけてから関数を下記のように書けばOKです。

import cf from 'cloudfront';

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

async function handler(event) {
    var request = event.request;
    var headers = request.headers;
    var unautherized = {
            statusCode: 401,
            statusDescription: "Unauthorized",
            headers: { "www-authenticate": { value: "Basic" } }
        };

    if ( typeof headers.authorization === "undefined" ){
        console.log("Authorization header is not found!")
        return unautherized
    } else {
        var val = headers.authorization.value;
        val = val.replace('Basic ','');
        var decoded = atob(val);
        var values = decoded.split(":");
        var username = values[0];
        var password = values[1];
        var correctPassword = "Not found"
        try {
            correctPassword = await kvsHandle.get(username);
        } catch (err) {
            console.log(`Key ${username}: ${err}`);
        }
        if ( "Not found" != correctPassword && correctPassword == password ){
            console.log("Authorized!")
            return request;
        }
    }
    console.log("Unauthorized!")
    return unautherized;
}

以上です。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?