存取 Azure Static Web Apps 中的使用者資訊

Azure Static Web Apps 透過 直接存取端點 API 函式 提供驗證相關的使用者資訊。

許多使用者介面高度依賴使用者驗證資料。 直接存取端點是公用程式 API,可公開使用者資訊,而不需要實作自訂函式。 除了便利性之外,直接存取端點不會受限於與無伺服器架構相關聯的冷啟動延遲。

用戶端主體資料

用戶端主體資料物件會將使用者可識別的資訊公開給您的應用程式。 用戶端主體物件中有下列屬性:

屬性 說明
identityProvider 識別提供者 的名稱
userId 使用者的 Azure Static Web Apps 特定唯一識別碼。
  • 此值在個別應用程式的基礎上是唯一的。 例如,相同的使用者在不同的靜態 Web Apps 資源上傳回不同的 userId 值。
  • 值會保存使用者存留期。 如果您刪除並新增相同的使用者回到應用程式,就會產生新的 userId
userDetails 使用者的使用者名稱或電子郵件地址。 有些提供者會傳回 使用者的電子郵件地址 ,而另一些提供者則會 傳送使用者控制碼
userRoles 使用者指派角色 陣列。
claims 自訂 驗證提供者 傳回的宣告陣列。 只能在直接存取端點中存取。

下列範例是範例用戶端主體物件:

{
  "identityProvider": "github",
  "userId": "d75b260a64504067bfc5b2905e3b8182",
  "userDetails": "username",
  "userRoles": ["anonymous", "authenticated"],
  "claims": [{
    "typ": "name",
    "val": "Azure Static Web Apps"
  }]
}

直接存取端點

您可以將要求傳送 GET 至路由, /.auth/me 並接收用戶端主體資料的直接存取權。 當您的檢視狀態依賴授權資料時,請使用此方法獲得最佳效能。

對於登入的使用者,回應會包含用戶端主體 JSON 物件。 未經驗證的使用者所提出的要求會傳回 null

使用擷 1 API,您可以使用下列語法來存取用戶端主體資料。

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

(async () => {
console.log(await getUserInfo());
})();

API 函式

透過 Azure Functions 後端在靜態 Web Apps 中提供的 API 函式可以存取與用戶端應用程式相同的使用者資訊,但陣列除外 claims 。 雖然 API 確實會收到使用者可識別的資訊,但它不會執行自己的檢查,以確認使用者是否已通過驗證,或是否符合必要的角色。 存取控制規則定義于 檔案中 staticwebapp.config.json

用戶端主體資料會傳遞至要求標頭中的 x-ms-client-principal API 函式。 用戶端主體資料會以 Base64 編碼的字串形式傳送, 其中包含序列化的 JSON 物件。

下列範例函式顯示如何讀取和傳回使用者資訊。

module.exports = async function (context, req) {
  const header = req.headers.get('x-ms-client-principal');
  const encoded = Buffer.from(header, 'base64');
  const decoded = encoded.toString('ascii');

  context.res = {
    body: {
      clientPrincipal: JSON.parse(decoded),
    },
  };
};

假設上述函式命名 user 為 ,您可以使用 擷取 1 瀏覽器 API,使用下列語法來存取 API 的回應。

async function getUser() {
  const response = await fetch('/api/user');
  const payload = await response.json();
  const { clientPrincipal } = payload;
  return clientPrincipal;
}

console.log(await getUser());

當使用者登入時,標頭 x-ms-client-principal 會透過靜態 Web Apps 邊緣節點新增至使用者資訊要求。

注意

x-ms-client-principalAPI 函式中可存取的標頭不包含 claims 陣列。

1 Internet Explorer 不支援擷取 API 和 await 運算子。

下一步