使用 Azure Pipelines 部署自定义策略

重要

自 2025 年 5 月 1 日起,Azure AD B2C 将不再可供新客户购买。 在我们的常见问题解答中了解详细信息

Azure Pipelines 支持持续集成 (CI) 和持续交付 (CD),以持续一致地测试、生成代码并将其交付到任何目标。 本文介绍如何使用 Azure Pipelines 自动执行 Azure Active Directory B2C (Azure AD B2C) 自定义策略 的部署过程。

重要

借助 Azure Pipelines 管理 Azure AD B2C 自定义策略目前使用 Microsoft Graph API /beta 终结点上提供的预览操作。 不支持在生产应用程序中使用这些 API。 有关详细信息,请参阅 Microsoft Graph REST API beta 版本终结点参考

先决条件

为管理任务注册应用程序

使用 PowerShell 脚本部署 Azure AD B2C 策略。 在 PowerShell 脚本可以与 Microsoft Graph API 交互之前,请在 Azure AD B2C 租户中创建应用程序注册。 如果尚未注册,请 注册 Microsoft Graph 应用程序

要使 PowerShell 脚本访问 MS Graph 中的数据,请向已注册的应用程序授予相关的 应用程序权限。 在应用注册的 API 权限中授予 Microsoft Graph>策略>Policy.ReadWrite.TrustFramework 权限。

配置 Azure 存储库

注册 Microsoft Graph 应用程序后,您就可以为策略文件配置存储库了。

  1. 登录到你的 Azure DevOps 组织
  2. 创建新项目,或选择现有项目。
  3. 在项目中,导航到 存储库,然后选择文件
  4. 选择现有存储库或创建一个存储库。
  5. 在你的仓库根目录中,创建一个名为 B2CAssets 的文件夹。 将 Azure AD B2C 自定义策略文件添加到 B2CAssets 文件夹。
  6. 在仓库的根目录中,创建一个名称为Scripts的文件夹。 创建 PowerShell 文件 DeployToB2C.ps1. 将以下 PowerShell 脚本粘贴到 DeployToB2C.ps1中。
  7. 提交并推送更改。

以下脚本从 Microsoft Entra ID 获取访问令牌。 使用令牌,脚本会调用 MS Graph API 将策略上传到 B2CAssets 文件夹中。 您还可以在上传策略之前更改策略的内容。 例如,将tenant-name.onmicrosoft.com替换为您的租户名称。

[Cmdletbinding()]
Param(
    [Parameter(Mandatory = $true)][string]$ClientID,
    [Parameter(Mandatory = $true)][string]$ClientSecret,
    [Parameter(Mandatory = $true)][string]$TenantId,
    [Parameter(Mandatory = $true)][string]$Folder,
    [Parameter(Mandatory = $true)][string]$Files
)

try {
    $body = @{grant_type = "client_credentials"; scope = "https://graph.microsoft.com/.default"; client_id = $ClientID; client_secret = $ClientSecret }

    $response = Invoke-RestMethod -Uri https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token -Method Post -Body $body
    $token = $response.access_token

    $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
    $headers.Add("Content-Type", 'application/xml')
    $headers.Add("Authorization", 'Bearer ' + $token)

    # Get the list of files to upload
    $filesArray = $Files.Split(",")

    Foreach ($file in $filesArray) {

        $filePath = $Folder + $file.Trim()

        # Check if file exists
        $FileExists = Test-Path -Path $filePath -PathType Leaf

        if ($FileExists) {
            $policycontent = Get-Content $filePath -Encoding UTF8

            # Optional: Change the content of the policy. For example, replace the tenant-name with your tenant name.
            # $policycontent = $policycontent.Replace("your-tenant.onmicrosoft.com", "contoso.onmicrosoft.com")     
    
    
            # Get the policy name from the XML document
            $match = Select-String -InputObject $policycontent  -Pattern '(?<=\bPolicyId=")[^"]*'
    
            If ($match.matches.groups.count -ge 1) {
                $PolicyId = $match.matches.groups[0].value
    
                Write-Host "Uploading the" $PolicyId "policy..."
    
                $graphuri = 'https://graph.microsoft.com/beta/trustframework/policies/' + $PolicyId + '/$value'
                $content = [System.Text.Encoding]::UTF8.GetBytes($policycontent)
                $response = Invoke-RestMethod -Uri $graphuri -Method Put -Body $content -Headers $headers -ContentType "application/xml; charset=utf-8"
    
                Write-Host "Policy" $PolicyId "uploaded successfully."
            }
        }
        else {
            $warning = "File " + $filePath + " couldn't be not found."
            Write-Warning -Message $warning
        }
    }
}
catch {
    Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__

    $_

    $streamReader = [System.IO.StreamReader]::new($_.Exception.Response.GetResponseStream())
    $streamReader.BaseStream.Position = 0
    $streamReader.DiscardBufferedData()
    $errResp = $streamReader.ReadToEnd()
    $streamReader.Close()

    $ErrResp

    exit 1
}

