Share via


在 Azure Functions 中建立令牌發行開始事件的 REST API

本文說明如何在 Azure 入口網站 中使用 Azure Functions 建立具有令牌發行開始事件的 REST API。 您可以建立 Azure 函式應用程式和 HTTP 觸發程式函式,以傳回令牌的額外宣告。

必要條件

  • 對自定義驗證延伸模組概觀涵蓋的概念有基本瞭解。
  • 能夠建立 Azure Functions 的 Azure 訂用帳戶。 如果您沒有現有的 Azure 帳戶,請在建立帳戶時註冊免費試用或使用 Visual Studio 訂用帳戶權益。
  • Microsoft Entra ID 租使用者。 您可以使用客戶或員工租用戶來進行本操作指南。

本文說明如何使用 Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents NuGet 連結庫建立令牌發行開始事件的 REST API,並設定它以進行驗證。 您將在 Visual Studio 或 Visual Studio Code 中建立 HTTP 觸發程式函式、進行驗證設定,並將其部署至 Azure 入口網站,以便透過 Azure Functions 存取。

必要條件

  • 對自定義驗證延伸模組概觀涵蓋的概念有基本瞭解。
  • 能夠建立 Azure Functions 的 Azure 訂用帳戶。 如果您沒有現有的 Azure 帳戶,請在建立帳戶時註冊免費試用或使用 Visual Studio 訂用帳戶權益。
  • Microsoft Entra ID 租使用者。 您可以使用客戶或員工租用戶來進行本操作指南。
  • 下列其中一個 IDE 和組態:

注意

Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents NuGet 連結庫目前為預覽狀態。 本文中的步驟可能會變更。 如需實作令牌發行開始事件的正式運作實作,您可以使用 Azure 入口網站

建立 Azure 函式應用程式

在 Azure 入口網站 中,先建立 Azure 函式應用程式及其相關聯的資源,再繼續建立 HTTP 觸發程式函式。

  1. 至少以 Application 管理員 istrator 和 Authentication 管理員 istrator 身分登入 Azure 入口網站

  2. 從 Azure 入口網站功能表或 [首頁] 頁面,選取 [建立資源]

  3. 搜尋並選取 [函式應用程式 ],然後選取 [ 建立]。

  4. 在 [ 基本] 頁面上,使用下表中指定的設定來建立函式應用程式:

    設定 建議的值 描述
    訂用帳戶 您的訂用帳戶 將建立新函式應用程式的訂用帳戶。
    資源群組 myResourceGroup 選取現有的資源群組,或您要在其中建立函式應用程式的新資源群組名稱。
    函數應用程式名稱 全域唯一的名稱 識別新函式應用程式的名稱。 有效的字元是 a-z (不區分大小寫)、0-9-
    部署程式代碼或容器映像 代碼 發佈程式碼檔案或 Docker 容器的選項。 在本教學課程中,選取 [ 程序代碼]。
    執行階段堆疊 .NET 您慣用的程式設計語言。 在本教學課程中,選取 [.NET]。
    版本 6 (LTS) 進程內 .NET 運行時間的版本。 進程內表示您可以在入口網站中建立和修改函式,本指南建議使用此功能
    區域 慣用區域 選取的區域應靠近您或靠近函式能夠存取的其他服務。
    作業系統 Windows 系統會根據運行時間堆疊選取專案,為您預先選取作業系統。
    方案類型 使用量 (無伺服器) 定義如何將資源配置給函式應用程式的主控方案。
  5. 選取 [ 檢閱 + 建立 ] 以檢閱應用程式設定選取專案,然後選取 [ 建立]。 部署需要幾分鐘的時間。

  6. 部署之後,選取 [移至資源 ] 以檢視新的函式應用程式。

建立 HTTP 觸發程序函式

建立 Azure 函式應用程式之後,請在應用程式內建立 HTTP 觸發程式函式。 HTTP 觸發程式可讓您使用 HTTP 要求叫用函式,並由 Microsoft Entra 自定義驗證延伸模組參考。

  1. 在函式應用程式的 [概觀] 頁面中,選取 [式] 窗格,然後選取 [在 Azure 入口網站 中建立] 底下的 [建立函]。
  2. 在 [建立函式] 視窗中,將 [開發環境] 屬性保留入口網站中的 [開發]。 在 [範本] 底下,選取 [HTTP 觸發程式]。
  3. 在 [範本詳細數據] 底下,輸入 New Function 屬性的 CustomAuthenticationExtensionsAPI
  4. 針對 [ 授權層級],選取 [ 函式]。
  5. 選取 建立顯示如何選擇開發環境和範本的螢幕快照。

