教學課程:在 Azure App Service 中對使用者進行端對端驗證和授權Tutorial: Authenticate and authorize users end-to-end in Azure App Service

Azure App Service 可提供可高度擴充、自我修復的 Web 主控服務。Azure App Service provides a highly scalable, self-patching web hosting service. 此外,App Service 具有使用者驗證和授權的內建支援。In addition, App Service has built-in support for user authentication and authorization. 本教學課程說明如何使用 App Service 驗證和授權來保護您的應用程式。This tutorial shows how to secure your apps with App Service authentication and authorization. 其使用 ASP.NET Core 應用程式,並搭配作為範例的 Angular.js 前端。It uses a ASP.NET Core app with an Angular.js front end as an example. App Service 驗證和授權支援所有語言執行階段,且您可以透過本教學課程了解如何將其套用至您偏好的語言。App Service authentication and authorization support all language runtimes, and you can learn how to apply it to your preferred language by following the tutorial.

Azure App Service 使用 Linux 作業系統提供可高度擴充、自我修復的 Web 主機服務。Azure App Service provides a highly scalable, self-patching web hosting service using the Linux operating system. 此外,App Service 具有使用者驗證和授權的內建支援。In addition, App Service has built-in support for user authentication and authorization. 本教學課程說明如何使用 App Service 驗證和授權來保護您的應用程式。This tutorial shows how to secure your apps with App Service authentication and authorization. 其使用 ASP.NET Core 應用程式,並搭配作為範例的 Angular.js 前端。It uses an ASP.NET Core app with an Angular.js front end as an example. App Service 驗證和授權支援所有語言執行階段,且您可以透過本教學課程了解如何將其套用至您偏好的語言。App Service authentication and authorization support all language runtimes, and you can learn how to apply it to your preferred language by following the tutorial.

簡單驗證和授權

此外也會說明如何藉由代表已驗證的使用者存取受保護的後端 API (從伺服器程式碼從瀏覽器程式碼),來保護多層式應用程式。It also shows you how to secure a multi-tiered app, by accessing a secured back-end API on behalf of the authenticated user, both from server code and from browser code.

進階驗證和授權

這些只是 App Service 中可能出現的部分驗證和授權案例。These are only some of the possible authentication and authorization scenarios in App Service.

以下更完整地列出您在本教學課程中可了解的事項:Here's a more comprehensive list of things you learn in the tutorial:

  • 啟用內建驗證和授權Enable built-in authentication and authorization
  • 防止應用程式接受未經驗證的要求Secure apps against unauthenticated requests
  • 以 Azure Active Directory 作為身分識別提供者Use Azure Active Directory as the identity provider
  • 代表已登入的使用者存取遠端應用程式Access a remote app on behalf of the signed-in user
  • 使用權杖驗證保護服務對服務呼叫Secure service-to-service calls with token authentication
  • 從伺服器程式碼使用存取權杖Use access tokens from server code
  • 從用戶端 (瀏覽器) 程式碼使用存取權杖Use access tokens from client (browser) code

您可以在 macOS、Linux、Windows 上依照本教學課程中的步驟進行。You can follow the steps in this tutorial on macOS, Linux, Windows.

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin.

必要條件Prerequisites

若要完成本教學課程:To complete this tutorial:

建立本機 .NET Core 應用程式Create local .NET Core app

在此步驟中,您要設定本機的 .NET Core 專案。In this step, you set up the local .NET Core project. 您可以使用相同的專案來部署後端 API 應用程式和前端 Web 應用程式。You use the same project to deploy a back-end API app and a front-end web app.

複製及執行範例應用程式Clone and run the sample application

執行下列命令,以複製範例存放庫並加以執行。Run the following commands to clone the sample repository and run it.

git clone https://github.com/Azure-Samples/dotnet-core-api
cd dotnet-core-api
dotnet run

瀏覽至 http://localhost:5000,並嘗試新增、編輯和移除待辦事項項目。Navigate to http://localhost:5000 and try adding, editing, and removing todo items.

在本機執行的 ASP.NET Core API

如需隨時停止 ASP.NET Core,請在終端機上按下 Ctrl+CTo stop ASP.NET Core at any time, press Ctrl+C in the terminal.

將應用程式部署至 AzureDeploy apps to Azure

在此步驟中,您會將專案部署至兩個 App Service 應用程式。In this step, you deploy the project to two App Service apps. 一個是前端應用程式,另一個是後端應用程式。One is the front-end app and the other is the back-end app.

