Microsoft Graph API - Blazor Server App .NET 5.0 使用 Azure 身份验证,MsalUiRequiredException 因用户质询而引发

Posted

技术标签:

【中文标题】Microsoft Graph API - Blazor Server App .NET 5.0 使用 Azure 身份验证,MsalUiRequiredException 因用户质询而引发【英文标题】:Microsoft Graph API - Blazor Server App .NET 5.0 using Azure Authentication , MsalUiRequiredException was thrown due to a challenge for the user 【发布时间】:2021-09-02 05:42:13 【问题描述】:

关于(以下问题需要帮助)

我目前遇到的问题是在同一浏览器会话中请求新的不记名令牌时。有时我能够从 Microsoft Graph API 检索承载令牌并提取数据,而在其他情况下会收到错误消息:-

执行这行代码时会间歇性发生错误:-

令牌 = 等待 TokenAcquisitionService.GetAccessTokenForUserAsync("User.Read").ConfigureAwait(false);

导致 try catch 错误:-

“IDW10502:由于用户的质询而引发了 MsalUiRequiredException。请参阅 https://aka.ms/ms-id-web/ca_incremental-consent。“

其他信息

使用 Blazor Server App .NET 5.0 编写,使用 Microsoft Azure 身份验证

在我的 startup.cs 类中添加了以下内容:-

public void ConfigureServices(IServiceCollection services)

  services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
     .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
     .EnableTokenAcquisitionToCallDownstreamApi("User.Read") 
     .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
     .AddInMemoryTokenCaches();


在我的 index.razor 页面中:-

@using Microsoft.Extensions.Configuration;
@using Microsoft.Identity.Web
@inject IConfiguration Configuration
@inject Microsoft.Identity.Web.ITokenAcquisition TokenAcquisitionService
@inject MicrosoftIdentityConsentAndConditionalAccessHandler ConsentHandler

@page "/"
<p>Help!!!</p>

在我的 index.razor.cs 类中:-

/// <summary>
/// The User constructor
/// </summary>
public User user  get; set; 

/// <summary>
/// Provides information about the current logged in user if any.
/// </summary>
[CascadingParameter]
public Task<AuthenticationState> authenticationStateTask  get; set; 

private GraphServiceClient GetGraphClient(string token)
        
            return new GraphServiceClient(
                "https://graph.microsoft.com/beta", new DelegateAuthenticationProvider(async (request) =>
                
                request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", token);
                await Task.FromResult<object>(null);
                
            ));
        

protected override async Task OnInitializedAsync()

   string token = null;
   try
   
      var authenticationState = await authenticationStateTask;
      if (authenticationState.User.Identity.IsAuthenticated)
      
         token = await TokenAcquisitionService.GetAccessTokenForUserAsync("User.Read").ConfigureAwait(false);
         GraphClient = Client.GetGraphClient(token);
         User = await graph.Me.Request().GetAsync();
      
   
   catch (Exception ex)
   
      // This is the error I get, sometimes the above code executes OK and able to pull MS Graph user data, other times I get the error
      // "IDW10502: An MsalUiRequiredException was thrown due to a challenge for the user. See https://aka.ms/ms-id-web/ca_incremental-consent. "

      Debug.WriteLine($"Token: token");
      ConsentHandler.HandleException(ex);
   


对此的任何帮助将不胜感激!

【问题讨论】:

【参考方案1】:

使用位于 Microsoft 网站 Microsoft identity platform code samples (v2.0 endpoint) 上的项目,自己设法找到解决我自己问题的方法,查找 Web 应用程序 --> 语言/ 平台 --> Blazor --> 调用 Microsoft Graph 并点击下载项目。否则这里是直接链接ms-identity-blazor-server

在我的 startup.cs 类中添加了以下内容:-

public void ConfigureServices(IServiceCollection services)

string[] initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');

  wtSecurityTokenHandler.DefaultMapInboundClaims = false;
  services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
     .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
     .EnableTokenAcquisitionToCallDownstreamApi(initialScopes) 
     .AddMicrosoftGraph(Configuration.GetSection("initialScopes"))
     .AddInMemoryTokenCaches();

在我的 index.razor 页面中:-

@page "/"

@using Microsoft.Identity.Web
@using Microsoft.Graph
@inject Microsoft.Graph.GraphServiceClient GraphServiceClient
@inject MicrosoftIdentityConsentAndConditionalAccessHandler ConsentHandler

@page "/"
<p>Help!!!</p>

在我的 index.razor.cs 类中:-

/// The User constructor
public User user  get; set; 

private GraphServiceClient GraphClient  get; set; 

protected override async Task OnInitializedAsync()

  User = await GraphServiceClient.Me.Request().GetAsync();     

在我的 appsettings.json 中

"DownstreamApi": 
    "BaseUrl": "https://graph.microsoft.com/beta",
    "Scopes": "User.Read"
  ,

【讨论】:

以上是关于Microsoft Graph API - Blazor Server App .NET 5.0 使用 Azure 身份验证,MsalUiRequiredException 因用户质询而引发的主要内容,如果未能解决你的问题,请参考以下文章

获取 Microsoft Graph API 的有效访问令牌

Microsoft Graph API SharePoint 文件搜索

如何使用 microsoft graph api 获取 EndRecurrenceDate

Microsoft Graph API - 列出用户登录的所有权限/范围

Microsoft Graph REST API 来更新 Microsoft Planner 任务?

Microsoft graph api预订-与onlinemeeting集成