編輯函式

此程式代碼會讀取傳入的 JSON 物件,而 Microsoft Entra ID 會將 JSON 物件 傳送至您的 API。 在此範例中,它會讀取相互關聯標識符值。 然後,程式代碼會傳回自定義宣告的集合,包括您 Azure 函式的原始 CorrelationIdApiVersionDateOfBirth 以及 CustomRoles 傳回至 Microsoft Entra ID 的 。

  1. 從功能表的 [開發人員] 底下,選取 [程序代碼 + 測試]。

  2. 以下列代碼段取代整個程式碼,然後選取 [ 儲存]。

    #r "Newtonsoft.Json"
    using System.Net;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Primitives;
    using Newtonsoft.Json;
    public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");
        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
    
        // Read the correlation ID from the Microsoft Entra request    
        string correlationId = data?.data.authenticationContext.correlationId;
    
        // Claims to return to Microsoft Entra
        ResponseContent r = new ResponseContent();
        r.data.actions[0].claims.CorrelationId = correlationId;
        r.data.actions[0].claims.ApiVersion = "1.0.0";
        r.data.actions[0].claims.DateOfBirth = "01/01/2000";
        r.data.actions[0].claims.CustomRoles.Add("Writer");
        r.data.actions[0].claims.CustomRoles.Add("Editor");
        return new OkObjectResult(r);
    }
    public class ResponseContent{
        [JsonProperty("data")]
        public Data data { get; set; }
        public ResponseContent()
        {
            data = new Data();
        }
    }
    public class Data{
        [JsonProperty("@odata.type")]
        public string odatatype { get; set; }
        public List<Action> actions { get; set; }
        public Data()
        {
            odatatype = "microsoft.graph.onTokenIssuanceStartResponseData";
            actions = new List<Action>();
            actions.Add(new Action());
        }
    }
    public class Action{
        [JsonProperty("@odata.type")]
        public string odatatype { get; set; }
        public Claims claims { get; set; }
        public Action()
        {
            odatatype = "microsoft.graph.tokenIssuanceStart.provideClaimsForToken";
            claims = new Claims();
        }
    }
    public class Claims{
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string CorrelationId { get; set; }
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string DateOfBirth { get; set; }
        public string ApiVersion { get; set; }
        public List<string> CustomRoles { get; set; }
        public Claims()
        {
            CustomRoles = new List<string>();
        }
    }
    
  3. 從頂端功能表中,選取 [取得函式 URL],然後複製 URL 值。 設定自訂驗證延伸模組時,可以使用此函式URL。

建立及建置 Azure 函式應用程式

在此步驟中,您會使用 IDE 建立 HTTP 觸發程式函式 API、安裝必要的 NuGet 套件,並在範例程式代碼中複製。 您可以建置項目並執行 函式來擷取本機函式 URL。

建立應用程式

若要建立 Azure 函式應用程式,請遵循下列步驟:

  1. 開啟 Visual Studio,然後選取 [建立新專案]
  2. 搜尋並選取 [Azure Functions],然後選取 [ 下一步]。
  3. 為專案命名,例如 AuthEventsTrigger。 最好將方案名稱與項目名稱相符。
  4. 選取專案的 [位置] 。 選取 [下一步]。
  5. 選取 .NET 6.0 (長期支持) 作為目標架構。
  6. 選取 [Http 觸發程式 ] 作為 [ 函式 類型],並將該 [授權層級 ] 設定為 [ 函式]。 選取 建立
  7. 方案總管 中,將Function1.cs檔案重新命名為AuthEventsTrigger.cs,並接受重新命名變更建議。

安裝 NuGet 套件並建置專案

建立項目之後,您必須安裝必要的 NuGet 套件並建置專案。

  1. 在 Visual Studio 的頂端功能表中,選取 [專案],然後選取 [管理 NuGet 套件]。
  2. 選取 [ 瀏覽] 索引卷標,然後在右窗格中搜尋並選取 [Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents ]。 選取 [安裝]。
  3. 套用並接受出現的彈出視窗中的變更。

新增範例程序代碼

函式 API 是您令牌的額外宣告來源。 為了本文的目的,我們會硬式編碼範例應用程式的值。 在生產環境中,您可以從外部數據存放區擷取使用者的相關信息。