設定部署使用者Configure a deployment user

FTP 和本機 Git 可以透過使用「部署使用者」 部署到 Azure Web 應用程式。FTP and local Git can deploy to an Azure web app by using a deployment user. 部署使用者只需設定一次,就能供所有 Azure 部署使用。Once you configure your deployment user, you can use it for all your Azure deployments. 使用者名稱和密碼屬於帳戶等級部署,因此與 Azure 訂用帳戶認證不同。Your account-level deployment username and password are different from your Azure subscription credentials.

若要設定部署使用者,請在 Azure Cloud Shell 中執行 az webapp deployment user set 命令。To configure the deployment user, run the az webapp deployment user set command in Azure Cloud Shell. 以部署使用者的使用者名稱和密碼取代 <username> 和 <password>。Replace <username> and <password> with a deployment user username and password.

  • 使用者名稱在 Azure 服務及本機 Git 推送中都必須是唯一的,且不能包含 ‘@’ 符號。The username must be unique within Azure, and for local Git pushes, must not contain the ‘@’ symbol.
  • 密碼長度必須至少為 8 個字元,包含下列三個元素其中兩個:字母、數字及符號。The password must be at least eight characters long, with two of the following three elements: letters, numbers, and symbols.
az webapp deployment user set --user-name <username> --password <password>

JSON 輸出會將密碼顯示為 nullThe JSON output shows the password as null. 如果您收到 'Conflict'. Details: 409 錯誤,請變更使用者名稱。If you get a 'Conflict'. Details: 409 error, change the username. 如果您收到 'Bad Request'. Details: 400 錯誤,請使用更強的密碼。If you get a 'Bad Request'. Details: 400 error, use a stronger password.

將使用者名稱和密碼記錄下來,在部署 Web 應用程式時還會用到。Record your username and password to use to deploy your web apps.

建立 Azure 資源Create Azure resources

在 Cloud Shell 中執行下列命令,以建立兩個 Windows Web 應用程式。In the Cloud Shell, run the following commands to create two Windows web apps. 以兩個全域唯一的應用程式名稱取代 <front-end-app-name><back-end-app-name> (有效的字元為 a-z0-9-)。Replace <front-end-app-name> and <back-end-app-name> with two globally unique app names (valid characters are a-z, 0-9, and -). 如需各個命令的詳細資訊,請參閱 Azure App Service 中具有 CORS 支援的 RESTful APIFor more information on each command, see RESTful API with CORS in Azure App Service.

az group create --name myAuthResourceGroup --location "West Europe"
az appservice plan create --name myAuthAppServicePlan --resource-group myAuthResourceGroup --sku FREE
az webapp create --resource-group myAuthResourceGroup --plan myAuthAppServicePlan --name <front-end-app-name> --deployment-local-git --query deploymentLocalGitUrl
az webapp create --resource-group myAuthResourceGroup --plan myAuthAppServicePlan --name <back-end-app-name> --deployment-local-git --query deploymentLocalGitUrl

在 Cloud Shell 中執行下列命令,以建立兩個 Web 應用程式。In the Cloud Shell, run the following commands to create two web apps. 以兩個全域唯一的應用程式名稱取代 <front-end-app-name><back-end-app-name> (有效的字元為 a-z0-9-)。Replace <front-end-app-name> and <back-end-app-name> with two globally unique app names (valid characters are a-z, 0-9, and -). 如需每個命令的詳細資訊,請參閱在 Azure App Service 中建立 .NET Core 應用程式For more information on each command, see Create a .NET Core app in Azure App Service.

az group create --name myAuthResourceGroup --location "West Europe"
az appservice plan create --name myAuthAppServicePlan --resource-group myAuthResourceGroup --sku FREE --is-linux
az webapp create --resource-group myAuthResourceGroup --plan myAuthAppServicePlan --name <front-end-app-name> --runtime "DOTNETCORE|3.1" --deployment-local-git --query deploymentLocalGitUrl
az webapp create --resource-group myAuthResourceGroup --plan myAuthAppServicePlan --name <back-end-app-name> --runtime "DOTNETCORE|3.1" --deployment-local-git --query deploymentLocalGitUrl

注意

儲存前端應用程式和後端應用程式之 Git 遠端的 URL,如 az webapp create 的輸出所顯示。Save the URLs of the Git remotes for your front-end app and back-end app, which are shown in the output from az webapp create.

從 Git 推送至 AzurePush to Azure from Git

