NuGet · nuget

Redeon.SuperSiteEngineCore.Web.Eltheon.Core.Features.Identity

Core Feature for Identity for Eltheon Framework

Install

Install-Kommandos

dotnet add package Redeon.SuperSiteEngineCore.Web.Eltheon.Core.Features.Identity --version 0.9.10.8
<PackageReference Include="Redeon.SuperSiteEngineCore.Web.Eltheon.Core.Features.Identity" Version="0.9.10.8" />
paket add Redeon.SuperSiteEngineCore.Web.Eltheon.Core.Features.Identity --version 0.9.10.8
Install-Package Redeon.SuperSiteEngineCore.Web.Eltheon.Core.Features.Identity -Version 0.9.10.8

README

Vorschau

Redeon.SuperSiteEngineCore.Web.Eltheon.Core.Features.Identity

Purpose

The Identity feature extends ASP.NET Core Identity with Eltheon-specific repositories, managers, runtime permission evaluation, typed permissions, events and metrics. It centralizes Identity ownership so hosts can keep project-specific UI while using the same authorization and event surface.

Building Blocks

  • v1/Extensions registers the feature through AddEltheonIdentityCore().
  • v1/Interfaces define repositories (IAuthRepository) and runtime permission managers (IEltheonPermissionManager).
  • v1/Manager contains Identity-owned orchestration such as EltheonPermissionManager and EltheonSignInManager.
  • v1/Permissions exposes typed User/Role admin permission sets.
  • v1/Cache owns runtime permission cache abstraction and the default memory-cache implementation.
  • v1/WebUi adapts Identity permission checks to Core.WebUi.
  • v1/ExternalAuth contains provider-neutral external authentication contracts, options, diagnostics managers, conservative group-to-role mapping, provisioning, an in-memory directory cache with managed sync service and the LDAP/AD provider foundation.
  • v1/Models (AuthRole, RolePermission, Permission) capture role metadata and grant matrices that can be serialized, seeded or exposed via APIs.
  • Converter and enum types (PermissionTypeConverter, PermissionType) make it simple to map between persisted values and domain friendly enums.

Usage

  1. Register the Identity feature alongside ASP.NET Core Identity in your host:
builder.Services.AddDefaultIdentity<IdentityUser>()
    .AddRoles<AuthRole>()
    .AddEntityFrameworkStores<AuthDbContext>()
    .AddDefaultTokenProviders();

builder.Services.AddEltheonIdentityCore();
builder.Services.AddEltheonIdentitySecurityDefaults(options =>
{
    options.Registration.AllowPublicRegistration = false;
});

For DB-backed ExternalAuth management, hosts with an EF-backed auth context also register the concrete store:

builder.Services.AddEltheonExternalAuthenticationDbStore<AuthDbContext>();
  1. Register the feature Razor Class Library application part when configuring Razor Pages and MVC:
builder.Services.AddRazorPages()
    .AddEltheonIdentityApplicationPart();

builder.Services.AddMvc()
    .AddEltheonIdentityApplicationPart();
  1. Reference the shared models in Razor pages, controllers or APIs when exposing role/permission settings.
  2. Use the provided converters when persisting or reading permission values from configuration stores.

External Authentication

External authentication is disabled by default. Register provider-neutral services through AddEltheonIdentityCore() and enable providers explicitly:

builder.Services.AddEltheonExternalAuthentication(options =>
{
    options.Enabled = true;
    options.Mode = ExternalAuthMode.LocalFirstThenExternal;
});

builder.Services.AddEltheonLdapExternalAuthentication(options =>
{
    options.Host = "dc.example.test";
    options.BaseDn = "DC=example,DC=test";
});

LDAP defaults to LDAPS on port 636. Plain LDAP is rejected unless AllowInsecurePlainLdap is explicitly enabled. Bind credentials are accepted as options for bootstrap/fallback, but the management UI stores provider secrets through ASP.NET Core DataProtection and never returns, logs or emits cleartext/protected secret values.

External Authentication Management

