如何使用启用了 2FA 的 Microsoft Azure 帐户调用GenerateToken REST API

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

Postman request

API POST: https://login.microsoftonline.com/common/oauth2/token

我的塞内里奥:

当 Microsoft 帐户启用 2FA 时,此 API 不起作用。它显示这个错误

"error": "interaction_required",
    "error_description": "AADSTS50076: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access '00000009-0000-0000-c000-000000000000'. Trace ID: 05451564-7c99-454f-9f1c-85b5d0ac6a00 Correlation ID: 026670ad-9c04-46d8-828b-0c1435938e90 Timestamp: 2023-11-05 14:11:35Z",
    "error_codes": [
        50076
    ]

但是通过禁用 2FA,效果很好。那么,如何通过启用 2FA 来调用此 API?

azure rest powerbi powerbi-embedded two-factor-authentication
1个回答
0
投票

如果您在使用启用了 2FA 的 Microsoft 帐户调用 API 时收到“interaction_required”错误,则意味着应用程序正在尝试执行非交互式身份验证,而帐户配置为多重身份验证 (MFA)。

在这种情况下,您通常需要使用不同的身份验证方法,例如证书或客户端密钥或设备代码流,这些方法不依赖于 MFA 的用户交互。

使用客户端密钥

以下是我修改应用程序以使用客户端密钥进行身份验证的方法,该方法可以与启用 2FA 的帐户一起正常工作

    using System;
    using Microsoft.Identity.Client;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Threading.Tasks;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            string clientId = "YOUR_CLIENT_ID";
            string tenantId = "YOUR_TENANT_ID";
            string clientSecret = "YOUR_CLIENT_SECRET"; // Replace with your client secret
            string authority = $"https://login.microsoftonline.com/{tenantId}";
            string apiScope = "https://api.example.com/.default"; // Replace with your API scope
            string apiEndpoint = "https://api.example.com/generateToken"; // Replace with your API endpoint
    
            var app = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithClientSecret(clientSecret)
                .WithAuthority(new Uri(authority))
                .Build();
    
            string[] scopes = new string[] { apiScope };
    
            var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
    
            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
    
            var response = await httpClient.PostAsync(apiEndpoint, null);
    
            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();
                Console.WriteLine("API call successful.");
                Console.WriteLine(content);
            }
            else
            {
                Console.WriteLine($"API call failed with status code {response.StatusCode}");
            }
        }
    }

结果 enter image description here

设备代码流程

设备代码流程是一个两步身份验证流程。第一步,用户打开 Web 浏览器并导航到特定 URL。然后,系统会提示他们输入应用程序上显示的设备代码。用户输入设备代码后,他们将被授予访问应用程序的权限。

enter image description here

enter image description here

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