AuthenticationStateProvider is null

Prathamesh Shende 381 Reputation points
2022-09-18T14:00:46.777+00:00

I have created the project on blazor Server-Side and It will authenticating from another project of Identity Server 4.
If I visit the website it redirect me to authenticate (IS4 project) and after login it will get back to website but the I cannot see the who is authenticated. The AutheticationStateProvider is null and also IHttpContextAccessor also null/empty.

index.razor (blazor Server-Side)

@inject AuthenticationStateProvider auth
@inject IHttpContextAccessor httpContextAccessor

   var user_auth = await auth.GetAuthenticationStateAsync();  
   string Name = user_auth.User.Identity.Name;  
   string AccName = "acc" + httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(a=> a.Type == "email").Value;  

What is the issue?

Thanks

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,552 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Michael Washington 911 Reputation points MVP
    2022-09-18T15:16:42.293+00:00

    In your Program.cs file ensure you have:

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

  2. Prathamesh Shende 381 Reputation points
    2022-09-18T17:04:06.847+00:00

    this my program.cs

    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://localhost:7065/") });

    builder.Services.AddBlazoredLocalStorage(config =>
    config.JsonSerializerOptions.WriteIndented = true);
    builder.Services.AddBlazoredSessionStorage(config =>
    config.JsonSerializerOptions.WriteIndented = true);

    region authentication

    builder.Services.AddAuthentication(options =>
    {
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme,
    options =>
    {
    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.SignOutScheme = OpenIdConnectDefaults.AuthenticationScheme;

                        options.Authority = builder. Configuration["OIDC:Authority"];  
    
                        options.ClientId = builder. Configuration["OIDC:ClientId"];  
    
                        options.ClientSecret = builder.Configuration["OIDC:ClientSecret"];  
    
                        options.CallbackPath = builder.Configuration["OIDC:RedirectUri"];  
    
                        options.SignedOutCallbackPath = builder.Configuration["OIDC:PostLogoutRedirectUri"];  
    
                        options.ResponseType = "code";  
    
                        options.Scope.Add("openid");  
                        options.Scope.Add("profile");  
                        options.Scope.Add("email");  
    
                        options.SaveTokens = true;  
    
                        options.GetClaimsFromUserInfoEndpoint = true;  
                        options.TokenValidationParameters = new TokenValidationParameters  
                        {  
    
                            NameClaimType = "email"  
                        };  
    
                        options.Events = new OpenIdConnectEvents  
                        {  
                            OnAccessDenied = context =>  
                            {  
                                context.HandleResponse();  
                                context.Response.Redirect("/");  
                                return Task.CompletedTask;  
                            }  
                        };  
                    });  
    

    builder.Services.AddAuthorization(options =>
    {
    options.FallbackPolicy = options.DefaultPolicy;
    });
    builder.Services.AddHttpContextAccessor();
    builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    endregion

    builder.Services.AddRazorPages();
    builder.Services.AddServerSideBlazor();

    region services

    builder.Services.AddScoped<IWorksService, WorksService>();

    endregion

    var app = builder. Build();

    if (!app.Environment.IsDevelopment())
    {
    app.UseExceptionHandler("/Error");

    app.UseHsts();  
    

    }

    app.UseHttpsRedirection();

    app.UseStaticFiles();

    app.UseRouting();

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

    app.MapBlazorHub();
    app.MapFallbackToPage("/_Host");

    app.Run();

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.