使用 Azure Functions 创建具有令牌颁发启动事件的 REST API(预览版)

本文介绍如何使用 Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents NuGet 库创建具有令牌颁发启动事件的 REST API。 在 Visual Studio 中创建 HTTP 触发器函数并将其部署到 Azure 门户,可通过 Azure Functions 访问它。

先决条件

本文介绍如何使用 Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents NuGet 库创建具有令牌颁发启动事件的 REST API。 在 Visual Studio 中创建 HTTP 触发器函数并将其部署到 Azure 门户,可通过 Azure Functions 访问它。

先决条件

创建和生成 Azure 函数应用

在此步骤中,你将使用 Visual Studio 创建一个 HTTP 触发器函数 API,安装所需的 NuGet 包并在示例代码中复制。 生成项目并在本地运行函数以提取函数 URL。

创建 Azure 函数应用

要创建 Azure 函数应用,请按照以下步骤操作:

  1. 打开 Visual Studio,选择“新建项目”。
  2. 搜索并选择“Azure Functions”,然后选择“下一步”。
  3. 为项目命名,例如“AuthEventsTrigger”。 最好将解决方案名称与项目名称匹配。
  4. 选择项目的位置。 选择下一步
  5. 选择“.NET 6.0 (长期支持)”作为目标框架。
  6. 选择“Http 触发器”作为“函数”类型,并将“授权级别”设置为“函数”。 选择创建

安装 NuGet 包并生成项目

创建完项目后,需要安装所需的 NuGet 包并生成项目。

  1. 在 Visual Studio 的顶部菜单中,选择“项目”,然后选择“管理 NuGet 包”。
  2. 选择“浏览”选项卡,然后搜索并选择“Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents”。 在右窗格中,选择“安装”。
  3. 应用并接受显示的弹出窗口中的更改。

添加示例代码

该函数 API 是令牌的附加声明的源。 在本文中,我们将对示例应用的值进行硬编码。 在生产中,请从外部数据存储提取有关用户的信息。

在你的 Function1.cs 文件中,将文件的全部内容替换为以下代码:

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents.TokenIssuanceStart;
using Microsoft.Azure.WebJobs.Extensions.WebJobsAuthenticationEvents;

namespace AuthEventTrigger
{
    public static class Function1
    {
        [FunctionName("onTokenIssuanceStart")]
        public static WebJobsAuthenticationEventResponse Run(
        // [WebJobsAuthenticationEventsTriggerAttribute] WebJobsTokenIssuanceStartRequest request, ILogger log)
        // The WebJobsAuthenticationEventsTriggerAttribute attribute can be used to specify and audience app ID, authority URL and authorized party app id. This is an alternative route to setting up Authorization values instead of Environment variables or EzAuth
            [WebJobsAuthenticationEventsTriggerAttribute(AudienceAppId = "Enter custom authentication extension app ID here",
                                         AuthorityUrl = "Enter authority URI here", 
                                         AuthorizedPartyAppId = "Enter the Authorized Party App Id here")]WebJobsTokenIssuanceStartRequest request, ILogger log)
        {
            try
            {
                // Checks if the request is successful and did the token validation pass
                if (request.RequestStatus == RequestStatusType.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 await request.Completed();
            }
            catch (Exception ex) 
            { 
                return await request.Failed(ex);
            }
        }
    }
}

提示

在本地开发和测试中,请打开 local.settings.json 并添加 AzureWebJobsStorageAzureWebJobsSecretStorageType 值,如以下代码片段所示:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "AzureWebJobsSecretStorageType": "files",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  }
}

生成并运行项目

项目已创建,且示例代码已添加。 现在,我们要生成并运行项目以提取函数 URL。

  1. 导航到顶部菜单中的“生成”,然后选择“生成解决方案”。
  2. 按 F5 或从顶部菜单中选择“AuthEventsTrigger”以运行函数。
  3. 从运行函数时弹出的终端复制“函数 URL”。 设置自定义身份验证扩展时可以使用它。

部署函数并发布到 Azure