回到 本機終端機視窗 ,執行下列 Git 命令,以部署至後端應用程式。Back in the local terminal window, run the following Git commands to deploy to the back-end app. 以您從 建立 Azure 資源儲存的 Git 遠端 URL 取代 <deploymentLocalGitUrl-of-back-end-app>Replace <deploymentLocalGitUrl-of-back-end-app> with the URL of the Git remote that you saved from Create Azure resources. 當 Git 認證管理員提示您輸入認證時,請務必輸入您的部署認證,而不是您用來登入 Azure 入口網站的認證。When prompted for credentials by Git Credential Manager, make sure that you enter your deployment credentials, not the credentials you use to sign in to the Azure portal.

git remote add backend <deploymentLocalGitUrl-of-back-end-app>
git push backend master

在本機終端機視窗中執行下列 Git 命令,以將相同的程式碼部署至前端應用程式。In the local terminal window, run the following Git commands to deploy the same code to the front-end app. 以您從 建立 Web 應用程式儲存的 Git 遠端 URL 取代 <deploymentLocalGitUrl-of-front-end-app>Replace <deploymentLocalGitUrl-of-front-end-app> with the URL of the Git remote that you saved from Create Azure resources.

git remote add frontend <deploymentLocalGitUrl-of-front-end-app>
git push frontend master

瀏覽至應用程式Browse to the apps

在瀏覽器中瀏覽至下列 URL,並確認兩個應用程式都在運作中。Navigate to the following URLs in a browser and see the two apps working.

http://<back-end-app-name>.azurewebsites.net
http://<front-end-app-name>.azurewebsites.net

瀏覽器視窗中 Azure App Service Rest API 範例的螢幕擷取畫面,其中顯示「待辦事項清單」應用程式。

注意

如果應用程式重新啟動,您可能會發現新的資料已被清除。If your app restarts, you may have noticed that new data has been erased. 這是刻意設計的行為,因為範例 ASP.NET Core 應用程式會使用記憶體內部資料庫。This behavior by design because the sample ASP.NET Core app uses an in-memory database.

從前端呼叫後端 APICall back-end API from front end

在此步驟中,您會使用前端應用程式的伺服器程式碼存取後端 API。In this step, you point the front-end app's server code to access the back-end API. 接著,您會啟用從前端到後端的驗證存取。Later, you enable authenticated access from the front end to the back end.

修改前端程式碼Modify front-end code

在本機存放庫中,開啟 Controllers/TodoController.csIn the local repository, open Controllers/TodoController.cs. TodoController 類別的開頭處加上以下幾行,並將 <back-end-app-name> 取代為後端應用程式的名稱:At the beginning of the TodoController class, add the following lines and replace <back-end-app-name> with the name of your back-end app:

private static readonly HttpClient _client = new HttpClient();
private static readonly string _remoteUrl = "https://<back-end-app-name>.azurewebsites.net";

尋找以 [HttpGet] 裝飾的方法,並將大括號內的程式碼取代為:Find the method that's decorated with [HttpGet] and replace the code inside the curly braces with:

var data = await _client.GetStringAsync($"{_remoteUrl}/api/Todo");
return JsonConvert.DeserializeObject<List<TodoItem>>(data);

第一行會對後端 API 應用程式發出 GET /api/Todo 呼叫。The first line makes a GET /api/Todo call to the back-end API app.

接著,尋找以 [HttpGet("{id}")] 裝飾的方法,並將大括號內的程式碼取代為:Next, find the method that's decorated with [HttpGet("{id}")] and replace the code inside the curly braces with:

var data = await _client.GetStringAsync($"{_remoteUrl}/api/Todo/{id}");
return Content(data, "application/json");

第一行會對後端 API 應用程式發出 GET /api/Todo/{id} 呼叫。The first line makes a GET /api/Todo/{id} call to the back-end API app.

接著,尋找以 [HttpPost] 裝飾的方法,並將大括號內的程式碼取代為:Next, find the method that's decorated with [HttpPost] and replace the code inside the curly braces with:

var response = await _client.PostAsJsonAsync($"{_remoteUrl}/api/Todo", todoItem);
var data = await response.Content.ReadAsStringAsync();
return Content(data, "application/json");

第一行會對後端 API 應用程式發出 POST /api/Todo 呼叫。The first line makes a POST /api/Todo call to the back-end API app.

接著,尋找以 [HttpPut("{id}")] 裝飾的方法,並將大括號內的程式碼取代為:Next, find the method that's decorated with [HttpPut("{id}")] and replace the code inside the curly braces with:

