练习 - 使用 MSAL.NET 实现交互式身份验证

已完成

本练习介绍如何执行以下操作:

  • 将应用程序注册到 Microsoft 标识平台
  • 在 MSAL.NET 中使用 PublicClientApplicationBuilder
  • 在控制台应用程序中以交互方式获取令牌

先决条件

注册新应用程序

  1. 登录到门户:https://portal.azure.com

  2. 搜索并选择 Microsoft Entra ID

  3. 在“管理”下,选择“应用注册”>“新建注册” 。

  4. “注册应用程序”页出现后,请输入应用程序的注册信息:

    字段
    名称 az204appreg
    支持的帐户类型 选择“仅此组织目录中的帐户”
    重定向 URI(可选) 选择“公共客户端/本机(移动和桌面)”并在右侧框中输入 http://localhost
  5. 选择注册

Microsoft Entra ID 将为你的应用分配一个唯一的应用程序(客户端)ID,然后转至应用程序的“概览”页面。

设置控制台应用程序

  1. 启动 Visual Studio Code,然后依次选择“终端”和“新建终端”打开一个终端。

  2. 为该项目创建一个文件夹,并更改到该文件夹。

    md az204-auth
    cd az204-auth
    
  3. 创建 .NET 控制台应用。

    dotnet new console
    
  4. 在 Visual Studio Code 中打开“az204-auth”文件夹。

    code . -r
    

生成控制台应用

在此部分,你需要将必要的包和代码添加到项目中。

添加包和 using 语句

  1. 在 Visual Studio Code 的终端中将 Microsoft.Identity.Client 包添加到项目中。

    dotnet add package Microsoft.Identity.Client
    
  2. 打开 Program.cs 文件,然后添加 语句以包含 Microsoft.Identity.Client 并启用异步操作。

    using System.Threading.Tasks;
    using Microsoft.Identity.Client;
    
  3. 更改 Main 方法以启用异步。

    public static async Task Main(string[] args)
    

添加交互式身份验证的代码

  1. 你需要使用两个变量来保留应用程序(客户端)和目录(租户)ID。 你可以从门户中复制这些值。 添加以下代码,并将字符串值替换为门户中的相应值。

    private const string _clientId = "APPLICATION_CLIENT_ID";
    private const string _tenantId = "DIRECTORY_TENANT_ID";
    
  2. 使用 PublicClientApplicationBuilder 类生成授权上下文。

    var app = PublicClientApplicationBuilder
        .Create(_clientId)
        .WithAuthority(AzureCloudInstance.AzurePublic, _tenantId)
        .WithRedirectUri("http://localhost")
        .Build();
    
    代码 说明
    .Create 基于 clientID 创建一个 PublicClientApplicationBuilder
    .WithAuthority 添加与 ADFS 服务器对应的已知机构。 在此代码中,我们将指定公有云,并将租户用于我们注册的应用。

获取令牌

当你注册“az204appreg”应用时,它会自动为 Microsoft Graph 生成 API 权限 user.read。 使用该权限来获取令牌。

  1. 设置令牌请求的权限范围。 将以下代码添加到 PublicClientApplicationBuilder 下。

    string[] scopes = { "user.read" };
    
  2. 添加代码以请求令牌,将结果写出到控制台。

    AuthenticationResult result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
    
    Console.WriteLine($"Token:\t{result.AccessToken}");
    

查看已完成的应用程序

Program.cs 文件的内容应类似于下面的示例:

using System;
using System.Threading.Tasks;
using Microsoft.Identity.Client;

namespace az204_auth
{
    class Program
    {
        private const string _clientId = "APPLICATION_CLIENT_ID";
        private const string _tenantId = "DIRECTORY_TENANT_ID";

        public static async Task Main(string[] args)
        {
            var app = PublicClientApplicationBuilder
                .Create(_clientId)
                .WithAuthority(AzureCloudInstance.AzurePublic, _tenantId)
                .WithRedirectUri("http://localhost")
                .Build(); 
            string[] scopes = { "user.read" };
            AuthenticationResult result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();

            Console.WriteLine($"Token:\t{result.AccessToken}");
        }
    }
}

运行应用程序

  1. 在 Visual Studio Code 终端中运行 dotnet build 以检查是否有错误,然后运行 dotnet run 以运行应用。

  2. 应用将打开默认浏览器,提示你选择要进行身份验证的帐户。 如果列出了多个帐户,请选择与应用中使用的租户关联的那个帐户。

  3. 如果这是你第一次对注册的应用进行身份验证,你将收到一条“已请求权限”通知,要求你批准该应用读取与你的帐户关联的数据。 选择“接受”。

    Select **Accept** to grant the permission.

  4. 你应该会在控制台中看到与以下示例类似的结果。

    Token:  eyJ0eXAiOiJKV1QiLCJub25jZSI6IlVhU.....