需要使用我们的 IDE 将函数部署到 Azure。 检查你是否已正确登录到 Azure 帐户,以便可以发布函数。

  1. 在解决方案资源管理器中,右键单击项目并选择“发布”。

  2. 在“目标”中选择“Azure”,然后选择“下一步”。

  3. 为“特定目标”选择“Azure 函数应用(Windows)”,选择“Azure 函数应用(Windows)”,然后选择“下一步”。

  4. 在“函数实例”中,使用“订阅名称”下拉列表选择要在其中创建新函数应用的订阅。

  5. 选择要发布新函数应用的位置,然后选择“新建”。

  6. 在“函数应用(Windows)”页上,使用下表中指定的函数应用设置,然后选择“创建”。

    设置 建议值 说明
    名称 全局唯一名称 用于标识新函数应用的名称。 有效字符为 a-z(不区分大小写)、0-9-
    订阅 你的订阅 在其下创建此新函数应用的订阅。
    资源组 myResourceGroup 选择现有的资源组,或命名一个新组以便在其中创建函数应用。
    计划类型 消耗(无服务器) 定义如何将资源分配给 Function App 的托管计划。
    位置 首选区域 选择与你靠近或者与函数可以访问的其他服务靠近的区域
    Azure 存储 你的存储帐户 Functions 运行时需要 Azure 存储帐户。 选择“新建”即可配置常规用途存储帐户。
    Application Insights 默认值 Azure Monitor 的一项功能。 这是自动选择的,请选择你要使用的项或配置新的。
  7. 等待片刻,让函数应用完成部署。 窗口关闭后,选择“完成”。

  8. 此时会打开新的“发布”窗格。 在顶部,选择“发布”。 等待几分钟,让函数应用完成部署并在 Azure 门户中显示。

为 Azure 函数设置环境变量(可选)

你可以为 Azure Functions 设置环境变量,而不使用 AuthenticationEventsTrigger 特性来实现内置的 Azure 应用服务身份验证和授权。 可以在该特性中硬编码这些环境变量,也可以在 Azure 门户中设置,但不能两者同时进行。

在代码中设置环境变量

修改 AuthenticationEventsTrigger 包含 AuthorityUrlAudienceAppIdAuthorizedPartyAppId(可选)属性,如以下代码片段所示。

[FunctionName("onTokenIssuanceStart")]
public async static Task<AuthenticationEventResponse> Run(
    [AuthenticationEventsTrigger(
    AudienceAppId = "Enter custom authentication extension app ID here",
    AuthorityUrl = "Enter authority URI here", // The .well-known/openid-configuration endpoint is appended to the AuthorityUrl in the SDK
    AuthorizedPartyAppId = "Enter the Authorized Party App Id here")] TokenIssuanceStartRequest request, ILogger log) 

在 Azure 门户中设置环境变量

  1. 至少以应用程序管理员身份验证管理员身份登录到 Azure 门户

  2. 导航到你创建的函数应用,然后在“设置”下选择“配置”。

  3. 在“应用程序设置”下,选择“新建应用程序设置”,然后添加以下环境变量和关联值。

    名称
    AuthenticationEvents__AudienceAppId 自定义身份验证扩展应用 ID
    AuthenticationEvents__AuthorityUrl • 工作人员租户 https://login.microsoftonline.com/<tenantID>
    • 外部租户 https://<mydomain>.ciamlogin.com
    AuthenticationEvents__AuthorizedPartyAppId 99045fe1-7639-4a75-9d4a-577b6ca3810f
  4. 选择“保存”,以保存应用程序设置。

    提示

    AuthenticationEvents__AuthorizedPartyAppId 环境变量是可选的,可用于开发目的。 本方案不严格要求使用它。

创建和生成 Azure 函数应用

在此步骤中,你将使用 Visual Studio Code 创建一个 HTTP 触发器函数 API,安装所需的 NuGet 包并在示例代码中复制。 你将生成项目并在本地运行函数以提取函数 URL。

创建 Azure 函数应用

要创建 Azure 函数应用,请按照以下步骤操作:

  1. 打开 Visual Studio Code。

  2. 在“资源管理器”窗口中选择“新建文件夹”图标,然后为你的项目创建一个新文件夹,例如“AuthEventsTrigger”。

  3. 选择屏幕左侧的 Azure 扩展图标。 登录到你的 Azure 帐户(如果尚未)。

  4. 在“工作区”栏下,选择“Azure Functions”图标 >“创建新项目”。

    显示如何在 Visual Studio Code 中添加 Azure 函数的屏幕截图。

  5. 在顶部栏中,选择要创建项目的位置。

  6. 选择“C#”作为语言,“.NET 6.0 LTS”作为 .NET 运行时。

  7. 选择“HTTP 触发器”作为模板。

  8. 提供项目的名称,例如“AuthEventsTrigger”。

  9. 接受“Company.Function”作为命名空间,使 AccessRights 设置为“Function”。

安装 NuGet 包并生成项目

创建完项目后,需要安装所需的 NuGet 包并生成项目。

  1. 在 Visual Studio Code 中打开“终端”,然后导航到项目文件夹。

  2. 在控制台中输入以下命令以安装 Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents NuGet 包。

    dotnet add package Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents --prerelease
    

