在 C# WPF 桌面应用程序中将 MSAL 与身份验证上下文结合使用

Using MSAL with authentication context in C# WPF desktop app

我们想在我们的桌面应用程序中使用 Azure AD (https://techcommunity.microsoft.com/t5/azure-active-directory-identity/conditional-access-authentication-context-now-in-public-preview/ba-p/1942484) 的身份验证上下文功能,以便在使用我们应用程序的某些部分时触发条件访问。

该文档提供了 Web api 和 Web 应用程序 (https://github.com/Azure-Samples/ms-identity-dotnetcore-ca-auth-context-app/blob/main/README.md https://github.com/Azure-Samples/ms-identity-ca-auth-context/blob/main/README.md) 的示例,但没有关于如何使用此功能保护桌面应用程序部分的文档。

在桌面应用程序 (c# WPF 4.8) 中,我们使用 MSAL 库 (4.35.1),我们也没有找到任何选项/功能来使用应用程序内部的身份验证上下文。

是否有可能或打算能够在桌面应用程序中使用身份验证上下文,或者它是否针对网络场景?

您可以在任何平台上实施身份验证。没有平台限制。

获取令牌:

桌面应用步骤几乎相同。您可以通过以下方式获取令牌:

             authResult = await app.AcquireTokenInteractive(scopes)
                        .WithAccount(firstAccount)
                        .WithParentActivityOrWindow(new WindowInteropHelper(this).Handle) // optional, used to center the browser on the window
                        .WithPrompt(Prompt.SelectAccount)
                        .ExecuteAsync();

使用令牌访问资源:

var httpClient = new System.Net.Http.HttpClient();
            System.Net.Http.HttpResponseMessage response;
            try
            {
                var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, "https://graph.microsoft.com/v1.0/users");
                //Add the token in Authorization header
                request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
                response = await httpClient.SendAsync(request);
                var content = await response.Content.ReadAsStringAsync();
                return content;
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }

您可以从 here in official docs

下载示例应用程序

如果您需要任何进一步的帮助,请告诉我。