在您的 AuthEventsTrigger.cs 檔案中,以下列程式代碼取代檔案的整個內容:

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents.TokenIssuanceStart;
using Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents;

namespace AuthEventsTrigger
{
    public static class AuthEventsTrigger
    {
        [FunctionName("onTokenIssuanceStart")]
        public static WebJobsAuthenticationEventResponse Run(
            [WebJobsAuthenticationEventsTrigger] WebJobsTokenIssuanceStartRequest request, ILogger log)
        {
            try
            {
                // Checks if the request is successful and did the token validation pass
                if (request.RequestStatus == WebJobsAuthenticationEventsRequestStatusType.Successful)
                {
                    // Fetches information about the user from external data store
                    // Add new claims to the token's response
                    request.Response.Actions.Add(
                        new WebJobsProvideClaimsForToken(
                            new WebJobsAuthenticationEventsTokenClaim("dateOfBirth", "01/01/2000"),
                            new WebJobsAuthenticationEventsTokenClaim("customRoles", "Writer", "Editor"),
                            new WebJobsAuthenticationEventsTokenClaim("apiVersion", "1.0.0"),
                            new WebJobsAuthenticationEventsTokenClaim(
                                "correlationId", 
                                request.Data.AuthenticationContext.CorrelationId.ToString())));
                }
                else
                {
                    // If the request fails, such as in token validation, output the failed request status, 
                    // such as in token validation or response validation.
                    log.LogInformation(request.StatusMessage);
                }
                return request.Completed();
            }
            catch (Exception ex) 
            { 
                return request.Failed(ex);
            }
        }
    }
}

在本機建置並執行專案

專案已建立,並已新增範例程序代碼。 使用 IDE 時,我們需要在本機建置並執行專案,以擷取本機函式 URL。

  1. 流覽至頂端功能表中的 [ 置],然後選取 [ 建置方案]。
  2. F5 或從頂端功能表中選取 [AuthEventsTrigger ],以執行函式。
  3. 從執行函式時快顯的終端機複製函 式 URL 。 設定自訂驗證延伸模組時,可以使用此功能。

在將函式部署至 Azure 之前,最好先在本機測試函式。 我們可以使用模擬 Microsoft Entra ID 傳送至 REST API 的要求的虛擬 JSON 主體。 使用您慣用的 API 測試工具來直接呼叫 函式。

  1. 在您的 IDE 中,開啟 local.settings.json ,並以下列 JSON 取代程式碼。 我們可以針對本機測試目的將 設定 "AuthenticationEvents__BypassTokenValidation"true

    {
      "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "",
        "AzureWebJobsSecretStorageType": "files",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet",
        "AuthenticationEvents__BypassTokenValidation" : true
      }
    }
    
  2. 使用您慣用的 API 測試工具,建立新的 HTTP 要求,並將 HTTP 方法設定POST

  3. 使用下列 JSON 主體,模擬 Microsoft Entra ID 傳送至 REST API 的要求。

    {
        "type": "microsoft.graph.authenticationEvent.tokenIssuanceStart",
        "source": "/tenants/aaaabbbb-0000-cccc-1111-dddd2222eeee/applications/00001111-aaaa-2222-bbbb-3333cccc4444",
        "data": {
            "@odata.type": "microsoft.graph.onTokenIssuanceStartCalloutData",
            "tenantId": "aaaabbbb-0000-cccc-1111-dddd2222eeee",
            "authenticationEventListenerId": "11112222-bbbb-3333-cccc-4444dddd5555",
            "customAuthenticationExtensionId": "22223333-cccc-4444-dddd-5555eeee6666",
            "authenticationContext": {
                "correlationId": "aaaa0000-bb11-2222-33cc-444444dddddd",
                "client": {
                    "ip": "127.0.0.1",
                    "locale": "en-us",
                    "market": "en-us"
                },
                "protocol": "OAUTH2.0",
                "clientServicePrincipal": {
                    "id": "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
                    "appId": "00001111-aaaa-2222-bbbb-3333cccc4444",
                    "appDisplayName": "My Test application",
                    "displayName": "My Test application"
                },
                "resourceServicePrincipal": {
                    "id": "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
                    "appId": "00001111-aaaa-2222-bbbb-3333cccc4444",
                    "appDisplayName": "My Test application",
                    "displayName": "My Test application"
                },
                "user": {
                    "companyName": "Casey Jensen",
                    "createdDateTime": "2023-08-16T00:00:00Z",
                    "displayName": "Casey Jensen",
                    "givenName": "Casey",
                    "id": "00aa00aa-bb11-cc22-dd33-44ee44ee44ee",
                    "mail": "casey@contoso.com",
                    "onPremisesSamAccountName": "Casey Jensen",
                    "onPremisesSecurityIdentifier": "<Enter Security Identifier>",
                    "onPremisesUserPrincipalName": "Casey Jensen",
                    "preferredLanguage": "en-us",
                    "surname": "Jensen",
                    "userPrincipalName": "casey@contoso.com",
                    "userType": "Member"
                }
            }
        }
    }
    
    
  4. 選取 [ 傳送],您應該會收到類似下列的 JSON 回應:

    {
        "data": {
            "@odata.type": "microsoft.graph.onTokenIssuanceStartResponseData",
            "actions": [
                {
                    "@odata.type": "microsoft.graph.tokenIssuanceStart.provideClaimsForToken",
                    "claims": {
                        "customClaim1": "customClaimValue1",
                        "customClaim2": [
                            "customClaimString1",
                            "customClaimString2" 
                        ]
                    }
                }
    
            ]
        }
    }
    

