Azure Static Web Appsにおける認証について(HTML+JavaScript版)

Azure Static Web Appsにおける認証機能についてHTML+JavaScriptでできるだけ単純にログイン機能と現在の認証状況について表示するというところに絞ってサンプルを作ってみた。

まずは、参考にした公式ドキュメント。

docs.microsoft.com

docs.microsoft.com

で、大事なところはここ。

f:id:tomo_k:20210507183200p:plain

 

それぞれ、5つの承認プロバイダーがあるがリンクを張るだけでログイン機能が実装できるということ。

なので、例えば以下のようなHTMLを書くとログイン機能が作れる。

 

<a href="/.auth/login/aad">AAD Login</a><br />
<a href="/.auth/login/facebook">facebook Login</a><br />
<a href="/.auth/login/github">github Login</a><br />
<a href="/.auth/login/google">google Login</a><br />
<a href="/.auth/login/twitter">twitter Login</a><br />
<a href="/.auth/logout">Log out</a><br />

 一番下の行はログアウト機能である。

認証しているかどうかによって実際に見ることができるかどうかという実装はルート規則によって実現できますがここでは触れません。

docs.microsoft.com

次に、ユーザがログインしているかどうかを調べるには「/.auth/me」にGETアクセスすればよいとなっています。

 

ドキュメントにJavaScriptでのファンクション例が書かれていますのでそれをそのまま使うこととします。

 

 

async function getUserInfo() {
  const response = await fetch('/.auth/me');
  const payload = await response.json();
  const { clientPrincipal } = payload;
  return clientPrincipal;
}

 見ての通り、非同期処理になっていますので、さらに非同期関数で受けてclientPrincipalの内容を表示するようにしてみました。

 

 

<script>
async function getUserInfo() {
  const response = await fetch('/.auth/me');
  const payload = await response.json();
  const { clientPrincipal } = payload;
  return clientPrincipal;
}
async function get() {
var rejson = await getUserInfo();
console.log(rejson);
if (rejson == null) {
var new_ele = document.createElement("p");
new_ele.innerHTML = '認証されてません';
document.getElementById('add').appendChild(new_ele);
}
else 
{
var new_ele = document.createElement('p');
new_ele.innerHTML = rejson.identityProvider;
var new_ele2 = document.createElement('p');
new_ele2.innerHTML = rejson.userId;
var new_ele3 = document.createElement('p');
new_ele3.innerHTML = rejson.userDetails;
var new_ele4 = document.createElement('p');
new_ele4.innerHTML = rejson.userRoles;
document.getElementById('add').appendChild(new_ele);
document.getElementById('add').appendChild(new_ele2);
document.getElementById('add').appendChild(new_ele3);
document.getElementById('add').appendChild(new_ele4);
}

}

</script>

 で、HTMLに以下の要素をどこかに用意してあげればよいと思います。

 

 

<div id="add"></div>

 

それで、どこかでget()を実行してあげればよい。

全体のソースとしては以下を参照してください。

 

github.com

Azure Static Web Appsで動いているものは以下

brave-glacier-0efa2b900.azurestaticapps.net

実際のアプリケーションは/.auth/meから取られたJSONの情報をもとにユーザを識別してFunctionを動かしたりだとかという動きをするのだと思います。