var res = await _client.PutAsJsonAsync($"{_remoteUrl}/api/Todo/{id}", todoItem);
return new NoContentResult();

第一行會對後端 API 應用程式發出 PUT /api/Todo/{id} 呼叫。The first line makes a PUT /api/Todo/{id} call to the back-end API app.

接著,尋找以 [HttpDelete("{id}")] 裝飾的方法,並將大括號內的程式碼取代為:Next, find the method that's decorated with [HttpDelete("{id}")] and replace the code inside the curly braces with:

var res = await _client.DeleteAsync($"{_remoteUrl}/api/Todo/{id}");
return new NoContentResult();

第一行會對後端 API 應用程式發出 DELETE /api/Todo/{id} 呼叫。The first line makes a DELETE /api/Todo/{id} call to the back-end API app.

儲存您的所有變更。Save all your changes. 在本機終端機視窗中,使用下列 Git 命令,將您的變更部署至前端應用程式:In the local terminal window, deploy your changes to the front-end app with the following Git commands:

git add .
git commit -m "call back-end API"
git push frontend master

檢查您的變更Check your changes

瀏覽至 http://<front-end-app-name>.azurewebsites.net 並新增一些項目,例如 from front end 1from front end 2Navigate to http://<front-end-app-name>.azurewebsites.net and add a few items, such as from front end 1 and from front end 2.

瀏覽至 http://<back-end-app-name>.azurewebsites.net,以查看從前端應用程式新增的項目。Navigate to http://<back-end-app-name>.azurewebsites.net to see the items added from the front-end app. 此外,請新增一些項目 (例如 from back end 1from back end 2),然後重新整理前端應用程式,以查看它是否反映這些變更。Also, add a few items, such as from back end 1 and from back end 2, then refresh the front-end app to see if it reflects the changes.

瀏覽器視窗中 Azure App Service Rest API 範例的螢幕擷取畫面,其中顯示「待辦事項清單」應用程式,其中包含從前端應用程式新增的項目。

設定驗證Configure auth

在此步驟中,您會為兩個應用程式啟用驗證和授權。In this step, you enable authentication and authorization for the two apps. 您也會設定前端應用程式,以產生可用來對後端應用程式發出已驗證呼叫的存取權杖。You also configure the front-end app to generate an access token that you can use to make authenticated calls to the back-end app.

您會以 Azure Active Directory 作為身分識別提供者。You use Azure Active Directory as the identity provider. 如需詳細資訊,請參閱為您的 App Service 應用程式設定 Azure Active Directory 驗證For more information, see Configure Azure Active Directory authentication for your App Services application.

為後端應用程式啟用驗證和授權Enable authentication and authorization for back-end app

Azure 入口網站功能表中,選取 [資源群組],或從任何頁面搜尋並選取 [資源群組]。In the Azure portal menu, select Resource groups or search for and select Resource groups from any page.

在 [資源群組] 中,尋找並選取資源群組。In Resource groups, find and select your resource group. 在 [概觀] 中,選取後端應用程式的管理頁面。In Overview, select your back-end app's management page.

[資源群組] 視窗的螢幕擷取畫面,其中顯示已選取範例資源群組和後端應用程式管理頁面的概觀。

在後端應用程式的左側功能表中,選取 [ 驗證],然後按一下 [ 新增識別提供者]。In your back-end app's left menu, select Authentication, and then click Add identity provider.

在 [ 新增識別提供者 ] 頁面中,選取 [ Microsoft 作為身分 識別提供者 ,以登入 microsoft 並 Azure AD 身分識別]。In the Add an identity provider page, select Microsoft as the Identity provider to sign in Microsoft and Azure AD identities.

針對 應用程式註冊 > 應用程式註冊類型,選取 [建立新的應用程式註冊]。For App registration > App registration type, select Create new app registration.

針對 應用程式註冊 > 支援的帳戶類型,選取 [目前的租使用者-單一租 使用者]。For App registration > Supported account types, select Current tenant-single tenant.