添加示例代码

该函数 API 是令牌的附加声明的源。 在本文中,我们将对示例应用的值进行硬编码。 在生产中,请从外部数据存储提取有关用户的信息。

将 AuthEventsTrigger.cs 文件的整个内容替换为以下代码:

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents.TokenIssuanceStart;
using Microsoft.Azure.WebJobs.Extensions.WebJobsAuthenticationEvents;

namespace AuthEventTrigger
{
    public static class Function1
    {
        [FunctionName("onTokenIssuanceStart")]
        public static WebJobsAuthenticationEventResponse Run(
        // [WebJobsAuthenticationEventsTriggerAttribute] WebJobsTokenIssuanceStartRequest request, ILogger log)
        // The WebJobsAuthenticationEventsTriggerAttribute attribute can be used to specify and audience app ID, authority URL and authorized party app id. This is an alternative route to setting up Authorization values instead of Environment variables or EzAuth
            [WebJobsAuthenticationEventsTriggerAttribute(AudienceAppId = "Enter custom authentication extension app ID here",
                                         AuthorityUrl = "Enter authority URI here", 
                                         AuthorizedPartyAppId = "Enter the Authorized Party App Id here")]WebJobsTokenIssuanceStartRequest request, ILogger log)
        {
            try
            {
                // Checks if the request is successful and did the token validation pass
                if (request.RequestStatus == RequestStatusType.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 await request.Completed();
            }
            catch (Exception ex) 
            { 
                return await request.Failed(ex);
            }
        }
    }
}

提示

在本地开发和测试中,请打开 local.settings.json 并添加 AzureWebJobsStorageAzureWebJobsSecretStorageType 值,如以下代码片段所示:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "AzureWebJobsSecretStorageType": "files",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  }
}

生成并运行项目

  1. 在顶部菜单中,选择“运行”>”开始调试”或按 F5 运行函数。
  2. 在终端中,复制显示的“函数 URL”。 设置自定义身份验证扩展时可以使用它。

部署函数并发布到 Azure

需要使用我们的 IDE 将函数部署到 Azure。 检查你是否已正确登录到 Azure 帐户,以便可以发布函数。

  1. 选择 Azure 扩展图标。 在“资源”中,选择 + 图标以创建资源。
  2. 选择“在 Azure 中创建函数应用”。 使用以下设置来设置你的函数应用。
  3. 为函数应用命名,例如“AuthEventsTriggerNuGet”,然后按 Enter。
  4. 选择“.NET 6 (LTS) 进程内”运行时堆栈。
  5. 选择函数应用的位置,例如“美国东部”。
  6. 等待几分钟,让函数应用完成部署并在 Azure 门户中显示。

为 Azure 函数设置环境变量(可选)

你可以为 Azure Functions 设置环境变量,而不使用 AuthenticationEventsTrigger 特性来实现内置的 Azure 应用服务身份验证和授权。 可以在该特性中硬编码这些环境变量,也可以在 Azure 门户中设置,但不能两者同时进行。

在代码中设置环境变量

修改 AuthenticationEventsTrigger 包含 AuthorityUrlAudienceAppIdAuthorizedPartyAppId(可选)属性,如以下代码片段所示。

[FunctionName("onTokenIssuanceStart")]
public async static Task<AuthenticationEventResponse> Run(
    [AuthenticationEventsTrigger(
    AudienceAppId = "Enter custom authentication extension app ID here",
    AuthorityUrl = "Enter authority URI here", // The .well-known/openid-configuration endpoint is appended to the AuthorityUrl in the SDK
    AuthorizedPartyAppId = "Enter the Authorized Party App Id here")] TokenIssuanceStartRequest request, ILogger log) 

在 Azure 门户中设置环境变量

  1. 至少以应用程序管理员身份验证管理员身份登录到 Azure 门户

  2. 导航到你创建的函数应用,然后在“设置”下选择“配置”。

  3. 在“应用程序设置”下,选择“新建应用程序设置”,然后添加以下环境变量和关联值。

    名称
    AuthenticationEvents__AudienceAppId 自定义身份验证扩展应用 ID
    AuthenticationEvents__AuthorityUrl • 工作人员租户 https://login.microsoftonline.com/<tenantID>
    • 外部租户 https://<mydomain>.ciamlogin.com
    AuthenticationEvents__AuthorizedPartyAppId 99045fe1-7639-4a75-9d4a-577b6ca3810f
  4. 选择“保存”,以保存应用程序设置。

    提示

    AuthenticationEvents__AuthorizedPartyAppId 环境变量是可选的,可用于开发目的。 本方案不严格要求使用它。

下一步