Blazor WASM-AzureAD身份验证-HttpContext.User.Claims是否为空?

时间:2020-08-19 19:28:54

标签: azure-active-directory asp.net-identity microsoft-graph-api blazor

我正在尝试在我正在构建的Blazor WASM应用程序上为我的身份平台切换到Azure AD。我非常关注Microsoft的this documentation

当我登录到应用程序时,客户端应用程序能够显示登录的用户名,该用户名来自AuthenticationState对象。

但是,在服务器端,当我发送HTTP请求(例如,发表评论)时,HttpContext.User.Claims为空,而我之前用来获取userId的以下行返回null:< / p>

comment.UserId = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier); 

我对理赔/身份/ Microsoft Graph等表示了一些无知,但我仍然不知道为什么用户/理赔会是未知的,因为至少在某一时刻可以访问此信息,因为客户端应用程序能够显示用户名...

我也查看了以下StackOverflow / GitHub帖子,但未找到任何解决此问题的方法:

在此无法识别传入的HTTP请求中的用户吗?

FWIW,这是我的Startup.cs类(发出了一些不相关的代码):

    public void ConfigureServices(IServiceCollection services)
    {
        #region Azure Active Directory
        services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
            .AddAzureADBearer(options => {
                Configuration.Bind("AzureAd", options);                 
            }
        );
        #endregion

        services.Configure<JwtBearerOptions>(
            AzureADDefaults.JwtBearerAuthenticationScheme, options =>
            {
                options.TokenValidationParameters.NameClaimType = "name";
                //options.TokenValidationParameters.NameClaimType = "preferred_username";
            });

        services.AddHttpContextAccessor();
        services.AddControllersWithViews().AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
        services.AddRazorPages();
    }

和Configure():

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseHttpsRedirection();
        app.UseBlazorFrameworkFiles();
        app.UseStaticFiles();

        app.UseRouting();

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

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllers();
            endpoints.MapFallbackToFile("index.html");
        });
    }

1 个答案:

答案 0 :(得分:1)

问题在于,删除/不为客户端ID加上“ api://”方案会导致其由于某种原因而无法填充声明。很奇怪。 Scope documentation