部署函式併發佈至 Azure

函式必須使用我們的 IDE 部署至 Azure。 確認您已正確登入您的 Azure 帳戶,以便發布函式。

  1. 在 方案總管 中,以滑鼠右鍵按兩下專案,然後選取 [發佈]。

  2. [目標] 中,選取 [Azure],然後選取 [ 下一步]。

  3. 選取 [特定目標的 Azure 函式應用程式]、選取 [Azure 函式應用程式] [Windows],然後選取 [下一步]。

  4. 在 [函式] 實例,使用 [訂用帳戶名稱] 下拉式清單來選取將在其中建立新函式應用程式的訂用帳戶。

  5. 選取您要發佈新函式應用程式的位置,然後選取 [ 新建]。

  6. 在 [ 函式應用程式 (Windows)] 頁面上,使用下表中指定的函式應用程式設定,然後選取 [ 建立]。

    設定 建議的值 名描述
    名稱 全域唯一的名稱 識別新函式應用程式的名稱。 有效的字元是 a-z (不區分大小寫)、0-9-
    訂用帳戶 您的訂用帳戶 建立新函式應用程式的訂用帳戶。
    資源群組 myResourceGroup 選取現有的資源群組,或命名您要在其中建立函式應用程式的新資源群組。
    方案類型 使用量 (無伺服器) 定義如何將資源配置給函式應用程式的主控方案。
    地點 慣用區域 選取的區域應靠近您或靠近函式能夠存取的其他服務。
    Azure 儲存體 您的儲存體帳戶 函數執行階段所需的 Azure 儲存體帳戶。 選取 [新增] 以設定一般用途的儲存體帳戶。
    Application Insights Default Azure 監視器的功能。 這會自動選取,選取您想要使用或設定新選項。
  7. 請稍候片刻,讓函式應用程式部署。 窗口關閉后,選取 [ 完成]。

  8. 隨即開啟新的 [發佈] 窗格。 在頂端,選取 [ 發佈]。 請等候幾分鐘,讓函式應用程式部署並顯示在 Azure 入口網站 中。

設定 Azure 函式的驗證

有三種方式可設定 Azure 函式的驗證:

根據預設,程式代碼已設定為在 Azure 入口網站 中使用環境變數進行驗證。 使用下列索引標籤來選取您實作環境變數的慣用方法,或者,請參閱內 建的 Azure App Service 驗證和授權。 若要設定環境變數,請使用下列值:

名稱
AuthenticationEvents__AudienceAppId 在設定令牌發行事件的自定義宣告提供者中設定的自定義驗證延伸模組應用程式識別碼
AuthenticationEvents__AuthorityUrl • 員工租使用者 https://login.microsoftonline.com/<tenantID>
• 外部租使用者 https://<mydomain>.ciamlogin.com
AuthenticationEvents__AuthorizedPartyAppId 99045fe1-7639-4a75-9d4a-577b6ca3810f 或另一個授權合作物件

使用環境變數在 Azure 入口網站 中設定驗證

  1. 至少以 Application 管理員 istrator 或 Authentication 管理員 istrator 身分登入 Azure 入口網站
  2. 流覽至您所建立的函式應用程式,然後在 [設定] 底下,選取 [組態]。
  3. 在 [應用程式設定] 底下,選取 [新增應用程式設定],然後從數據表及其相關聯的值新增環境變數。
  4. 選取 [儲存] 以儲存應用程式設定。

後續步驟