單頁 AD FS 使用的應用程式Single Page Application with AD FS

適用於: Windows Server Technical PreviewApplies To: Windows Server Technical Preview

本節提供驗證 AD FS 使用 ADAL 適用於 JavaScript 保護 AngularJS 指令單頁應用程式、 ASP.NET Web API 端與實作。This walkthrough provides instruction for authenticating against AD FS using ADAL for JavaScript securing an AngularJS based single page application, implemented with an ASP.NET Web API backend.

警告:僅供教育是您可以在此組建的範例。WARNING: The example that you can build here is for educational purposes only. 這些指示僅適用於可能公開所需項目模式的最簡單、最小實作。These instructions are for the simplest, most minimal implementation possible to expose the required elements of the model. 範例可能不會包含錯誤處理的一切和其他相關功能。The example may not include all aspects of error handling and other relate functionality.

概觀Overview

在此範例中,我們將建立單頁應用程式 client 位置將會驗證 AD FS 保護的存取權端 WebAPI 資源驗證流程。In this sample we will be creating an authentication flow where a single page application client will be authenticating against AD FS to secure access to the WebAPI resources on the backend. 以下是整體驗證流程Below is the overall authentication flow

AD FS 授權

時使用單頁應用程式時,使用者瀏覽至開始的位置,從開始網頁和一系列 JavaScript 檔案,並會載入 HTML 檢視。When using a single page application, the user navigates to a starting location, from where starting page and a collection of JavaScript files and HTML views are loaded. 您需要設定 Active Directory 驗證媒體櫃 (ADAL) 若要知道您的應用程式,也就是 AD FS 執行個體 client ID 的重要資訊,讓它可以直接驗證您 AD FS。You need to configure the Active Directory Authentication Library (ADAL) to know the critical information about your application, i.e. the AD FS instance, client ID, so that it can direct the authentication to your AD FS.

如果 ADAL 看到觸發程序進行驗證時,它會使用應用程式所提供的資訊,並會引導您 AD FS STS 驗證。If ADAL sees a trigger for authentication, it uses the information provided by the application and directs the authentication to your AD FS STS. AD FS 在公用 client 為登記完畢單頁應用程式會自動設定隱含授與流程。The single page application, which is registered as a public client in AD FS, is automatically configured for implicit grant flow. 要求授權會導致 ID 權杖透過 #fragment 傳回回應用程式。The authorization request results in an ID token that is returned back to the application via a #fragment. 進一步來電後端 WebAPI 將承載權杖標題存取 WebAPI 中執行此 ID 預付碼。Further calls to the backend WebAPI will carry this ID token as the bearer token in the header to gain access to the WebAPI.

開發方塊設定Setting up the development box

這個解說使用 Visual Studio 2015。This walk-through uses Visual Studio 2015. 專案使用 ADAL JS 媒體櫃。The project uses ADAL JS library. 若要深入了解 ADAL 請朗讀Active Directory 驗證庫.NET。To learn about ADAL please read Active Directory Authentication Library .NET.

設定環境Setting up the environment

適用於本節我們將會使用基本的安裝:For this walkthrough we will be using a basic setup of:

  1. AD FS 可裝載網域俠: 網域控制站DC: Domain controller for the domain in which AD FS will be hosted
  2. AD FS: AD FS 伺服器的網域AD FS Server: The AD FS Server for the domain
  3. 我們已安裝 Visual Studio,將會開發我們範例開發電腦: 電腦Development Machine: Machine where we have Visual Studio installed and will be developing our sample

您可以如果您想要使用只兩部電腦。You can, if you want, use only two machines. 另一個用於俠日 AD FS,另一個用於範例開發無障礙。One for DC/AD FS and the other for developing the sample.

如何設定的網域控制站和 AD FS 超出範圍的這篇文章。How to setup the domain controller and AD FS is beyond the scope of this article. 適用於其他部署的資訊查看:For additional deployment information see:

複製或下載這個存放庫Clone or download this repository

我們會使用 Azure AD 整合 AngularJS 單頁應用程式與它修改建立的範例應用程式,改為使用 AD FS 保護端資源。We will be using the sample application created for integrating Azure AD into an AngularJS single page app and modifying it to instead secure the backend resource by using AD FS.

從命令列或殼層:From your shell or command line:

git clone https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp.git

程式碼About the Code

包含驗證邏輯金鑰檔案如下所示:The key files containing authentication logic are the following:

App.js -ADAL 模組相依性會將提供的應用程式的設定值 ADAL 用於 「 駕駛通訊協定 AAD 互動,表示的路徑不應該存取而先前的驗證。App.js - injects the ADAL module dependency, provides the app configuration values used by ADAL for driving protocol interactions with AAD and indicates whihc routes should not be accessed without previous authentication.

index.html -包含 adal.js 參考index.html - contains a reference to adal.js

HomeController.js-示範如何 ADAL 利用 login() 和 logOut() 的方法。HomeController.js- shows how to take advantage of the login() and logOut() methods in ADAL.

UserDataController.js的顯示快取 id_token 從解壓縮使用者資訊的方式。UserDataController.js - shows how to extract user information from the cached id_token.