在 [ App Service authentication 設定] 區段中 ,將 [ 驗證] 設定為 [要求驗證] 和 [未經驗證的要求] 設定為 [ HTTP 302 找到重新導向:建議使用網站In the App Service authentication settings section, leave Authentication set to Require authentication and Unauthenticated requests set to HTTP 302 Found redirect: recommended for websites.

在 [ 新增識別提供者 ] 頁面的底部,按一下 [ 新增 ],為您的 web 應用程式啟用驗證。At the bottom of the Add an identity provider page, click Add to enable authentication for your web app.

後端應用程式左側功能表的螢幕擷取畫面,其中顯示已選取的驗證/授權,以及在右功能表中選取的設定。

[ 驗證 ] 頁面隨即開啟。The Authentication page opens. 將 Azure AD 應用程式的 用戶端識別碼 複製到記事本。Copy the Client ID of the Azure AD application to a notepad. 您後續會用到此值。You need this value later.

Azure Active Directory [設定] 視窗的螢幕擷取畫面,其中顯示 [Azure AD App],以及 [Azure AD 應用程式] 視窗,其中顯示要複製的用戶端識別碼。

如果您在這裡停止,您會有一個已受到 App Service 驗證和授權保護的獨立應用程式。If you stop here, you have a self-contained app that's already secured by the App Service authentication and authorization. 其餘各節將說明如何藉由讓已驗證的使用者從前端「流向」後端,以保護多應用程式解決方案。The remaining sections show you how to secure a multi-app solution by "flowing" the authenticated user from the front end to the back end.

為前端應用程式啟用驗證和授權Enable authentication and authorization for front-end app

請遵循前端應用程式的相同步驟,但略過最後一個步驟。Follow the same steps for the front-end app, but skip the last step. 您的前端應用程式不需要用戶端識別碼。You don't need the client ID for the front-end app.

如果您想要,瀏覽至 http://<front-end-app-name>.azurewebsites.netIf you like, navigate to http://<front-end-app-name>.azurewebsites.net. 它此時應會將您導向至安全的登入頁面。It should now direct you to a secured sign-in page. 登入之後,「您仍然無法從後端應用程式存取資料」,因為後端應用程式現在需要來自前端應用程式的 Azure Active Directory 登入。After you sign in, you still can't access the data from the back-end app, because the back-end app now requires Azure Active Directory sign-in from the front-end app. 需要執行三個步驟:You need to do three things:

  • 授與前端對後端的存取權Grant the front end access to the back end
  • 設定 App Service,以傳回可使用的權杖Configure App Service to return a usable token
  • 在程式碼中使用權杖Use the token in your code

提示

如果發生錯誤,且您重新設定應用程式的驗證/授權設定,權杖存放區中的權杖可能不會從新的設定重新產生。If you run into errors and reconfigure your app's authentication/authorization settings, the tokens in the token store may not be regenerated from the new settings. 為了確保您的權杖會重新產生,您必須先登出應用程式,然後再重新登入。To make sure your tokens are regenerated, you need to sign out and sign back in to your app. 您可以透過簡單的方式完成此動作,即以私用模式使用瀏覽器,並在變更應用程式中的設定後關閉,再以私用模式重新開啟瀏覽器。An easy way to do it is to use your browser in private mode, and close and reopen the browser in private mode after changing the settings in your apps.

授與前端應用程式對後端的存取權Grant front-end app access to back end

現在,您已為這兩個應用程式啟用驗證和授權,兩者皆受到 AD 應用程式的支援。Now that you've enabled authentication and authorization to both of your apps, each of them is backed by an AD application. 在此步驟中,您會為前端應用程式提供代表使用者存取後端的權限。In this step, you give the front-end app permissions to access the back end on the user's behalf. (技術上,您會為前端的 AD 應用程式 提供代表使用者存取後端 AD 應用程式 的權限。)(Technically, you give the front end's AD application the permissions to access the back end's AD application on the user's behalf.)

Azure 入口網站功能表中,選取 [Azure Active Directory],或從任何頁面搜尋並選取 [Azure Active Directory]。In the Azure portal menu, select Azure Active Directory or search for and select Azure Active Directory from any page.

選取 [應用程式註冊] > [擁有的應用程式] > [檢視此目錄中的所有應用程式]。Select App registrations > Owned applications > View all applications in this directory. 選取您的前端應用程式名稱,然後選取 [API 權限]。Select your front-end app name, then select API permissions.

[Microsoft - 應用程式註冊] 視窗的螢幕擷取畫面,其中包含所擁有的應用程式、前端應用程式名稱,以及所選取的 API 許可權。

選取 [新增權限],然後選取 [我的組織使用的 API] > <back-end-app-name>Select Add a permission, then select APIs my organization uses > <back-end-app-name>.

在後端應用程式的 [要求 API 權限] 頁面中,選取 [委派的權限]和 [user_impersonation],然後選取 [新增權限]。In the Request API permissions page for the back-end app, select Delegated permissions and user_impersonation, then select Add permissions.

[要求 API 許可權] 頁面的螢幕擷取畫面,其中顯示已選取 [委派的許可權]、[user_impersonation] 和 [新增權限] 按鈕。

設定 App Service,以傳回可使用的存取權杖Configure App Service to return a usable access token

前端應用程式現在具有必要權限,能夠以登入使用者的身分存取後端應用程式。The front-end app now has the required permissions to access the back-end app as the signed-in user. 在此步驟中,您會設定 App Service 驗證和授權,讓自己取得可用來存取後端的存取權杖。In this step, you configure App Service authentication and authorization to give you a usable access token for accessing the back end. 此步驟中,您需要後端的用戶端識別碼,也就是您從為後端應用程式啟用驗證和授權中複製的識別碼。For this step, you need the back end's client ID, which you copied from Enable authentication and authorization for back-end app.

瀏覽至 Azure 資源總管並使用資源樹狀結構,找出您的前端 Web 應用程式。Navigate to Azure Resource Explorer and using the resource tree, locate your front-end web app.

現在,在資源樹狀結構中選取您的前端應用程式,以開啟 Azure 資源總管The Azure Resource Explorer is now opened with your front-end app selected in the resource tree. 在頁面頂端按一下 [讀取/寫入],以啟用 Azure 資源的編輯。At the top of the page, click Read/Write to enable editing of your Azure resources.

[Azure 資源總管] 頁面頂端 [唯讀] 和 [讀取/寫入] 按鈕的螢幕擷取畫面,並已選取 [讀取/寫入] 按鈕。

在左側瀏覽器中,向下切入至 [config] > [authsettings]。In the left browser, drill down to config > authsettings.

authsettings 檢視中,按一下 [編輯]。In the authsettings view, click Edit. 使用您複製的用戶端識別碼,將 additionalLoginParams 設為下列 JSON 字串。Set additionalLoginParams to the following JSON string, using the client ID you copied.

"additionalLoginParams": ["response_type=code id_token","resource=<back-end-client-id>"],

Authsettings 視圖中程式碼範例的螢幕擷取畫面,其中顯示 additionalLoginParams 字串,並包含用戶端識別碼的範例。

按一下 PUT 以儲存您的設定。Save your settings by clicking PUT.

您的應用程式已完成設定。Your apps are now configured. 前端現在已可使用適當的存取權杖存取後端。The front end is now ready to access the back end with a proper access token.

如需如何為其他提供者設定存取權杖的相關資訊,請參閱重新整理識別提供者權杖For information on how to configure the access token for other providers, see Refresh identity provider tokens.

從伺服器程式碼安全地呼叫 APICall API securely from server code

在此步驟中,您會啟用您先前修改的伺服器程式碼,對後端 API 發出已驗證的呼叫。In this step, you enable your previously modified server code to make authenticated calls to the back-end API.

您的前端應用程式現已具有必要的權限,且會將後端的用戶端識別碼新增至登入參數。Your front-end app now has the required permission and also adds the back end's client ID to the login parameters. 因此,它可以取得對後端應用程式進行驗證的存取權杖。Therefore, it can obtain an access token for authentication with the back-end app. App Service 會藉由在每個已驗證的要求中插入 X-MS-TOKEN-AAD-ACCESS-TOKEN 標頭將此權杖提供給您的伺服器程式碼 (請參閱擷取應用程式程式碼中的權杖)。App Service supplies this token to your server code by injecting a X-MS-TOKEN-AAD-ACCESS-TOKEN header to each authenticated request (see Retrieve tokens in app code).

注意

在所有支援的語言中都會插入這些標頭。These headers are injected for all supported languages. 您可以使用個別語言的標準模式存取這些標頭。You access them using the standard pattern for each respective language.

在本機存放庫中,再次開啟 Controllers/TodoController.csIn the local repository, open Controllers/TodoController.cs again. TodoController(TodoContext context) 建構函式下,新增下列程式碼:Under the TodoController(TodoContext context) constructor, add the following code:

public override void OnActionExecuting(ActionExecutingContext context)
{
    base.OnActionExecuting(context);

    _client.DefaultRequestHeaders.Accept.Clear();
    _client.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", Request.Headers["X-MS-TOKEN-AAD-ACCESS-TOKEN"]);
}

此程式碼會將標準 HTTP 標頭 Authorization: Bearer <access-token> 新增至所有遠端 API 呼叫。This code adds the standard HTTP header Authorization: Bearer <access-token> to all remote API calls. 在 ASP.NET Core MVC 要求執行管線中,OnActionExecuting 會在各自的動作之前執行,因此您的每個傳出 API 呼叫現在都會提供存取權杖。In the ASP.NET Core MVC request execution pipeline, OnActionExecuting executes just before the respective action does, so each of your outgoing API call now presents the access token.

儲存您的所有變更。Save all your changes. 在本機終端機視窗中,使用下列 Git 命令,將您的變更部署至前端應用程式:In the local terminal window, deploy your changes to the front-end app with the following Git commands:

git add .
git commit -m "add authorization header for server code"
git push frontend master

再次登入 https://<front-end-app-name>.azurewebsites.netSign in to https://<front-end-app-name>.azurewebsites.net again. 在 [使用者資料使用合約] 頁面上,按一下 [接受]。At the user data usage agreement page, click Accept.

現在,您應該能夠和之前一樣從後端應用程式建立、讀取、更新和刪除資料。You should now be able to create, read, update, and delete data from the back-end app as before. 唯一的差別在於,現在這兩個應用程式都受到 App Service 驗證和授權的保護,包括服務對服務呼叫。The only difference now is that both apps are now secured by App Service authentication and authorization, including the service-to-service calls.

恭喜!Congratulations! 您的伺服器程式碼現在已可代表已驗證的使用者存取後端資料。Your server code is now accessing the back-end data on behalf of the authenticated user.

從瀏覽器程式碼安全地呼叫 APICall API securely from browser code

在此步驟中,您會將前端 Angular.js 應用程式指向後端 API。In this step, you point the front-end Angular.js app to the back-end API. 如此,您即了解如何擷取存取權杖,並且用它對後端應用程式發出 API 呼叫。This way, you learn how to retrieve the access token and make API calls to the back-end app with it.

伺服器程式碼可存取要求標頭,而用戶端程式碼則可存取 GET /.auth/me 以取得相同的存取權杖 (請參閱擷取應用程式程式碼中的權杖)。While the server code has access to request headers, client code can access GET /.auth/me to get the same access tokens (see Retrieve tokens in app code).

提示

本節會使用標準 HTTP 方法來示範安全的 HTTP 呼叫。This section uses the standard HTTP methods to demonstrate the secure HTTP calls. 不過,您可以利用適用於 JavaScript 的 Microsoft Authentication Library 來簡化 Angular.js 應用程式模式。However, you can use Microsoft Authentication Library for JavaScript to help simplify the Angular.js application pattern.

設定 CORSConfigure CORS

在 Cloud Shell 中,使用 az webapp cors add 命令,對您的用戶端 URL 啟用 CORS。In the Cloud Shell, enable CORS to your client's URL by using the az webapp cors add command. 取代 <back-end-app-name><front-end-app-name> 預留位置。Replace the <back-end-app-name> and <front-end-app-name> placeholders.

az webapp cors add --resource-group myAuthResourceGroup --name <back-end-app-name> --allowed-origins 'https://<front-end-app-name>.azurewebsites.net'

此步驟與驗證和授權無關。This step is not related to authentication and authorization. 但您仍需加以執行,您的瀏覽器才會允許來自 Angular.js 應用程式的跨網域 API 呼叫。However, you need it so that your browser allows the cross-domain API calls from your Angular.js app. 如需詳細資訊,請參閱新增 CORS 功能For more information, see Add CORS functionality.

將 Angular.js 應用程式指向後端 APIPoint Angular.js app to back-end API

在本機存放庫中,開啟 wwwroot/index.html。In the local repository, open wwwroot/index.html.

在第 51 行中,將 apiEndpoint 變數設為後端應用程式的 HTTPS URL (https://<back-end-app-name>.azurewebsites.net)。In Line 51, set the apiEndpoint variable to the HTTPS URL of your back-end app (https://<back-end-app-name>.azurewebsites.net). 以您在 App Service 中的應用程式名稱取代 <back-end-app-name>Replace <back-end-app-name> with your app name in App Service.

在本機存放庫中開啟 wwwroot/app/scripts/todoListSvc.js,並確認所有 API 呼叫前面都加上了 apiEndpointIn the local repository, open wwwroot/app/scripts/todoListSvc.js and see that apiEndpoint is prepended to all the API calls. 您的 Angular.js 應用程式現在會呼叫後端 API。Your Angular.js app is now calling the back-end APIs.

將存取權杖新增至 API 呼叫Add access token to API calls

wwwroot/app/scripts/todoListSvc.js 中的 API 呼叫清單上方 (getItems : function(){ 行上方),將下列函式新增至清單中:In wwwroot/app/scripts/todoListSvc.js, above the list of API calls (above the line getItems : function(){), add the following function to the list:

setAuth: function (token) {
    $http.defaults.headers.common['Authorization'] = 'Bearer ' + token;
},

呼叫此函式可設定含有存取權杖的預設 Authorization 標頭。This function is called to set the default Authorization header with the access token. 您將在下一個步驟中加以呼叫。You call it in the next step.

在本機存放庫中開啟 wwwroot/app/scripts/app.js,並尋找下列程式碼:In the local repository, open wwwroot/app/scripts/app.js and find the following code:

$routeProvider.when("/Home", {
    controller: "todoListCtrl",
    templateUrl: "/App/Views/TodoList.html",
}).otherwise({ redirectTo: "/Home" });

將這一整個程式碼區塊取代為下列程式碼:Replace the entire code block with the following code:

$routeProvider.when("/Home", {
    controller: "todoListCtrl",
    templateUrl: "/App/Views/TodoList.html",
    resolve: {
        token: ['$http', 'todoListSvc', function ($http, todoListSvc) {
            return $http.get('/.auth/me').then(function (response) {
                todoListSvc.setAuth(response.data[0].access_token);
                return response.data[0].access_token;
            });
        }]
    },
}).otherwise({ redirectTo: "/Home" });

新的變更會新增呼叫 /.auth/me 和設定存取權杖的 resolve 對應。The new change adds the resolve mapping that calls /.auth/me and sets the access token. 它可確保您在具現化 todoListCtrl 控制器之前具有存取權杖。It makes sure you have the access token before instantiating the todoListCtrl controller. 如此,該控制器所發出的所有 API 呼叫都會包含權杖。That way all API calls by the controller includes the token.

部署更新和測試Deploy updates and test

儲存您的所有變更。Save all your changes. 在本機終端機視窗中,使用下列 Git 命令,將您的變更部署至前端應用程式:In the local terminal window, deploy your changes to the front-end app with the following Git commands:

git add .
git commit -m "add authorization header for Angular"
git push frontend master

再次瀏覽至 https://<front-end-app-name>.azurewebsites.netNavigate to https://<front-end-app-name>.azurewebsites.net again. 現在,您應該能夠直接在 Angular.js 應用程式中從後端應用程式建立、讀取、更新和刪除資料。You should now be able to create, read, update, and delete data from the back-end app, directly in the Angular.js app.

恭喜!Congratulations! 您的用戶端程式碼現在已可代表已驗證的使用者存取後端資料。Your client code is now accessing the back-end data on behalf of the authenticated user.

當存取權杖到期When access tokens expire

存取權杖會在一段時間後到期。Your access token expires after some time. 若要了解如何重新整理存取權杖,而不需要讓使用者向應用程式重新驗證,請參閱重新整理識別提供者權杖For information on how to refresh your access tokens without requiring users to reauthenticate with your app, see Refresh identity provider tokens.

清除資源Clean up resources

在前述步驟中,您在資源群組中建立了 Azure 資源。In the preceding steps, you created Azure resources in a resource group. 如果您在未來不需要這些資源,請在 Cloud Shell 中執行下列命令,刪除資源群組:If you don't expect to need these resources in the future, delete the resource group by running the following command in the Cloud Shell:

az group delete --name myAuthResourceGroup

此命令可能會花一分鐘執行。This command may take a minute to run.

後續步驟Next steps

您已了解如何︰What you learned:

  • 啟用內建驗證和授權Enable built-in authentication and authorization
  • 防止應用程式接受未經驗證的要求Secure apps against unauthenticated requests
  • 以 Azure Active Directory 作為身分識別提供者Use Azure Active Directory as the identity provider
  • 代表已登入的使用者存取遠端應用程式Access a remote app on behalf of the signed-in user
  • 使用權杖驗證保護服務對服務呼叫Secure service-to-service calls with token authentication
  • 從伺服器程式碼使用存取權杖Use access tokens from server code
  • 從用戶端 (瀏覽器) 程式碼使用存取權杖Use access tokens from client (browser) code

前往下一個教學課程,了解如何將自訂的 DNS 名稱對應至應用程式。Advance to the next tutorial to learn how to map a custom DNS name to your app.