chore: remove .opencode submodule, now using global opencode-infra plugin

All shared agents, skills, commands, rules are now provided by the
opencode-infra plugin installed globally at ~/.config/opencode/plugins/.
No per-project configuration needed.
This commit is contained in:
Arnaud Dartois committed 2026-08-01 07:58:35 +00:00
1 parent 094567234f
commit 8e14d72a9a
4 files changed
+879 -5

No files matched your search

-4
View File
@@ -1,4 +0,0 @@
[submodule ".opencode"]
path = .opencode
url = https://forgejo.tordais.cc/nonobis/opencode.git
branch = main
Submodule .opencode deleted from dac28a8733.
@@ -0,0 +1,788 @@
# Zitadel Migration — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use subagent-driven-development to implement this plan task-by-task.
**Goal:** Replace all Microsoft Identity traces with Zitadel OIDC + gRPC management.
**Architecture:** Zitadel (Docker self-hosted) devient l'identity provider unique. Heimdall utilise OIDC pour l'auth et l'API gRPC Zitadel pour le user management. Les données métier (sites, groupes, préférences) restent en local avec userId string.
**Tech Stack:** Zitadel v2.x (Docker), smartive/zitadel-net v7.0.44, ASP.NET Core OIDC, gRPC
## Global Constraints
- Supprimer TOUTE trace de Microsoft Identity (namespace, packages, héritage)
- .NET 10 — toutes les migrations targettent net10.0
- PostgreSQL — base de données existante
- Approche C — aucun user store local, Zitadel est la seule source de vérité pour users/roles
- Les commits doivent être atomiques et indépendants
---
### Commit 1: Docker Compose Zitadel + Documentation Configuration
**Files:**
- Create: `docker/zitadel/docker-compose.yml`
- Create: `docker/zitadel/.env.example`
- Create: `docs/zitadel-configuration.md`
**Description:** Infrastructure Zitadel self-hosted + documentation de configuration des rôles Heimdall.
- [ ] **Step 1: Créer docker/zitadel/docker-compose.yml**
```yaml
version: "3.8"
services:
zitadel:
image: ghcr.io/zitadel/zitadel:latest
command: start-from-init --masterkey "${ZITADEL_MASTERKEY}" --tlsMode disabled
environment:
- ZITADEL_DATABASE_POSTGRES_HOST=postgres
- ZITADEL_DATABASE_POSTGRES_PORT=5432
- ZITADEL_DATABASE_POSTGRES_DATABASE=zitadel
- ZITADEL_DATABASE_POSTGRES_USER=${POSTGRES_USER:-zitadel}
- ZITADEL_DATABASE_POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
- ZITADEL_DATABASE_POSTGRES_ADMIN_USERNAME=${POSTGRES_USER:-zitadel}
- ZITADEL_DATABASE_POSTGRES_ADMIN_PASSWORD=${POSTGRES_PASSWORD}
- ZITADEL_EXTERNALSECURE=false
- ZITADEL_EXTERNALDOMAIN=${ZITADEL_DOMAIN:-localhost}
- ZITADEL_EXTERNALPORT=8080
ports:
- "8080:8080"
depends_on:
postgres:
condition: service_healthy
restart: unless-stopped
postgres:
image: postgres:16-alpine
environment:
- POSTGRES_USER=${POSTGRES_USER:-zitadel}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
- POSTGRES_DB=zitadel
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-zitadel}"]
interval: 10s
timeout: 5s
retries: 5
volumes:
- pgdata:/var/lib/postgresql/data
restart: unless-stopped
volumes:
pgdata:
```
- [ ] **Step 2: Créer docker/zitadel/.env.example**
```bash
ZITADEL_MASTERKEY=ChangeMeToAtLeast32BytesLongKey!
POSTGRES_USER=zitadel
POSTGRES_PASSWORD=ChangeMeToAtLeast16Bytes!
ZITADEL_DOMAIN=localhost
```
- [ ] **Step 3: Créer docs/zitadel-configuration.md**
Document complet incluant :
1. Démarrage Zitadel : `docker compose -f docker/zitadel/docker-compose.yml up -d`
2. Accès UI : http://localhost:8080 — créer le premier admin (org IAM)
3. Créer une Organization "Heimdall"
4. Créer un Project "Heimdall"
5. Créer les Applications :
- **Heimdall Web** (OIDC, Auth Code + PKCE) → callback URL `http://localhost:5000/signin-oidc`
- **Heimdall API** (OIDC, JWT) → pour les appels API REST
- **Heimdall Management** (service account) → pour le user management gRPC
6. Créer les **Project Roles** :
- `admin` → Toutes les permissions
- `supervisor` → Lecture + écriture limitée
- `viewer` → Lecture seule
7. Créer les users Zitadel manuellement via l'UI ou l'API
8. Assigner les rôles aux users dans le projet Heimdall
9. Configuration des claims JWT : `sub`, `email`, `name`, `role` (custom claim)
10. Note : Zitadel map les rôles projet dans le claim `urn:zitadel:iam:org:project:roles`
```markdown
# Configuration Zitadel pour Heimdall
## Rôles Heimdall dans Zitadel
| Role Zitadel | Permissions Heimdall |
|---|---|
| admin | Site.Read, Site.Write, Site.Delete, Camera.Read, Camera.Write, Camera.Live, Camera.Record, Camera.Snapshot, Event.Read, Person.Read, Person.Write, Admin.Manage, Admin.Users, Admin.ApiKeys, Admin.Jobs |
| supervisor | Site.Read, Camera.Read, Camera.Write, Camera.Live, Camera.Record, Camera.Snapshot, Event.Read, Person.Read, Person.Write |
| viewer | Site.Read, Camera.Read, Camera.Live, Event.Read, Person.Read |
## Mapping JWT → Claims ASP.NET Core
Le claim Zitadel `urn:zitadel:iam:org:project:roles` contient la map des rôles.
Dans le middleware OIDC, on transforme en claim `role` pour compatibilité.
## Configuration .NET requise
```json
{
"Zitadel": {
"Authority": "http://localhost:8080",
"WebClientId": "... (issu de l'app OIDC) ...",
"ApiClientId": "... (issu de l'app JWT) ...",
"ApiClientSecret": "...",
"ManagementServiceAccountJson": "{...}"
}
}
```
```
- [ ] **Step 4: Commit**
```bash
git add docker/zitadel/ docs/zitadel-configuration.md
git commit -m "feat(zitadel): add Docker Compose setup and configuration docs"
```
---
### Commit 2: Nettoyage Domain + Packages
**Files:**
- Modify: `src/Heimdall.Domain/Heimdall.Domain.csproj` — remove Identity package
- Delete: `src/Heimdall.Domain/Entities/AppUser.cs`
- Delete: `src/Heimdall.Domain/Entities/AppRole.cs`
- Create: `src/Heimdall.Domain/Entities/UserPreferences.cs`
- Modify: `src/Heimdall.Domain/Entities/UserSite.cs` — userId Guid→string
- Modify: `src/Heimdall.Domain/Entities/UserGroup.cs` — userId Guid→string
- Modify: `src/Heimdall.Application/Heimdall.Application.csproj` — remove Identity, add Zitadel
- Modify: `src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj` — remove Identity/Jwt/DataProtection, add Zitadel NuGet
- Modify: `src/Heimdall.Web/Heimdall.Web.csproj` — remove DataProtection ref if any
- [ ] **Step 1: Update .csproj files**
Supprimer de TOUS les .csproj :
- `Microsoft.AspNetCore.Identity.EntityFrameworkCore`
Ajouter dans `Heimdall.Infrastructure.csproj` :
```xml
<PackageReference Include="Zitadel" Version="7.0.44" />
<PackageReference Include="Google.Protobuf" Version="3.28.0" />
<PackageReference Include="Grpc.Net.Client" Version="2.66.0" />
```
Supprimer de `Heimdall.Infrastructure.csproj` :
- `Microsoft.AspNetCore.Identity.EntityFrameworkCore`
- `Microsoft.AspNetCore.Authentication.JwtBearer`
- `Microsoft.AspNetCore.DataProtection.Extensions`
- [ ] **Step 2: Delete AppUser.cs** — tout le fichier
- [ ] **Step 3: Delete AppRole.cs** — tout le fichier
- [ ] **Step 4: Create UserPreferences.cs**
```csharp
namespace Heimdall.Domain.Entities;
public class UserPreferences
{
public string UserId { get; set; } = string.Empty;
public string DisplayName { get; set; } = string.Empty;
public string Theme { get; set; } = "Auto";
public string Language { get; set; } = "fr";
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
private UserPreferences() { }
public UserPreferences(string userId, string displayName)
{
UserId = userId;
DisplayName = displayName;
}
}
```
- [ ] **Step 5: Update UserSite.cs** — userId de Guid à string
- [ ] **Step 6: Update UserGroup.cs** — userId de Guid à string
- [ ] **Step 7: Create IZitadelUserService.cs** dans Application/Common/Interfaces
```csharp
namespace Heimdall.Application.Common.Interfaces;
public record ZitadelUserInfo(
string UserId,
string Email,
string DisplayName,
List<string> Roles);
public interface IZitadelUserService
{
Task<ZitadelUserInfo> GetUserByIdAsync(string userId, CancellationToken ct = default);
Task<ZitadelUserInfo> GetUserByEmailAsync(string email, CancellationToken ct = default);
Task<string> CreateUserAsync(string email, string displayName, string? password, CancellationToken ct = default);
Task UpdateUserAsync(string userId, string? email, string? displayName, CancellationToken ct = default);
Task DeleteUserAsync(string userId, CancellationToken ct = default);
Task<List<ZitadelUserInfo>> ListUsersAsync(CancellationToken ct = default);
Task AssignRolesAsync(string userId, List<string> roles, CancellationToken ct = default);
Task LockUserAsync(string userId, CancellationToken ct = default);
Task UnlockUserAsync(string userId, CancellationToken ct = default);
Task SendPasswordResetAsync(string email, CancellationToken ct = default);
}
```
- [ ] **Step 8: Commit**
```bash
git add -A
git commit -m "refactor(domain): remove Identity entities, add UserPreferences, update userId types"
```
---
### Commit 3: Infrastructure Layer — DbContext, Services
**Files:**
- Modify: `src/Heimdall.Infrastructure/Data/AppDbContext.cs` — remove Identity inheritance
- Delete: `src/Heimdall.Infrastructure/Data/Configurations/IdentityConfiguration.cs`
- Modify: `src/Heimdall.Infrastructure/Data/Configurations/UserSiteConfiguration.cs` — userId type
- Modify: `src/Heimdall.Infrastructure/Data/Configurations/UserGroupConfiguration.cs` — userId type
- Create: `src/Heimdall.Infrastructure/Data/Configurations/UserPreferencesConfiguration.cs`
- Create: `src/Heimdall.Infrastructure/Security/ZitadelOptions.cs`
- Create: `src/Heimdall.Infrastructure/Security/ZitadelUserService.cs`
- Delete: `src/Heimdall.Infrastructure/Security/JwtService.cs`
- Delete: `src/Heimdall.Infrastructure/Security/AuthSignInService.cs`
- Delete: `src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs` — **conservé** (pas Identity)
- Delete: `src/Heimdall.Infrastructure/Security/AppPermissions.cs` — **conservé** (map statique)
- Modify: `src/Heimdall.Infrastructure/DependencyInjection.cs`
- [ ] **Step 1: Rewrite AppDbContext.cs**
```csharp
namespace Heimdall.Infrastructure.Data;
public class AppDbContext : DbContext, IApplicationDbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<UserSite> UserSites => Set<UserSite>();
public DbSet<UserGroup> UserGroups => Set<UserGroup>();
public DbSet<UserPreferences> UserPreferences => Set<UserPreferences>();
// ... autres DbSets inchangés (Sites, Cameras, Events, etc.)
protected override void OnModelCreating(ModelBuilder builder)
{
builder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
base.OnModelCreating(builder);
}
}
```
- [ ] **Step 2: Delete IdentityConfiguration.cs**
- [ ] **Step 3: Create UserPreferencesConfiguration.cs**
```csharp
namespace Heimdall.Infrastructure.Data.Configurations;
public class UserPreferencesConfiguration : IEntityTypeConfiguration<UserPreferences>
{
public void Configure(EntityTypeBuilder<UserPreferences> builder)
{
builder.ToTable("user_preferences");
builder.HasKey(x => x.UserId);
builder.Property(x => x.UserId).HasMaxLength(64);
builder.Property(x => x.DisplayName).HasMaxLength(256).IsRequired();
builder.Property(x => x.Theme).HasMaxLength(32).HasDefaultValue("Auto");
builder.Property(x => x.Language).HasMaxLength(8).HasDefaultValue("fr");
}
}
```
- [ ] **Step 4: Update UserSiteConfiguration.cs** — userId column type → nvarchar(64)
- [ ] **Step 5: Update UserGroupConfiguration.cs** — userId column type → nvarchar(64)
- [ ] **Step 6: Create ZitadelOptions.cs**
```csharp
namespace Heimdall.Infrastructure.Security;
public class ZitadelOptions
{
public const string SectionName = "Zitadel";
public string Authority { get; set; } = "http://localhost:8080";
public string WebClientId { get; set; } = string.Empty;
public string ApiClientId { get; set; } = string.Empty;
public string ApiClientSecret { get; set; } = string.Empty;
public string ManagementServiceAccountJson { get; set; } = "{}";
}
```
- [ ] **Step 7: Create ZitadelUserService.cs**
```csharp
namespace Heimdall.Infrastructure.Security;
public class ZitadelUserService : IZitadelUserService, IDisposable
{
private readonly ZitadelOptions _options;
private readonly GrpcChannel _channel;
private readonly AuthService.AuthServiceClient _authClient;
private readonly ManagementService.ManagementServiceClient _managementClient;
public ZitadelUserService(IOptions<ZitadelOptions> options)
{
_options = options.Value;
_channel = GrpcChannel.ForAddress(_options.Authority);
_authClient = new AuthService.AuthServiceClient(_channel);
_managementClient = new ManagementService.ManagementServiceClient(_channel);
}
// Implémente chaque méthode IZitadelUserService avec appels gRPC
// Voir le SDK smartive/zitadel-net pour les appels exacts
}
```
Note: Le SDK smartive/zitadel-net fournit `Clients.AuthService(url, tokenProvider)` et `Clients.ManagementService(url, tokenProvider)`. L'implémentation exacte dépend du SDK.
- [ ] **Step 8: Update DependencyInjection.cs**
```csharp
// Dans AddInfrastructure():
services.AddScoped<IZitadelUserService, ZitadelUserService>();
services.Configure<ZitadelOptions>(context.Configuration.GetSection(ZitadelOptions.SectionName));
// Supprimer :
// services.AddIdentity<AppUser, AppRole>(...)
// services.AddScoped<IJwtService, JwtService>()
// services.AddScoped<IAuthSignInService, AuthSignInService>()
```
- [ ] **Step 9: Commit**
```bash
git add -A
git commit -m "refactor(infrastructure): replace Identity with Zitadel services and DbContext"
```
**Note:** This commit deliberately leaves the build broken (handlers still reference removed types). Next commits fix that.
---
### Commit 4: EF Core Migration — Schema Change
**Files:**
- Run `dotnet ef migrations add RemoveIdentity` in Infrastructure project
- The migration should: drop all 7 Identity tables, create user_preferences
- [ ] **Step 1: Ensure Domain/Infrastructure projects build first** (after deleting Identity refs)
- [ ] **Step 2: Add migration**
```bash
cd src/Heimdall.Infrastructure
dotnet ef migrations add RemoveIdentity
```
- [ ] **Step 3: Review generated migration** — verify Identity tables are dropped, user_preferences created
- [ ] **Step 4: Commit**
```bash
git add src/Heimdall.Infrastructure/Migrations/
git commit -m "feat(db): add migration to remove Identity tables and add user_preferences"
```
---
### Commit 5: Auth Middleware — Program.cs
**Files:**
- Modify: `src/Heimdall.Web/Program.cs` — replace AddIdentity/AddJwtBearer with OIDC+JWKS
- Modify: `src/Heimdall.Web/appsettings.json` — add Zitadel config section
- Modify: All appsettings.*.json if needed
- [ ] **Step 1: Install OpenIdConnect package if not already present**
- [ ] **Step 2: Rewrite auth section in Program.cs**
```csharp
// Au lieu de AddIdentity + AddCookie + AddJwtBearer + AddApiKey:
// 1. OIDC for Blazor (Authorization Code + PKCE)
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.Cookie.Name = ".Heimdall.Auth";
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = SameSiteMode.Lax;
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.ExpireTimeSpan = TimeSpan.FromDays(7);
options.SlidingExpiration = true;
options.LoginPath = "/login";
options.LogoutPath = "/auth/logout";
})
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.Authority = zitadelOptions.Authority;
options.ClientId = zitadelOptions.WebClientId;
options.ResponseType = "code";
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.MapZitadelRolesToClaim(); // Extension custom
});
// 2. JWT Bearer for API (JWKS validation)
builder.Services.AddAuthentication() // Ajoute au lieu de remplacer
.AddJwtBearer("JwtBearer", options =>
{
options.Authority = zitadelOptions.Authority;
options.Audience = zitadelOptions.ApiClientId;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
context.Token = accessToken;
return Task.CompletedTask;
}
};
});
// 3. API Key (conservé, pas Identity)
.AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>("ApiKey", null);
// Authorization policies — inchangé (basé sur claims, compatibles OIDC)
```
- [ ] **Step 3: Add Claim Mapping Extension**
```csharp
// Heimdall.Web/Services/ZitadelClaimsExtensions.cs
public static AuthenticationBuilder MapZitadelRolesToClaims(
this AuthenticationBuilder builder)
{
// Mappe le claim Zitadel des rôles projet vers des claims "role" standards
// Zitadel utilise: urn:zitadel:iam:org:project:roles:{projectId}:{roleName}
// On le transforme en claim "role" pour compatibilité avec AppPermissions
}
```
- [ ] **Step 4: Update appsettings.json**
```json
{
"Zitadel": {
"Authority": "http://localhost:8080",
"WebClientId": "",
"ApiClientId": "",
"ApiClientSecret": "",
"ManagementServiceAccountJson": "{}"
}
}
```
- [ ] **Step 5: Commit**
```bash
git add src/Heimdall.Web/Program.cs src/Heimdall.Web/appsettings.json
git commit -m "feat(auth): replace Identity with Zitadel OIDC and JWKS middleware"
```
---
### Commit 6: Handlers CQRS Auth
**Files:**
- Delete: `src/Heimdall.Application/Auth/Commands/Register/` (register handler, command, validator)
- Delete: `src/Heimdall.Application/Auth/Commands/RegisterAdmin/`
- Rewrite: `src/Heimdall.Application/Auth/Commands/Login/` — devient un appel Zitadel
- Rewrite: `src/Heimdall.Application/Auth/Commands/RefreshToken/` — devient un appel Zitadel
- Delete: `src/Heimdall.Application/Auth/Commands/Verify2fa/` — géré par Zitadel
- Rewrite: `src/Heimdall.Application/Auth/Commands/ChangePassword/`
- Delete: `src/Heimdall.Application/Auth/Commands/ConfirmEmail/` — géré par Zitadel
- Rewrite: `src/Heimdall.Application/Auth/Commands/ForgotPassword/`
- Rewrite: `src/Heimdall.Application/Auth/Commands/ResetPassword/`
- Delete: `src/Heimdall.Application/Auth/Commands/Enable2fa/` — géré par Zitadel
- Delete: `src/Heimdall.Application/Auth/Commands/Disable2fa/` — géré par Zitadel
- Rewrite: `src/Heimdall.Application/Auth/Commands/Logout/`
- [ ] **Step 1: Rewrite LoginHandler**
```csharp
// LoginHandler.cs
// Note: Login devient un proxy OIDC.
// Le formulaire de login redirige vers Zitadel (Authorization Code flow).
// Ce handler gère le post-login : créer UserPreferences si nouveau user, logger l'event.
public class LoginHandler : IRequestHandler<LoginCommand, Result<AuthResponse>>
{
private readonly IZitadelUserService _zitadel;
private readonly IApplicationDbContext _context;
public async Task<Result<AuthResponse>> Handle(LoginCommand request, CancellationToken ct)
{
// Vérifier que l'utilisateur existe dans Zitadel
var user = await _zitadel.GetUserByEmailAsync(request.Email, ct);
if (user == null)
return Result.Fail("Invalid credentials");
// Créer UserPreferences si premier login (l'utilisateur a été créé dans Zitadel via l'admin)
var prefs = await _context.UserPreferences.FindAsync(new object[] { user.UserId }, ct);
if (prefs == null)
{
_context.UserPreferences.Add(new UserPreferences(user.UserId, user.DisplayName));
await _context.SaveChangesAsync(ct);
}
return Result.Ok(new AuthResponse
{
RequiresRedirect = true,
RedirectUrl = "/auth/signin-zitadel"
});
}
}
```
- [ ] **Step 2: Rewrite RegisterHandler** — Appel IZitadelUserService.CreateUserAsync
- [ ] **Step 3: Rewrite ChangePasswordHandler** — Appel IZitadelUserService (mot de passe via Zitadel)
- [ ] **Step 4: Rewrite ForgotPasswordHandler** — Appel IZitadelUserService.SendPasswordResetAsync
- [ ] **Step 5: Rewrite ResetPasswordHandler** — Appel API Zitadel (ou redirection vers Zitadel)
- [ ] **Step 6: Delete 2FA handlers** — Zitadel gère le 2FA
- [ ] **Step 7: Delete ConfirmEmail handler** — Zitadel gère la confirmation d'email
- [ ] **Step 8: Rewrite LogoutHandler** — Invalide la session locale
- [ ] **Step 9: Build && fix errors**
```bash
dotnet build src/Heimdall.Web/
```
- [ ] **Step 10: Commit**
```bash
git add -A
git commit -m "refactor(handlers): rewrite auth CQRS handlers to use Zitadel API"
```
---
### Commit 7: Handlers CQRS Users
**Files:**
- Rewrite: `src/Heimdall.Application/Users/Commands/CreateUser/`
- Rewrite: `src/Heimdall.Application/Users/Commands/UpdateUser/`
- Rewrite: `src/Heimdall.Application/Users/Commands/DeleteUser/`
- Rewrite: `src/Heimdall.Application/Users/Commands/AssignRoles/`
- Rewrite: `src/Heimdall.Application/Users/Commands/AssignSites/`
- Rewrite: `src/Heimdall.Application/Users/Commands/ResetPassword/`
- Rewrite: `src/Heimdall.Application/Users/Commands/LockUser/`
- Rewrite: `src/Heimdall.Application/Users/Commands/UnlockUser/`
- [ ] **Step 1: Rewrite CreateUserHandler**
```csharp
public class CreateUserHandler : IRequestHandler<CreateUserCommand, Result<string>>
{
private readonly IZitadelUserService _zitadel;
private readonly IApplicationDbContext _context;
public async Task<Result<string>> Handle(CreateUserCommand request, CancellationToken ct)
{
// Créer l'utilisateur dans Zitadel (source of truth)
var userId = await _zitadel.CreateUserAsync(
request.Email, request.DisplayName, request.Password, ct);
// Assigner les rôles dans Zitadel
if (request.Roles?.Any() == true)
await _zitadel.AssignRolesAsync(userId, request.Roles, ct);
// Créer les préférences locales
_context.UserPreferences.Add(new UserPreferences(userId, request.DisplayName));
await _context.SaveChangesAsync(ct);
return Result.Ok(userId);
}
}
```
- [ ] **Step 2-8: Rewrite remaining user handlers** — Each one calls IZitadelUserService
- [ ] **Step 9: Build && fix errors**
```bash
dotnet build src/Heimdall.Web/
```
- [ ] **Step 10: Commit**
```bash
git add -A
git commit -m "refactor(handlers): rewrite user management CQRS handlers to use Zitadel API"
```
---
### Commit 8: Blazor Auth State Provider
**Files:**
- Rewrite: `src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs`
- Rewrite: `src/Heimdall.Web/Services/AuthState.cs`
- Modify: `src/Heimdall.Web/Components/Routes.razor` — adapter si nécessaire
- [ ] **Step 1: Rewrite HeimdallAuthStateProvider.cs**
```csharp
// Au lieu de lire le ProtectedSessionStorage, utilise l'utilisateur OIDC connecté
public class HeimdallAuthStateProvider : AuthenticationStateProvider
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly AppPermissions _permissions;
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
var user = _httpContextAccessor.HttpContext?.User;
if (user?.Identity?.IsAuthenticated != true)
return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
// Ajouter les claims de permission basés sur le rôle
var role = user.FindFirst(ClaimTypes.Role)?.Value
?? user.FindFirst("role")?.Value;
if (role != null && AppPermissions.RolePermissions.TryGetValue(role, out var permissions))
{
var identity = (ClaimsIdentity)user.Identity!;
foreach (var perm in permissions)
identity.AddClaim(new Claim("permission", perm));
}
return Task.FromResult(new AuthenticationState(user));
}
}
```
- [ ] **Step 2: Rewrite AuthState.cs** — lire les infos du HttpContext.User au lieu du session storage
- [ ] **Step 3: Build && fix errors**
- [ ] **Step 4: Commit**
```bash
git add -A
git commit -m "refactor(blazor): update auth state provider for Zitadel OIDC"
```
---
### Commit 9: Controllers — AuthController
**Files:**
- Rewrite: `src/Heimdall.Web/Controllers/AuthController.cs`
- [ ] **Step 1: Rewrite AuthController**
```csharp
[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
// POST /api/auth/login → redirect OIDC (ou challenge)
[AllowAnonymous]
[HttpPost("login")]
public IActionResult Login([FromBody] LoginRequest request)
{
// Rediriger vers le challenge OIDC
return Challenge(new AuthenticationProperties
{
RedirectUri = "/api/auth/callback"
}, OpenIdConnectDefaults.AuthenticationScheme);
}
// GET /api/auth/callback → OIDC callback, set cookie
[AllowAnonymous]
[HttpGet("callback")]
public async Task<IActionResult> Callback()
{
// L'OIDC middleware a déjà créé le cookie
// On redirige vers le frontend Blazor
return Redirect("/");
}
// POST /api/auth/logout
[Authorize]
[HttpPost("logout")]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return SignOut(new AuthenticationProperties { RedirectUri = "/" },
OpenIdConnectDefaults.AuthenticationScheme);
}
// Supprimer : register, refresh, 2fa, confirm-email, forgot-password, reset-password
// Ces opérations sont gérées par l'UI Zitadel ou via l'API Management
}
```
- [ ] **Step 2: Build && fix errors**
- [ ] **Step 3: Commit**
```bash
git add -A
git commit -m "refactor(api): rewrite AuthController for Zitadel OIDC flow"
```
---
### Commit 10: Final Cleanup — Tests, appsettings, env
**Files:**
- Delete: `.env.example` — remove JWT keys, update for Zitadel
- Update: `src/Heimdall.Web/appsettings.json` — final Zitadel config
- Update: `src/Heimdall.Web/appsettings.Testing.json`
- Fix: All test projects referencing Identity types
- Delete: any remaining references to IJwtService, IAuthSignInService
- [ ] **Step 1: Update .env.example** — replace JWT variables with Zitadel
```bash
# Au lieu de JWT__KEY, JWT__REFRESHKEY, etc.
ZITADEL__AUTHORITY=http://localhost:8080
ZITADEL__WEBCLIENTID=...
ZITADEL__APICLIENTID=...
ZITADEL__APICLIENTSECRET=...
```
- [ ] **Step 2: Fix test projects** — update to work without Identity
- [ ] **Step 3: Final build & test**
```bash
dotnet build
dotnet test --no-build
```
- [ ] **Step 4: Verify no remaining Microsoft.Identity references**
```bash
grep -r "Microsoft.AspNetCore.Identity" src/ --include="*.cs" --include="*.csproj" || echo "Clean - no Identity references found"
```
- [ ] **Step 5: Commit**
```bash
git add -A
git commit -m "chore: final cleanup — tests, env, and config for Zitadel migration"
```
@@ -0,0 +1,91 @@
# Zitadel Migration — Remplacer Microsoft Identity par Zitadel
**Date** : 2026-07-29
**Statut** : Approuvé
**Contexte** : Heimdall — plateforme de surveillance vidéo
## Résumé
Remplacer **toute** trace de Microsoft Identity (`IdentityUser`, `IdentityRole`,
`IdentityDbContext`, `UserManager<T>`, `SignInManager<T>`, `AddIdentity()`,
JWT symétrique maison) par **Zitadel** comme unique Identity Provider (OIDC).
## Architecture Cible
```
Zitadel (self-hosted, Docker Compose)
├── Users (email, name, MFA, passkeys)
├── Project "Heimdall"
│ ├── Roles : admin, supervisor, viewer
│ └── Applications :
│ ├── Heimdall Web (OIDC Auth Code + PKCE)
│ └── Heimdall API (JWT Bearer, introspection)
└── JWT émis avec claims: sub, email, name, role
Heimdall (approche C — aucun user store local)
├── Auth : OIDC middleware → JWT Zitadel → ClaimsPrincipal
├── Permissions : extraites du claim "role" → map AppPermissions
├── Tables locales (business only) :
│ ├── user_sites (user_id string, site_id FK)
│ ├── user_groups (user_id string, group_id FK)
│ └── user_prefs (user_id string PK, theme, language)
└── User management : appels gRPC à l'API Management Zitadel
```
## Ce qui est supprimé
| Composant | Fichiers |
|---|---|
| `AppUser : IdentityUser<Guid>` | `src/Heimdall.Domain/Entities/AppUser.cs` |
| `AppRole : IdentityRole<Guid>` | `src/Heimdall.Domain/Entities/AppRole.cs` |
| `IdentityDbContext<AppUser, AppRole, Guid>` | `src/Heimdall.Infrastructure/Data/AppDbContext.cs` |
| `IdentityConfiguration` (table renaming) | `src/Heimdall.Infrastructure/Data/Configurations/IdentityConfiguration.cs` |
| `JwtService` | `src/Heimdall.Infrastructure/Security/JwtService.cs` |
| `IJwtService` | `src/Heimdall.Application/Common/Interfaces/IJwtService.cs` |
| `IAuthSignInService` | `src/Heimdall.Application/Common/Interfaces/IAuthSignInService.cs` |
| `AuthSignInService` | `src/Heimdall.Infrastructure/Security/AuthSignInService.cs` |
| `AppPermissions` (local role→permission map) | `src/Heimdall.Infrastructure/Security/AppPermissions.cs` — **conservé** comme map statique |
| `HeimdallAuthStateProvider` | `src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs` |
| `AuthState` | `src/Heimdall.Web/Services/AuthState.cs` — **conservé** mais simplifié |
| `AuthController` (login, register, etc.) | `src/Heimdall.Web/Controllers/AuthController.cs` — réécrit |
| Tous les handlers CQRS auth (12+) | `src/Heimdall.Application/Auth/Commands/*` — réécrits via Zitadel gRPC |
| Tous les handlers CQRS users (8+) | `src/Heimdall.Application/Users/Commands/*` — réécrits via Zitadel gRPC |
| NuGet `Microsoft.AspNetCore.Identity.EntityFrameworkCore` | Tous les `.csproj` |
| NuGet `Microsoft.AspNetCore.Authentication.JwtBearer` | `Heimdall.Infrastructure.csproj` |
| NuGet `Microsoft.AspNetCore.DataProtection.Extensions` | `Heimdall.Infrastructure.csproj` |
| 7 tables Identity (users, roles, etc.) | Migration de suppression |
| Cookie auth Blazor (`/_auth/signin`) | Remplacé par OIDC session |
## Nouveaux composants
| Composant | Description |
|---|---|
| `UserPreferences` entity | Table locale pour theme/language (userId string PK) |
| `UserSite`, `UserGroup` | userId passe de Guid à string |
| `ZitadelUserService` | Service d'appel à l'API gRPC Zitadel (CRUD users, roles) |
| `IZitadelUserService` | Interface Application |
| `ZitadelOptions` | Config pour URL Zitadel, client ID, etc. |
| OIDC middleware | `AddOpenIdConnect()` au lieu de `AddIdentity()` |
| JWT validation JWKS | `AddJwtBearer()` avec Authority = Zitadel |
## Dépendances NuGet (nouvelles)
| Package | Projet |
|---|---|
| `Zitadel` (smartive, v7.0.44) | `Heimdall.Infrastructure` |
| `Microsoft.AspNetCore.Authentication.OpenIdConnect` | `Heimdall.Web` |
| `System.IdentityModel.Tokens.Jwt` | `Heimdall.Web` (déjà présent indirectement) |
## Plan de migration (ordre des commits)
1. **Zitadel Docker Compose + doc config rôles**
2. **Suppression des packages Identity + entités Domain**
3. **Nouveau DbContext sans Identity + nouvelles tables**
4. **Service Zitadel (gRPC) + interfaces**
5. **Migration DB (EF Core migration)**
6. **Nouveau middleware auth (OIDC + JWT) + Program.cs**
7. **Handlers CQRS auth réécrits**
8. **Handlers CQRS users réécrits**
9. **Controllers mis à jour**
10. **Blazor auth state provider mis à jour**
11. **Tests + ajustements finaux + doc config Zitadel**