The Identity RCL owns the Admin ExternalAuth shell pages under /Admin/Identity/ExternalAuth/* and the API surface under /api/v1/admin/identity/external-auth/*. The DB-backed store is the source of truth for runtime settings, providers, group mappings and diagnostics. Options remain defaults and fallback only.

The package also registers ExternalDirectorySyncService as an IEltheonManagedService. The service can be triggered through the existing Services admin surface and refreshes sanitized directory group caches for active provider instances. Auto-refresh stays disabled by default and can be enabled through EltheonExternalAuthOptions.DirectoryCache.AutoRefreshEnabled.

The ExternalAuth UI is API-first and EltheonJS-driven. Razor pages render only the shell, localized labels, help texts and antiforgery metadata; settings, providers, mappings, diagnostics and preview actions are loaded and mutated through the Identity-owned admin API.

External Authentication Runtime Model

Auth modes are resolved from the effective DB-backed configuration:

  • LocalOnly never calls external providers.
  • LocalFirstThenExternal tries local sign-in first and then active external providers by priority.
  • ExternalFirstThenLocal tries active external providers first and falls back to local sign-in.
  • ExternalOnly blocks normal local users, but can still allow the local break-glass SuperAdmin when configured.

Provider instances are identified by ProviderKey, for example ldap-main or ldap-dev. Runtime links are stored through ASP.NET Identity external-login records with the provider key and the stable external user id. New external users are first matched through that external-login link; initial provisioning can fall back to user name or email only when policy allows it.

Provisioning is conservative by default. Auto-provisioning must be enabled explicitly, the default external role cannot be SuperAdmin, and email candidates are selected from LDAP mail, then UPN, then the login identifier when they are valid. Identity events and audit payloads report bounded reason codes such as EmailFromLdapMail, EmailFromUserPrincipalName, DuplicateEmail or InvalidEmail without logging raw provider secrets or passwords.

Group-to-role mapping is additive unless RemoveMissingMappedRolesOnLogin is enabled. External role assignments are tracked with provider key, external user id and role name so missing mapped roles can later be removed without touching manual local roles. SuperAdmin is never offered as an external mapping target. Whenever external mappings change a user's local roles, the Identity permission cache is invalidated by the local user id.

Directory data is cached in memory by provider key. The cache stores sanitized user/group lookup data and group options for UI previews and mappings; password verification always performs an LDAP bind and is never satisfied from cache. Provider, mapping and settings changes invalidate the affected effective configuration and directory cache entries.

MFA and Session Lifecycle

The Identity package owns TOTP/Auth-App MFA through ASP.NET Identity authenticator keys, two-factor token verification and recovery codes. Policy is stored in the AuthDbContext table IdentityMfaPolicySettings; options are only the bootstrap fallback. Defaults are conservative: TOTP and recovery codes are available, remember-device is allowed, privileged users are evaluated, external provider MFA is not trusted by default and enforcement starts in WarnOnly mode.

User self-service pages live under /User/Security. They allow users to set up an authenticator app, regenerate recovery codes and review recent sessions. The template still owns the themed /Identity/Account/LoginWith2fa and /Identity/Account/LoginWithRecoveryCode pages, but those pages remain thin adapters around ASP.NET Identity and Identity-owned policy/session services.

Session tracking is persisted in IdentityUserSessions and accelerated through the normal Identity runtime. New sign-ins receive a stable session id claim. Logout marks the current session ended; self-service or admin “invalidate all sessions” updates the ASP.NET Identity security stamp and marks stored sessions invalidated. SecurityStamp remains the hard invalidation mechanism, while session rows provide current-session display, diagnostics and future targeted revocation support.

Admin MFA policy lives at /Admin/Identity/Mfa/Policy and user security actions are surfaced in the Admin Users detail panel. The new permissions are System.Identity.Mfa.View, System.Identity.Mfa.ConfigurePolicy, System.Users.ViewSecurityDetails, System.Users.ResetTwoFactor, System.Users.ForceMfaEnrollment and System.Users.InvalidateSessions.

MFA/session events are sanitized. They never contain authenticator secrets, entered TOTP codes, recovery codes, security stamps, tokens or links.

Identity Cockpit and User Directory

The Identity RCL exposes /Admin/Identity/Index as an API-first Identity cockpit. The page loads /api/v1/admin/identity/cockpit through EltheonJS and shows operational Identity data such as user counts, external user counts, active providers, provider diagnostics, directory cache status and bounded risk warnings.

The cockpit deliberately does not reference the concrete Events feature. Optional recent Identity events flow through the Identity-owned IIdentityCockpitEventSource port; the default implementation returns an empty event list so the package remains independently upgradeable.

The Admin Users view is enriched through /api/v1/admin/identity/users and the EltheonIdentityUserDirectoryManager. User source classification is conservative:

  • Local means no ASP.NET Identity external-login link exists.
  • External means an external-login link exists and no local password hash is present.
  • Mixed means a local password hash and at least one external-login link exist.
  • Provisioned is shown only when ExternalAuth tracking data is available.

ExternalAuth details are only projected when the current admin also has System.ExternalAuth.View. Directory data is read from the in-memory provider cache and tracking tables only; dashboard and user directory loads do not trigger live LDAP lookups.

Recommended first setup:

  1. Create an LDAP provider with LDAPS or StartTLS, validate the connection and keep plain LDAP disabled.
  2. Trigger directory sync and confirm that user and group previews show readable names.
  3. Enable ExternalAuth in LocalFirstThenExternal mode.
  4. Add group mappings to non-SuperAdmin roles.
  5. Enable auto-provisioning only after mappings and diagnostics are clean.
  6. Keep break-glass SuperAdmin enabled before testing ExternalOnly.

Common diagnostic reason codes include InvalidCredentials, DirectoryUnavailable, UserNotFound, NoGroupsFound, NoSuchObject, InvalidDNSyntax, InsufficientAccessRights, SizeLimitExceeded, TimeLimitExceeded, Referral, ExternalLoginLinkMismatch, InvalidEmail, DuplicateEmail, CacheHit and CacheMiss.

Integration Notes

  • Runtime permission caching uses IMemoryCache through IIdentityPermissionCache.
  • The package does not configure ASP.NET Identity stores itself. Continue to call AddIdentity / AddDefaultIdentity in your host and then call AddEltheonIdentityCore().
  • The package owns the Admin Users pages, Admin Roles page, Admin Roles API and User Profile edit page through its RCL. Account pages under /Identity/Account/* remain host-owned so themes can stay host-specific while PageModels delegate to Identity managers.
  • Hosts that persist role-permission matrices provide an IIdentityRolePermissionStore adapter. The Identity package does not reference the concrete Permissions feature or host database context.
  • External directory integrations use Identity-owned provider contracts and ASP.NET Identity external-login links. The management phase adds AuthDbContext tables for ExternalAuth settings, providers, group mappings and diagnostics; directory group cache data remains in memory only.
  • Identity references Core.WebUi only for the permission evaluator adapter. Domain permission evaluation stays in EltheonPermissionManager.
  • The package is designed to be consumed by both web hosts and plugins, allowing consistent enforcement of authorization policies.
  • Defines canonical Identity event names, metadata and safe payload/options contracts. Hosts that already reference the Eltheon event bus can publish these signals from the mutation owner without including passwords, reset tokens, confirmation tokens, reset links or raw email addresses.

Security Defaults

AddEltheonIdentitySecurityDefaults() registers EltheonIdentityOptions and applies conservative ASP.NET Core Identity, cookie and token-provider defaults:

  • public registration and development confirm links are disabled by default
  • password reset tokens default to short lifetimes
  • sign-in requires confirmed accounts
  • application cookies use stable paths, HttpOnly, SameSite=Lax and sliding expiration
  • Identity events are sanitized before publishing

Production hosts should configure persistent DataProtection key storage outside of the app directory and use a shared key ring for multi-node deployments. The option model exposes this baseline, but the host remains responsible for selecting the environment-specific key store.

Diagnostics

Loggers are injected throughout repository and manager classes. Enable the category Redeon.SuperSiteEngineCore.Web.Eltheon.Core.Features.Identity to observe user, role or permission operations during troubleshooting.

Metrics

  • eltheon_identity_login_attempts_total{outcome="success|failed|lockedout|requires2fa"} – emitted by EltheonSignInManager for every sign-in attempt.
  • eltheon_identity_user_registered_total – emitted on successful registration.
  • eltheon_identity_roles_created_total{outcome="success|failed"} – emits when roles are created via AuthRepository.
  • eltheon_identity_user_role_assignments_total{outcome="success|failed"} – emits when users are added to roles via AuthRepository.

Identity records metrics through Core.Abstractions.v1.Metrics.IMetrics; no concrete metrics feature is required.

Events

Identity event emission is enabled by default through IdentityEventOptions.EnableEvents.

Canonical events currently prepared for hosts and templates:

  • Eltheon.Identity.UserCreated
  • Eltheon.Identity.UserUpdated
  • Eltheon.Identity.UserDeleted
  • Eltheon.Identity.RoleCreated
  • Eltheon.Identity.RoleUpdated
  • Eltheon.Identity.RoleDeleted
  • Eltheon.Identity.UserRoleAssigned
  • Eltheon.Identity.UserRoleRemoved
  • Eltheon.Identity.LoginSucceeded
  • Eltheon.Identity.LoginFailed
  • Eltheon.Identity.PasswordResetRequested
  • Eltheon.Identity.PasswordResetCompleted