C# AuthenticationStateProvider GetAuthenticationStateAncy返回空ClaimsPrincipal

C# AuthenticationStateProvider GetAuthenticationStateAncy返回空ClaimsPrincipal,c#,asynchronous,async-await,azure-ad-b2c,blazor-server-side,C#,Asynchronous,Async Await,Azure Ad B2c,Blazor Server Side,我的服务器端Blazor.net 5.0应用程序使用Azure AD B2C进行身份验证 用户登录后,我们会向用户显示一条欢迎他的消息。然而,我们随机看到系统返回“匿名”而不是登录用户,即使用户已经登录 社区能否查看代码,看看我是否遗漏了什么 SecurityService.cs: public class SecurityService { ApplicationUser applicationUser; public ApplicationUser Application

我的服务器端Blazor.net 5.0应用程序使用Azure AD B2C进行身份验证

用户登录后,我们会向用户显示一条欢迎他的消息。然而,我们随机看到系统返回“匿名”而不是登录用户,即使用户已经登录

社区能否查看代码,看看我是否遗漏了什么

SecurityService.cs:

public class SecurityService
  {
    ApplicationUser applicationUser;
    public ApplicationUser ApplicationUser
    {
      get
      {
        if (ClaimsPrincipal == null)
        {
          return new ApplicationUser() { Name = "Anonymous" };
        }
        return applicationUser;
      }
    }
    private ClaimsPrincipal ClaimsPrincipal { get; set; }
    public async Task<bool> InitializeAsync(AuthenticationStateProvider authenticationStateProvider)
    {
      var authenticationState = await authenticationStateProvider.GetAuthenticationStateAsync();
      ClaimsPrincipal = authenticationState.User;<= this returns null randomly, but why? 

      var name = ClaimsPrincipal?.FindFirstValue("name");
      if (applicationUser == null && (name != null))
      {
        applicationUser = new ApplicationUser { Name = name};
      }
      var result = IsAuthenticated();
      if (result)
      {
        Authenticated?.Invoke();
      }
      return result;
    }
Hello, @(SecurityService.ApplicationUser.Name)
[Inject] protected ISecurityService SecurityService { get; set; }
    public class Startup
        {
            public virtual void ConfigureServices(IServiceCollection services)
            {
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(configuration.GetSection("AzureAdB2C"));
    services.AddScoped<ISecurityService, SecurityService>();
            services.Configure<AzureADB2C>(configuration.GetSection("AzureADB2C"));
    }
    }
{
  "AzureADB2C": {
    "Instance": "https://InstaTranscribe.b2clogin.com/",
    "Domain": "InstaTranscribe.onmicrosoft.com",
    "ClientId": "<ClientId>",
    "TenantId": "<TenantId>",
    "SignUpSignInPolicyId": "B2C_1_SignUpSignInUserFlow",
    "ResetPasswordPolicyId": "B2C_1_PasswordResetUserFlow",
    "EditProfilePolicyId": "B2C_1_ProfileEditingUserFlow",
    "CallbackPath": "/signin-oidc",
    "RedirectUri": "http://localhost:20001/signin-oidc",
    "ClientSecret": "<ClientSecret>"
  },
<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                  <NotAuthorized>
                <RedirectToLogin IsAuthenticated="@context.User.Identity.IsAuthenticated" />
              </NotAuthorized>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>
@inject NavigationManager NavigationManager
@using DataAccess.Models;
@code {
  [Parameter]
  public bool IsAuthenticated { get; set; }

  protected override void OnInitialized()
  {
    if (!IsAuthenticated)
    {
      NavigationManager.NavigateTo(Pages.AccountLogin, true);
    }
    else
    {
      NavigationManager.NavigateTo(Pages.Unauthorized, true);
    }
  }
}
MainLayout.razor.cs:

public class SecurityService
  {
    ApplicationUser applicationUser;
    public ApplicationUser ApplicationUser
    {
      get
      {
        if (ClaimsPrincipal == null)
        {
          return new ApplicationUser() { Name = "Anonymous" };
        }
        return applicationUser;
      }
    }
    private ClaimsPrincipal ClaimsPrincipal { get; set; }
    public async Task<bool> InitializeAsync(AuthenticationStateProvider authenticationStateProvider)
    {
      var authenticationState = await authenticationStateProvider.GetAuthenticationStateAsync();
      ClaimsPrincipal = authenticationState.User;<= this returns null randomly, but why? 

      var name = ClaimsPrincipal?.FindFirstValue("name");
      if (applicationUser == null && (name != null))
      {
        applicationUser = new ApplicationUser { Name = name};
      }
      var result = IsAuthenticated();
      if (result)
      {
        Authenticated?.Invoke();
      }
      return result;
    }
Hello, @(SecurityService.ApplicationUser.Name)
[Inject] protected ISecurityService SecurityService { get; set; }
    public class Startup
        {
            public virtual void ConfigureServices(IServiceCollection services)
            {
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(configuration.GetSection("AzureAdB2C"));
    services.AddScoped<ISecurityService, SecurityService>();
            services.Configure<AzureADB2C>(configuration.GetSection("AzureADB2C"));
    }
    }
{
  "AzureADB2C": {
    "Instance": "https://InstaTranscribe.b2clogin.com/",
    "Domain": "InstaTranscribe.onmicrosoft.com",
    "ClientId": "<ClientId>",
    "TenantId": "<TenantId>",
    "SignUpSignInPolicyId": "B2C_1_SignUpSignInUserFlow",
    "ResetPasswordPolicyId": "B2C_1_PasswordResetUserFlow",
    "EditProfilePolicyId": "B2C_1_ProfileEditingUserFlow",
    "CallbackPath": "/signin-oidc",
    "RedirectUri": "http://localhost:20001/signin-oidc",
    "ClientSecret": "<ClientSecret>"
  },
<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                  <NotAuthorized>
                <RedirectToLogin IsAuthenticated="@context.User.Identity.IsAuthenticated" />
              </NotAuthorized>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>
@inject NavigationManager NavigationManager
@using DataAccess.Models;
@code {
  [Parameter]
  public bool IsAuthenticated { get; set; }

  protected override void OnInitialized()
  {
    if (!IsAuthenticated)
    {
      NavigationManager.NavigateTo(Pages.AccountLogin, true);
    }
    else
    {
      NavigationManager.NavigateTo(Pages.Unauthorized, true);
    }
  }
}
Startup.cs:

public class SecurityService
  {
    ApplicationUser applicationUser;
    public ApplicationUser ApplicationUser
    {
      get
      {
        if (ClaimsPrincipal == null)
        {
          return new ApplicationUser() { Name = "Anonymous" };
        }
        return applicationUser;
      }
    }
    private ClaimsPrincipal ClaimsPrincipal { get; set; }
    public async Task<bool> InitializeAsync(AuthenticationStateProvider authenticationStateProvider)
    {
      var authenticationState = await authenticationStateProvider.GetAuthenticationStateAsync();
      ClaimsPrincipal = authenticationState.User;<= this returns null randomly, but why? 

      var name = ClaimsPrincipal?.FindFirstValue("name");
      if (applicationUser == null && (name != null))
      {
        applicationUser = new ApplicationUser { Name = name};
      }
      var result = IsAuthenticated();
      if (result)
      {
        Authenticated?.Invoke();
      }
      return result;
    }
Hello, @(SecurityService.ApplicationUser.Name)
[Inject] protected ISecurityService SecurityService { get; set; }
    public class Startup
        {
            public virtual void ConfigureServices(IServiceCollection services)
            {
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(configuration.GetSection("AzureAdB2C"));
    services.AddScoped<ISecurityService, SecurityService>();
            services.Configure<AzureADB2C>(configuration.GetSection("AzureADB2C"));
    }
    }
{
  "AzureADB2C": {
    "Instance": "https://InstaTranscribe.b2clogin.com/",
    "Domain": "InstaTranscribe.onmicrosoft.com",
    "ClientId": "<ClientId>",
    "TenantId": "<TenantId>",
    "SignUpSignInPolicyId": "B2C_1_SignUpSignInUserFlow",
    "ResetPasswordPolicyId": "B2C_1_PasswordResetUserFlow",
    "EditProfilePolicyId": "B2C_1_ProfileEditingUserFlow",
    "CallbackPath": "/signin-oidc",
    "RedirectUri": "http://localhost:20001/signin-oidc",
    "ClientSecret": "<ClientSecret>"
  },
<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                  <NotAuthorized>
                <RedirectToLogin IsAuthenticated="@context.User.Identity.IsAuthenticated" />
              </NotAuthorized>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>
@inject NavigationManager NavigationManager
@using DataAccess.Models;
@code {
  [Parameter]
  public bool IsAuthenticated { get; set; }

  protected override void OnInitialized()
  {
    if (!IsAuthenticated)
    {
      NavigationManager.NavigateTo(Pages.AccountLogin, true);
    }
    else
    {
      NavigationManager.NavigateTo(Pages.Unauthorized, true);
    }
  }
}