You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 7应用构建触发MsalUiRequiredException(user_null)错误求助

问题:构建应用时触发MsalUiRequiredException(user_null错误)

错误日志

fail: Microsoft.Identity.Web.TokenAcquisition[0]
      False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.0 Microsoft Windows 10.0.19043 Exception type: Microsoft.Identity.Client.MsalUiRequiredException
      , ErrorCode: user_null
      HTTP StatusCode 0
      CorrelationId

         at Microsoft.Identity.Client.Internal.Requests.Silent.SilentRequest.ExecuteAsync(CancellationToken cancellationToken)
         at Microsoft.Identity.Client.Internal.Requests.Silent.SilentRequest.ExecuteAsync(CancellationToken cancellationToken)
         at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)

背景信息

应用基于Azure AD ASP.NET Core WebApp调用MS Graph的官方示例项目构建,整体运行基本正常,但存在两个问题:

  1. 每次构建都会触发上述MsalUiRequiredException错误(错误码user_null)
  2. 此前还出现令牌约1小时后无法自动刷新的问题,该问题疑似为.NET 7的bug

Startup类代码

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        
    }

    public IConfiguration Configuration { get; }
    
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Get the scopes from the configuration (appsettings.json)
        var initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
        
        // Add sign-in with Microsoft
        services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))

            // Add the possibility of acquiring a token to call a protected web API
            .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)

            // Enables controllers and pages to get GraphServiceClient by dependency injection
            // And use an in memory token cache
            .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
            .AddDistributedTokenCaches();



        // Register AadService and PbiEmbedService for dependency injection
        services.AddScoped(typeof(AadService))
                .AddScoped(typeof(PbiEmbedService))
                .AddScoped(typeof(PowerBiServiceApi));

        services.AddControllersWithViews(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        });

        // Enables a UI and controller for sign in and sign out.
        services.AddRazorPages()
            .AddMicrosoftIdentityUI();
        
        // Session/cookie variables etc

        services.AddDistributedMemoryCache();
        services.AddSession();
        
        
        // Loading appsettings.json in C# Model classes
        services.Configure<AzureAd>(Configuration.GetSection("AzureAd"))
                .Configure<PowerBI>(Configuration.GetSection("PowerBI"));
        
        // Add the UI support to handle claims challenges
        services.AddServerSideBlazor()
            .AddMicrosoftIdentityConsentHandler();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseSession();
        
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });
    }
}

HomeController类代码

[Authorize]
public class HomeController : Controller
{
    public IConfiguration Configuration { get; }
    private readonly GraphServiceClient _graphServiceClient;

    public HomeController(IConfiguration configuration,
                            GraphServiceClient graphServiceClient)
    {
        Configuration = configuration;
        _graphServiceClient = graphServiceClient;
    }
    [AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
    public Task<IActionResult> Index()
    {
        var graphUser = _graphServiceClient.Me.Request().GetAsync();
        var datasource = Configuration["AzureDB:Datasource"];
        var username = Configuration["AzureDB:Username"];
        var password = Configuration["AzureDB:Password"];
        var database = Configuration["AzureDB:Database"];
        var user = new Userclass(graphUser.Result, datasource, username, password, database);
        Console.WriteLine(user.ProjectName);
        if (!user.ProjectName.IsNullOrEmpty())
        {
            HttpContext.Session.SetString("MyProject", user.ProjectName);
        }else{
            
            /*HttpContext.Session.SetString("MyProject", "No Project");*/
        }
        
        /*var user = _graphServiceClient.Me.Request().GetAsync();
        Console.WriteLine(user.Result.DisplayName);*/
        return Task.FromResult<IActionResult>(View());
    }
    [AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
    public async Task<IActionResult> Profile()
    {

        var user = await _graphServiceClient.Me.Request().GetAsync();
        

        return View(user);
    }
}

内容的提问来源于stack exchange,提问作者crissb3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 14:20:27