如何在 ASP.NET 中使用 Azure AD 和 MSAL 获取令牌 [英] How to acquire a token with Azure AD and MSAL in ASP.NET

查看:47
本文介绍了如何在 ASP.NET 中使用 Azure AD 和 MSAL 获取令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Azure AD 对令牌进行身份验证.在控制台应用程序中,由于 IConfidentialClientApplication,我对此没有任何问题:

I'm trying to authenticate a token using Azure AD. In a console application, I have no problem with this thanks to IConfidentialClientApplication:

static void Main(string[] args)
{
    Console.WriteLine("Making the call...");
    RunAsync().GetAwaiter().GetResult();
}

private static async Task RunAsync()
{
    AuthConfig config = AuthConfig.ReadJsonFromFile("appsettings.json");

    IConfidentialClientApplication app;

    app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
        .WithClientSecret(config.ClientSecret)
        .WithAuthority(new Uri(config.Authority))
        .Build();

    string[] ResourceIds = new string[] { config.ResourceId };

    AuthenticationResult result = null;

    try
    {
        result = await app.AcquireTokenForClient(ResourceIds).ExecuteAsync();
    }
    ...
}

但是在 ASP.NET Core 应用程序的启动中,该应用程序使用标准 IApplicationBuilder 并且 Configure(...) 方法不能采用 IConfidentialClientApplicationBuilder,因为它不存在.

But in a Startup for an ASP.NET Core application, the app uses the standard IApplicationBuilder and the Configure(...) method can't take an IConfidentialClientApplicationBuilder as it doesn't exist.

Microsoft 的文档,他们创建了一个 PublicClientApplicationBuilder,但我不想在我的配置中开始创建全新的应用程序.

In Microsoft's documentation, they create a PublicClientApplicationBuilder, but I don't want to start creating entirely new applications in my configuration.

推荐答案

这里有一个 示例 ASP.NET Core 应用程序的启动供您参考.但据我所知,我们无法使用IApplicationBuilder"直接在 Startup for ASP.NET Core 应用程序中获取令牌."IApplicationBuilder"和IConfidentialClientApplicationBuilder";是两个不同的概念.

Here is a sample of Startup for ASP.NET Core application for your reference. But as far as I know we can't get token directly in the Startup for ASP.NET Core application with "IApplicationBuilder". "IApplicationBuilder" and "IConfidentialClientApplicationBuilder" are two different concepts.

根据您的要求,您可以只为 msal 导入模块并使用您在上面提供的代码或您在 Microsoft 的文档 以获取令牌.

For your requirement, you can just import modules for msal and use the code you provided above or the code you mentioned in the Microsoft's documentation to get the token.

这篇关于如何在 ASP.NET 中使用 Azure AD 和 MSAL 获取令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