如何生成访问令牌来访问代理应用程序

问题描述 投票:0回答:1

如何使用 AcquireTokenSilent 方法生成访问令牌以访问代理应用程序。 我使用了 AcquireTokenSilent 方法,但该方法返回 null 结果。

下面是代码片段

var scopes = new string[] { todoListResourceId + "/user_impersonation" };

            AuthenticationResult authResult;
            //authResult = await clientApp.AcquireTokenSilent(scopes, account).ExecuteAsync();

            try
            {
                authResult = await clientApp.AcquireTokenSilent(scopes, account).ExecuteAsync();
                //authResult = await 
            }
            catch (MsalUiRequiredException ex)
            {
                authResult = await clientApp.AcquireTokenInteractive(scopes).ExecuteAsync();
            }

在** authResult ** 我得到空结果。

谢谢:)

azure azure-active-directory access-token microsoft-entra-id
1个回答
0
投票

我尝试了以下代码来生成访问令牌以访问代理应用程序。

代码:

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

class Program
{
    static async Task Main(string[] args)
    {
        string clientId = "<clientID>";
        string tenantId = "<tenantID>";
        string todoListResourceId = "<resourceID>";

        var pca = PublicClientApplicationBuilder.Create(clientId)
            .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
            .Build();

        var accounts = await pca.GetAccountsAsync();
        var account = accounts.FirstOrDefault();

        if (account == null)
        {
            Console.WriteLine("No accounts found. You need to sign in.");
        }
        else
        {
            var scopes = new string[] { todoListResourceId + "/user_impersonation" };
            AuthenticationResult authResult;

            try
            {
                authResult = await pca.AcquireTokenSilent(scopes, account).ExecuteAsync();
            }
            catch (MsalUiRequiredException)
            {
                try
                {
                    authResult = await pca.AcquireTokenInteractive(scopes).ExecuteAsync();
                }
                catch (Exception interactiveEx)
                {
                    Console.WriteLine($"Interactive authentication failed: {interactiveEx.Message}");
                    return;
                }
            }
            Console.WriteLine($"Access Token: {authResult.AccessToken}");
        }
    }
}

在运行上述代码之前,您应该授予对具有所需范围(user_impersonation)的指定资源(todoListResourceId)的访问权限。

输出:

代码成功运行并生成访问令牌以访问代理应用程序。

Access token output

© www.soinside.com 2019 - 2024. All rights reserved.