asp.net-coreoauthopenidasp.net-core-8

ASP.NET Core 8 using open id failed to authenticate the Cookie scheme


I'm just started a new project that uses fusion auth as authentiction provider (later also keycloak) Currently I only have the base boiler code of the asp.net core 8 poject, where I also included the config for openid


var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("SampleIdentityDbContextConnection") ?? throw new InvalidOperationException("Connection string 'MagicShareIdentityDbContextConnection' not found.");

builder.Services.AddDbContext<MagicShareIdentityDbContext>(options => options.UseSqlServer(connectionString));

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<MagicShareIdentityDbContext>();

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie(options =>
    {
        options.LoginPath = "/Account/Login";
    })
    .AddOpenIdConnect(options =>
    {
        options.Authority = builder.Configuration["SampleApp:Authority"];
        options.ClientId = builder.Configuration["SampleApp:ClientId"];
        options.ClientSecret = builder.Configuration["SampleApp:ClientSecret"];
        options.ResponseType = "code";
        options.SaveTokens = true;
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "preferred_username",
            RoleClaimType = "roles",
        };
    });


var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    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.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapRazorPages();

IdentityModelEventSource.ShowPII = true;
app.Run();

But right at the start I see this message in the logs Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler: Debug: AuthenticationScheme: Cookies was not authenticated.

and the user informations are not stored in the cookies

Log of login:

dbug: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[9]
      AuthenticationScheme: Cookies was not authenticated.
dbug: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[9]
      AuthenticationScheme: Cookies was not authenticated.
trce: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[4]
      Entering Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler's HandleUnauthorizedAsync.
trce: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[5]
      Using properties.RedirectUri for 'local redirect' post authentication: '/Identity/Account/ExternalLogin?returnUrl=%2F&handler=Callback'.
dbug: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[53]
      HandleChallenge with Location: https://....B1ZdqdwTVV5cnhEH1EWoYoPj5CH_0AeI=N; expires=Tue, 20 Feb 2024 12:33:53 GMT; path=/signin-oidc; secure; samesite=none; httponly,.AspNetCore.Correlation.Ky-hv-7NZiA_E7ij2KKpHSoFROsN7sfrQSJU5Axp1W4=N; expires=Tue, 20 Feb 2024 12:33:53 GMT; path=/signin-oidc; secure; samesite=none; httponly.
info: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[12]
      AuthenticationScheme: OpenIdConnect was challenged.
trce: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[9]
      Entering Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler's HandleRemoteAuthenticateAsync.
trce: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[24]
      MessageReceived: '?code=MQgGYb5k9GSCeYKSW75Y4O5-A-mtFsx8pGSGVuuqan8&locale=en&userState=Authenticated'.
dbug: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[13]
      Updating configuration
trce: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[27]
      Authorization code received.
dbug: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[19]
      Redeeming code for tokens.
trce: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[30]
      Token response received.
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[10]
      AuthenticationScheme: Identity.External signed in.
dbug: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[9]
      AuthenticationScheme: Cookies was not authenticated.
dbug: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[8]
      AuthenticationScheme: Identity.External was successfully authenticated.
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[11]
      AuthenticationScheme: Identity.External signed out.
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[10]
      AuthenticationScheme: Identity.Application signed in.
info: MagicShare.Areas.Identity.Pages.Account.ExternalLoginModel[0]
      eagleeye logged in with OpenIdConnect provider.
dbug: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[9]
      AuthenticationScheme: Cookies was not authenticated.
dbug: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[9]
      AuthenticationScheme: Cookies was not authenticated.
```heme: Cookies was not authenticated.

Solution

  • I manged to solve it by using JWT

        .AddJwtBearer()
        .AddOpenIdConnect(options =>
        {
            options.Authority = builder.Configuration["LoginProvider:Authority"];
            options.ClientId = builder.Configuration["LoginProvider:ClientId"];
            options.ClientSecret = builder.Configuration["LoginProvider:ClientSecret"];
            options.ResponseType = "code";
            options.SaveTokens = true;
            options.Scope.Add("openid");
            options.Scope.Add("profile");
            options.RequireHttpsMetadata = false;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = "preferred_username",
                RoleClaimType = "roles",
            };
        });