Web サーバーの設定を変更出来ない時、(権限がないとか設定ファイルが難解な為)簡単なパスワード認証をつける方法です。
私は、Synology の NAS の nginx の設定が難解な為に、Basic 認証をつけることを諦めました。nginx を再起動する度に、複数の mustache ファイルから、nginx.conf が生成されるという仕組みでした。
次のページを参考にしました。
[JavaScript] 簡単にパスワード認証(のようなもの)を作る
JavaScriptで文字列のハッシュ値を取得する
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8" />
<title>Simple Login</title>
</head>
<body>
<blockquote>
<h2>Simple Login</h2>
</blockquote>
<hr />
<table>
<tr><td>
UserName:
</td><td>
<input id="user" type="passsword"></input>
</td></tr>
<tr><td>
Password:
</td><td>
<input id="pass" type="passsword"></input>
</td></tr>
<tr><td>
</td><th>
<button id="enter">OK</button>
</th></tr>
</table>
<hr />
<p>Apr/25/2021 AM 07:19</p>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="password_check.js"></script>
</body>
</html>
password_check.js
// ---------------------------------------------------------------
// password_check.js
//
// Apr/25/2021
//
// ---------------------------------------------------------------
jQuery(function()
{
jQuery("#enter").click(function ()
{
const key = jQuery("#user").val() + "_" + jQuery("#pass").val()
sha256_async(key).then(value_hash => {
console.log(key)
console.log(value_hash)
jQuery.ajax({
url: value_hash + ".html"
}).then(html => {
jQuery("body").html(html)
}).catch(() => {
alert("パスワード認証に失敗しました")
jQuery("#pass").val("")
})
})
})
jQuery("#pass").on("keydown", e => {
if(e.keyCode === 13)
{
jQuery("#enter").trigger("click")
}
})
})
// ---------------------------------------------------------------
async function sha256_async(text){
const uint8 = new TextEncoder().encode(text)
const digest = await crypto.subtle.digest('SHA-256', uint8)
return Array.from(new Uint8Array(digest)).map(v => v.toString(16).padStart(2,'0')).join('')
}
// ---------------------------------------------------------------
例えば、
UserName: good
Password: morning
と入れると、コンソールに、ハッシュが表示されます。
この時は、
7f48567474fc65934fa4f1e50c9c2fd8f8123a257433b9255104e71607a255cf.html
というファイルを作成して下さい。それが表示されます。
https でなくて、http でアクセスすると、次のエラーが出ます。
password_check.js:39 Uncaught (in promise) TypeError: Cannot read property 'digest' of undefined
at sha256_async (password_check.js:39)
at HTMLButtonElement.<anonymous> (password_check.js:12)
at HTMLButtonElement.dispatch (jquery-3.6.0.min.js:2)
at HTMLButtonElement.v.handle (jquery-3.6.0.min.js:2)