为了测试和娱乐,我创建了一个默认的 ASP.NET Core 8 Blazor Web 应用程序,其中包含用于身份验证的个人帐户,并向其中添加了我的 keycloak。在 keycloak 中,用户可以拥有自定义属性,例如他们工作的地方 (cegnev)。如何使我的 ASP.NET Core 应用程序将该数据保存到其数据库中?
这是我修改过的
ApplicationUser
:
using Microsoft.AspNetCore.Identity;
namespace TesztBlazorAuth.Data
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
public string cegnev { get; set; }
}
}
Program.cs
:
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using TesztBlazorAuth.Components;
using TesztBlazorAuth.Components.Account;
using TesztBlazorAuth.Data;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.Extensions.Options;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped<IdentityUserAccessor>();
builder.Services.AddScoped<IdentityRedirectManager>();
builder.Services.AddScoped<AuthenticationStateProvider, IdentityRevalidatingAuthenticationStateProvider>();
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = IdentityConstants.ApplicationScheme;
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddIdentityCookies();
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddSignInManager()
.AddDefaultTokenProviders();
builder.Services.AddSingleton<IEmailSender<ApplicationUser>, IdentityNoOpEmailSender>();
builder.Services.AddAuthentication()
.AddGoogle(options =>
{
options.ClientId = configuration["GoogleAuth:id"];
options.ClientSecret = configuration["GoogleAuth:secret"];
})
.AddOpenIdConnect("Keycloak", "CorpAuth", options =>
{
options.Authority = $"{configuration["Keycloak:auth-server-url"]}realms/{configuration["Keycloak:realm"]}";
options.ClientId = configuration["Keycloak:resource"];
options.ClientSecret = configuration["Keycloak:credentials:secret"];
options.ResponseType = "code";
options.SaveTokens = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true
};
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
options.Scope.Add("phone");
options.Scope.Add("cegnev");
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// 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.UseAuthentication();
app.UseAuthorization();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
// Add additional endpoints required by the Identity /Account Razor components.
app.MapAdditionalIdentityEndpoints();
app.UseAntiforgery();
app.Run();
用户应该在数据库中拥有来自 keyclaok 的
cegnev
。
AddOpenIdConnect 中有事件处理程序,您可以插入它们,以捕获来自 KeyCloak 的所有声明,然后将它们保存到本地数据库。
请参阅此处记录的 OpenIdConnectEvents 类:
这是一个例子:
.AddOpenIdConnect(o =>
{
//Additional config snipped
o.Events = new OpenIdConnectEvents
{
OnTokenValidated = async ctx =>
{
...
}
};
});