exit 0

配置 Azure Pipelines

初始化存储库并填充自定义策略文件后,您就可以设置发布管道了。 要创建管道,请执行以下步骤:

  1. 在项目中,选择“管道”>“发布”>“新建管道”
  2. 在“选择模板”下,选择“空作业”,然后选择“应用”
  3. 输入 Stage name (阶段名称),例如 DeployCustomPolicies,然后关闭窗格。
  4. 选择“添加项目”,然后在“源类型”下选择“Azure 存储库”。
    1. 在“项目”这一项中选择你的项目。
    2. 选择包含 Scripts 文件夹的 Source (repository) (源(存储库))。
    3. 选择 Default branch(默认分支),例如 master
    4. 将“默认版本”设置保留为“默认分支中的最新内容”
    5. 输入存储库的 Source 别名 。 例如, policyRepo
  5. 选择 “添加”
  6. 重命名管道以反映其意图。 例如, 部署自定义策略管道
  7. 选择 Save 以保存管道配置。

配置管道变量

管道变量为您提供了一种将关键数据导入管道各个部分的便捷方法。 以下变量提供有关 Azure AD B2C 环境的信息。

名称 价值
clientId 您之前注册的应用程序(客户端)ID
clientSecret 您之前创建的 客户端密钥 的值。
将变量类型更改为 secret (选择锁图标)。
tenantId your-b2c-tenant.onmicrosoft.com,其中 your-b2c-tenant 是 Azure AD B2C 租户的名称。

要添加管道变量,请执行以下步骤:

  1. 在管道中,选择 Variables(变量)选项卡。
  2. Pipeline variables (管道变量) 下,添加上述变量及其值。
  3. 选择 Save 以保存变量。

添加管道任务

管道任务是一个预打包的脚本,用于执行某个操作。 添加调用 DeployToB2C.ps1 PowerShell 脚本的任务。

  1. 在您创建的管道中,选择 Tasks ( 任务) 选项卡。

  2. 选择 Agent job (代理作业),然后选择加号 ()+ 以将任务添加到代理作业。

  3. 搜索并选择 PowerShell。 请勿选择“Azure PowerShell”、“目标计算机上的 PowerShell”或其他 PowerShell 条目。

  4. 选择新添加的 PowerShell 脚本 任务。

  5. 为 PowerShell 脚本任务输入以下值:

    • 任务版本:2.*

    • Display name(显示名称):此任务应上传的策略的名称。 例如, B2C_1A_TrustFrameworkBase

    • 类型:文件路径

    • 脚本路径:选择省略号 (...),导航到 Scripts 文件夹,然后选择 DeployToB2C.ps1 文件。

    • 参数:输入以下 PowerShell 脚本。

      -ClientID $(clientId) -ClientSecret $(clientSecret) -TenantId $(tenantId) -Folder $(System.DefaultWorkingDirectory)/policyRepo/B2CAssets/ -Files "TrustFrameworkBase.xml,TrustFrameworkLocalization.xml,TrustFrameworkExtensions.xml,SignUpOrSignin.xml,ProfileEdit.xml,PasswordReset.xml"
      

      -Files 参数是要部署的策略文件的逗号分隔列表。 使用策略文件更新该列表。

      重要

      确保策略按正确的顺序上传。 首先是基本策略、扩展策略,然后是依赖方策略。 例如,TrustFrameworkBase.xml,TrustFrameworkLocalization.xml,TrustFrameworkExtensions.xml,SignUpOrSignin.xml

  6. 选择 Save 以保存代理作业。

测试管道

要测试发布流程,请执行以下步骤:

  1. 选择 Pipelines ,然后选择 Releases
  2. 选择您之前创建的管道,例如 DeployCustomPolicies
  3. 选择创建发布,然后选择创建以将发布加入队列。

应该会看到一个通知横幅,指出发布已排入队列。 要查看其状态,请选择通知横幅中的链接,或在 Releases 选项卡的列表中选择它。

后续步骤

了解有关以下方面的详细信息: