驗證和授權 Static Web Apps

Azure Static Web Apps 提供簡化的驗證體驗,不需要任何額外設定,即可使用 GitHub 和 Microsoft Entra ID 進行驗證。

在本文中,了解預設行為、如何設定登入和登出、如何封鎖驗證提供者等。

您可以註冊自訂提供者,這會停用所有預先設定的提供者。

警告

由於 X (先前稱為 Twitter) API 原則變更,因此應用程式的預先設定提供者不提供支援。 如果您想要繼續搭配您的應用程式使用 X (先前稱為 Twitter) 驗證/授權,請更新應用程式設定以註冊自訂提供者

必要條件

請注意使用 Azure Static Web Apps 進行驗證和授權的下列預設值和資源。

預設值:

  • 任何使用者都可以向預先設定的提供者進行驗證
    • GitHub
    • Microsoft Entra ID
    • 若要限制驗證提供者,請使用自訂路由規則來封鎖存取
  • 登入之後,使用者屬於 anonymousauthenticated 角色。 如需角色的詳細資訊,請參閱管理角色

資源:

設定登入

Azure 靜態 Web Apps 會使用 /.auth 系統資料夾來提供授權相關 API 的存取權。 請建立適用於易記 URL 的路由規則 (部分機器翻譯),而不是直接向使用者公開 /.auth 資料夾下的任何路由。

使用下表來尋找提供者特定的路由。

授權提供者 登入路由
Microsoft Entra ID /.auth/login/aad
GitHub /.auth/login/github

例如,若要使用 GitHub 登入,您可以使用類似下列範例的 URL。

<a href="/.auth/login/github">Login</a>

如果您選擇支援多個提供者,請在您的網站上提供每個提供者特定的連結。 請使用路由規則 (部分機器翻譯),將預設提供者對應到易記的路由,例如 /login

{
  "route": "/login",
  "redirect": "/.auth/login/github"
}

設定登入後重新導向

您可以在 post_login_redirect_uri 查詢字串參數中提供完整 URL,讓使用者在登入後回到特定頁面。

<a href="/.auth/login/github?post_login_redirect_uri=https://zealous-water.azurestaticapps.net/success">Login</a>

You can also redirect unauthenticated users back to the referring page after they sign in. To add this redirect, create a response override rule that sets post_login_redirect_uri to .referrer, like in the following example.

{
  "responseOverrides": {
    "401": {
      "redirect": "/.auth/login/github?post_login_redirect_uri=.referrer",
      "statusCode": 302
    }
  }
}

設定登出

/.auth/logout 路由會讓使用者從網站登出。 您可以新增網站導覽的連結來讓使用者登出,如下列範例所示。

<a href="/.auth/logout">Log out</a>

請使用路由規則 (部分機器翻譯) 來對應易記的路由,例如 /logout

{
  "route": "/logout",
  "redirect": "/.auth/logout"
}

設定登出後重新導向

若要讓使用者在登出後回到特定頁面,請在 post_logout_redirect_uri 查詢字串參數中提供 URL。

封鎖驗證提供者

根據預設,會啟用所有驗證提供者,但您可以限制應用程式,使其不要使用某個提供者。 例如,您的應用程式可能只想要使用公開電子郵件地址的提供者

若要封鎖提供者,請建立路由規則 (部分機器翻譯),針對已封鎖的提供者特定路由的要求,傳回 404 狀態碼。 例如,若要限制使用 X (之前稱為 Twitter) 作為提供者,請新增下列路由規則。

{
  "route": "/.auth/login/twitter",
  "statusCode": 404
}

移除個人資料

當您以使用者身分對應用程式授與同意時,應用程式可存取您的電子郵件地址或使用者名稱,視識別提供者而定。 提供這項資訊之後,應用程式的擁有者可決定如何管理個人資料。

使用者必須聯絡個別 Web Apps 的管理員,才能從其系統中撤銷這項資訊。

若要從 Azure Static Web Apps 平台移除個人資料,並避免平台在未來的要求中提供此資訊,請使用下列 URL 提交要求:

https://identity.azurestaticapps.net/.auth/purge/<AUTHENTICATION_PROVIDER_NAME>

To prevent the platform from providing this information on future requests to individual apps, submit a request using the following URL:

https://<WEB_APP_DOMAIN_NAME>/.auth/purge/<AUTHENTICATION_PROVIDER_NAME>

If you're using Microsoft Entra ID, use aad as the value for the <AUTHENTICATION_PROVIDER_NAME> placeholder.

Tip

For information about general restrictions and limitations, see Quotas.

後續步驟