我刚刚启动了一个新项目,该项目使用 fusion auth 作为身份验证提供程序(后来也使用 keycloak) 目前我只有 asp.net core 8 项目的基本锅炉代码,其中我还包含了 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();
但是一开始我就在日志中看到这条消息 Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:调试:AuthenticationScheme:Cookie 未经过身份验证。
并且用户信息不存储在cookie中
登录日志:
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.
我设法使用 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",
};
});