Startup.Auth.cs -包含承載驗證使用 Active Directory 同盟服務 WebAPI 設定。Startup.Auth.cs - contains configuration for the WebAPI to use Active Directory Federation Service for bearer authentication.

AD FS 中登記公用 clientRegistering the public client in AD FS

在此範例中,若要聆聽,https://localhost:44326 設定 WebAPI 日。In the sample, the WebAPI is configured to listen at https://localhost:44326/. 應用程式群組存取 web 應用程式的網頁瀏覽器可用於設定隱含授與流程應用程式。The application group Web browser accessing a web application can be used for configuring implicit grant flow application.

  1. 打開 AD FS 管理主控台中,並按一下[新增應用程式群組Open the AD FS management console and click on Add Application Group. 的應用程式群組精靈輸入名稱的應用程式,描述並選取 [存取 web 應用程式的網頁瀏覽器從範本Client 伺服器應用程式區段,如下所示In the Add Application Group Wizard enter the name of the application, description and select the Web browser accessing a web application template from the Client-Server applications section as shown below
    建立新的應用程式群組

  2. 在下一個頁面上應用程式原生提供應用程式 client 識別碼,如下所示,重新導向 URIOn the next page Native application, provide the application client identifier and redirect URI as shown below
    建立新的應用程式群組

  3. 在下一個頁面上適用於存取控制原則離開權限讓任何人On the next page Apply Access Control Policy leave the permissions as Permit everyone

  4. 看起來類似下列摘要頁面The summary page should look similar to below
    建立新的應用程式群組

  5. 按一下下一步以完成的應用程式群組,並關閉精靈。Click on Next to complete the addition of the application group and close the wizard.

修改範例Modifying the sample

設定 ADAL JSConfigure ADAL JS

開放app.js檔案,然後變更adalProvider.init來定義:Open the app.js file and change the adalProvider.init definition to:

adalProvider.init(
    {
        instance: 'https://fs.contoso.com/', // your STS URL
        tenant: 'adfs',                      // this should be adfs
        clientId: 'https://localhost:44326/', // your client ID of the
        //cacheLocation: 'localStorage', // enable this for IE, as sessionStorage does not work for localhost.
    },
    $httpProvider
    );
設定Configuration 描述Description
執行個體instance 您 STS 的 URL,例如 https://fs.contoso.com/Your STS URL, e.g. https://fs.contoso.com/
承租人tenant 將其保留為 'adfs'Keep it as 'adfs'
clientIDclientID 這是您指定的時設定的應用程式單頁公用 client client IDThis is the client ID you specified while configuring the public client for your single page application

設定使用 AD FS WebAPIConfigure WebAPI to use AD FS

開放Startup.Auth.cs在此範例中的檔案,然後新增下列開頭︰Open the Startup.Auth.cs file in the sample and add the following at the beginning:

using System.IdentityModel.Tokens;

移除:remove:

            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Audience = ConfigurationManager.AppSettings["ida:Audience"],
Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
});

並加入:and add:

app.UseActiveDirectoryFederationServicesBearerAuthentication(
new ActiveDirectoryFederationServicesBearerAuthenticationOptions
{
MetadataEndpoint = ConfigurationManager.AppSettings["ida:AdfsMetadataEndpoint"],
TokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"],
ValidIssuer = ConfigurationManager.AppSettings["ida:Issuer"]
}
}
);
參數Parameter 描述Description
ValidAudienceValidAudience 這會設定為 '對象',將會針對檢查權杖中This configures the value of 'audience' that will be checked against in the token
ValidIssuerValidIssuer 這會設定為 ' 會針對權杖中檢查的發行者This configures the value of 'issuer that will be checked against in the token
MetadataEndpointMetadataEndpoint 這指向您 STS 中繼資料資訊This points to the metadata information of your STS

新增 AD FS 應用程式設定Add application configuration for AD FS

變更和 appsettings 如下:Change the appsettings as below:

<appSettings>
<add key="ida:Audience" value="https://localhost:44326/" />
<add key="ida:AdfsMetadataEndpoint" value="https://fs.contoso.com/federationmetadata/2007-06/federationmetadata.xml" />
<add key="ida:Issuer" value="https://fs.contoso.com/adfs" />
  </appSettings>

執行方案Running the solution

清除方案、 重建方案和執行。Clean the solution, rebuild the solution and run it. 如果您想要查看詳細的追蹤,上市 Fiddler 以及 HTTPS 解密。If you want to see detailed traces, launch Fiddler and enable HTTPS decryption.

瀏覽器將會載入] 選項,您將會看到以下畫面:The browser will load the SPA and you will be presented with the following screen:

登記 client

按一下 [登入。Click on Login. 會待辦清單會觸發驗證流程並 ADAL JS 會直接驗證,AD FSThe ToDo List will trigger the authentication flow and ADAL JS will direct the authentication to AD FS

登入

在 Fiddler,您可以看到傳回 # 片段中的 URL 的一部分預付碼。In Fiddler you can see the token being returned as part of the URL in the # fragment.

Fiddler

您可以立即來電後端的 API,若要新增的登入的使用者待辦清單項目:You will be able to now call the backend API to add ToDo List items for the logged-in user:

Fiddler