How to acquire a token with Azure AD and MSAL in ASP.NET

两盒软妹~` 提交于 2021-02-11 14:18:29

问题


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();
    }
    ...
}

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.

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


回答1:


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.

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.



来源:https://stackoverflow.com/questions/65189280/how-to-acquire-a-token-with-azure-ad-and-msal-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!