快速入門:ASP.NET 登入 Microsoft Entra 使用者的 Web 應用程式

歡迎! 這可能不是您預期的頁面。 當我們處理修正時,此鏈接應該會帶您前往正確的文章:

快速入門:使用 Microsoft 將登入新增至 ASP.NET Web 應用程式

我們為不便道歉,並感謝您的耐心,同時我們努力解決這個問題。

在本快速入門中,您會下載並執行程式碼範例,示範可透過 Microsoft Entra 帳戶登入使用者的 ASP.NET Web 應用程式。

步驟 1:在 Azure 入口網站 中設定您的應用程式

若要讓本快速入門中的程式碼範例正常運作,請輸入 https://localhost:44368/ [ 重新導向 URI]。

Already configured 您的應用程式是使用這個屬性設定的。

步驟 2:下載專案

使用 Visual Studio 2019 執行專案。

提示

若要避免 Windows 中路徑長度限制所造成的錯誤,建議您將封存盤或複製存放庫擷取到磁碟驅動器根附近的目錄。

步驟 3:您的應用程式已設定並準備好執行

我們已使用您 app 屬性的值來設定您的專案。

  1. 將.zip檔案解壓縮到接近根資料夾的本機資料夾。 例如,擷取至 C:\Azure-Samples

    建議您將封存解壓縮到磁碟驅動器根目錄附近的目錄,以避免 Windows 上路徑長度限制所造成的錯誤。

  2. 在 Visual Studio 中開啟方案(AppModelv2-WebApp-OpenID 連線-DotNet.sln)。

  3. 根據 Visual Studio 的版本,您可能需要以滑鼠右鍵按兩下專案 >AppModelv2-WebApp-OpenID 連線-DotNet,然後選取 [還原 NuGet 套件]。

  4. 選取 [檢視>其他 Windows> 封裝管理員 控制台],以開啟 封裝管理員 控制台。 接著,執行 Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r

注意

Enter_the_Supported_Account_Info_Here

其他相關資訊

本節提供登入使用者所需的程式碼概觀。 此概觀有助於瞭解程式代碼的運作方式、主要自變數是什麼,以及如何將登入新增至現有的 ASP.NET 應用程式。

範例的運作方式

Diagram of the interaction between the web browser, the web app, and the Microsoft identity platform in the sample app.

OWIN 中間件 NuGet 套件

您可以在搭配 OWIN 中間件套件的 ASP.NET 中使用 OpenID 連線,設定以 Cookie 為基礎的驗證管線。 您可以在 Visual Studio 內的 封裝管理員 控制台中執行下列命令,以安裝這些套件:

Install-Package Microsoft.Owin.Security.OpenIdConnect
Install-Package Microsoft.Owin.Security.Cookies
Install-Package Microsoft.Owin.Host.SystemWeb

OWIN 啟動類別

OWIN 中間件會使用 啟動類別 ,在裝載進程啟動時執行。 在本快速入門中 ,startup.cs 檔案位於根資料夾中。 下列程式代碼顯示本快速入門所使用的參數:

public void Configuration(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions());
    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            // Sets the client ID, authority, and redirect URI as obtained from Web.config
            ClientId = clientId,
            Authority = authority,
            RedirectUri = redirectUri,
            // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it's using the home page
            PostLogoutRedirectUri = redirectUri,
            Scope = OpenIdConnectScope.OpenIdProfile,
            // ResponseType is set to request the code id_token, which contains basic information about the signed-in user
            ResponseType = OpenIdConnectResponseType.CodeIdToken,
            // ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application
            // To only allow users from a single organization, set ValidateIssuer to true and the 'tenant' setting in Web.> config to the tenant name
            // To allow users from only a list of specific organizations, set ValidateIssuer to true and use the ValidIssuers parameter
            TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = false // Simplification (see note below)
            },
            // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to > the OnAuthenticationFailed method
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = OnAuthenticationFailed
            }
        }
    );
}
其中 描述
ClientId Azure 入口網站 中註冊之應用程式的應用程式標識碼。
Authority 用戶要驗證的安全性令牌服務 (STS) 端點。 它通常是 https://login.microsoftonline.com/{tenant}/v2.0 針對公用雲端。 在該 URL 中, {tenant} 是您租用戶的名稱、您的租用戶標識碼,或 common 參考通用端點。 (通用端點用於多租用戶應用程式。
RedirectUri 用戶針對 Microsoft 身分識別平台 進行驗證之後傳送的 URL。
PostLogoutRedirectUri 用戶註銷後傳送的 URL。
Scope 要求的範圍清單,以空格分隔。
ResponseType 來自驗證之回應的要求包含授權碼和標識元令牌。
TokenValidationParameters 令牌驗證的參數清單。 在此情況下, ValidateIssuer 會設定為 false ,表示它可以接受來自任何個人、公司或學校帳戶類型的登入。
Notifications 可以在訊息上 OpenIdConnect 執行的委派清單。

注意

設定 ValidateIssuer = false 是本快速入門的簡化。 在實際的應用程式中,驗證簽發者。 請參閱範例以瞭解如何執行此動作。

驗證挑戰

您可以藉由控制器中要求驗證挑戰來強制使用者登入:

public void SignIn()
{
    if (!Request.IsAuthenticated)
    {
        HttpContext.GetOwinContext().Authentication.Challenge(
            new AuthenticationProperties{ RedirectUri = "/" },
            OpenIdConnectAuthenticationDefaults.AuthenticationType);
    }
}

提示

使用此方法要求驗證挑戰是選擇性的。 當您想要從已驗證和未驗證的使用者存取檢視時,通常會使用它。 或者,您可以使用下一節所述的 方法來保護控制器。

保護控制器或控制器動作的屬性

您可以使用 屬性來保護控制器或控制器動作 [Authorize] 。 此屬性只允許已驗證的使用者存取控制器或動作,以存取控制器中的動作。 當未經驗證的用戶嘗試存取屬性裝飾 [Authorize] 的其中一個動作或控制器時,驗證挑戰就會自動發生。

說明與支援 

如果您需要協助、想要回報問題,或想要了解支援選項,請參閱 開發人員的說明和支援。

下一步

如需建置應用程式和新功能的完整逐步指南,包括本快速入門的完整說明,請參閱 ASP.NET 教學課程。