SuperAdmin.Rbac
0.2.3
dotnet add package SuperAdmin.Rbac --version 0.2.3
NuGet\Install-Package SuperAdmin.Rbac -Version 0.2.3
<PackageReference Include="SuperAdmin.Rbac" Version="0.2.3" />
<PackageVersion Include="SuperAdmin.Rbac" Version="0.2.3" />
<PackageReference Include="SuperAdmin.Rbac" />
paket add SuperAdmin.Rbac --version 0.2.3
#r "nuget: SuperAdmin.Rbac, 0.2.3"
#:package SuperAdmin.Rbac@0.2.3
#addin nuget:?package=SuperAdmin.Rbac&version=0.2.3
#tool nuget:?package=SuperAdmin.Rbac&version=0.2.3
SuperAdmin.Rbac
Role-based authentication, URL-based permissions and a role-aware sidebar menu for ASP.NET Core. Everything is managed at runtime from a built-in admin panel: users, roles, permissions, URL rules and the menu. No code change and no redeploy are needed to change who can do what.
It is a port of the auth, role, permission and menu system of the Laravel super-admin package. It keeps the same look and URLs (/admin/auth/users, /admin/auth/roles, ...), and fixes the weaknesses of the original. See Security.
| Feature | Details |
|---|---|
| Login | Cookie scheme SuperAdmin, remember me, per-user lockout, per-IP rate limit, forced password change, POST-only logout |
| URL permissions | Every request under /admin (or the whole app) is checked against permission URL rules (GET,POST /admin/posts/{id}/edit) |
| Roles | Assign permissions to roles, roles to users, plus direct user permissions. Super-admin roles bypass checks |
| Menu | Database menu tree. Each user sees only items whose URL they may open (plus optional role/permission restrictions) |
| Admin panel | Users, user access view, roles, permissions, URL tester, menu editor, route discovery, operation log |
| Code API | [HasPermission], [AllowRoles], [DenyRoles], [SkipUrlPermission], [HasUrlPermission], Minimal API helpers, ICurrentAdmin, <sa-can> tag helper |
| Blazor Server | AddSuperAdminBlazor(): revalidating auth state, URL checks on in-circuit navigation, <SaCan>, <SuperAdminMenu />, and the panel shell (SuperAdminLayout, <SuperAdminHead />, <SuperAdminScripts />) |
| Audit and hooks | Operation log of write requests with secret redaction and retention, ISuperAdminEvents, custom IOperationLogSink |
| Database | SQL Server, PostgreSQL, MySQL, Oracle, SQLite (any EF Core relational provider), configurable table prefix and schema, create/migrate/script modes, install and upgrade SQL scripts |
Contents
- Requirements
- Install
- Quick start
- How access works
- Protect your own pages (no code)
- Use it from code
- Blazor Server
- URL pattern syntax
- Configuration reference
- Database and migrations
- Customize the UI
- Security
- Build and publish the package
- Limitations
Upgrading from 0.1.x? See CHANGELOG.md.
1. Requirements
- .NET 10 (LTS) SDK and an ASP.NET Core app (MVC, Razor Pages, Minimal APIs or Blazor Server / Interactive Server).
- An EF Core 10 relational provider package for your database, for example
Microsoft.EntityFrameworkCore.SqlServer. See 10.1 Supported databases.
2. Install
From a NuGet feed (nuget.org, GitHub Packages, Azure Artifacts or a local folder, see section 13):
dotnet add package SuperAdmin.Rbac --version 0.2.0
dotnet add package Microsoft.EntityFrameworkCore.SqlServer # or .Sqlite, Npgsql.EntityFrameworkCore.PostgreSQL, ...
From a local .nupkg file without a server:
# put SuperAdmin.Rbac.0.2.3.nupkg in a folder, for example C:\nuget-local
dotnet nuget add source C:\nuget-local --name local
dotnet add package SuperAdmin.Rbac --version 0.2.0 --source local
3. Quick start
3.1 Program.cs
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// 1. Register: options from appsettings "SuperAdmin" + your EF Core provider.
builder.Services.AddSuperAdmin(
builder.Configuration.GetSection("SuperAdmin"),
db => db.UseSqlServer(builder.Configuration.GetConnectionString("SuperAdmin")));
builder.Services.AddControllersWithViews(); // your own app, as usual
var app = builder.Build();
app.UseStaticFiles();
app.UseRouting();
// 2. Order matters: authentication -> SuperAdmin guard -> authorization.
app.UseAuthentication();
app.UseSuperAdmin();
app.UseAuthorization();
// 3. Map the admin panel and your endpoints.
app.MapSuperAdmin();
app.MapControllers();
// 4. Create tables (or apply migrations) and seed the admin user, role, permissions and menu.
await app.InitializeSuperAdminAsync();
app.Run();
3.2 appsettings.json
{
"ConnectionStrings": {
"SuperAdmin": "Server=.;Database=MyApp;Trusted_Connection=True;TrustServerCertificate=True"
},
"SuperAdmin": {
"RoutePrefix": "admin",
"Title": "My Admin",
"Auth": { "CookieSecurePolicy": "Always" },
"Seed": { "AdminUserName": "admin" }
}
}
The plugin tables can live in the same database as your app tables. They all start with sa_.
3.3 First login
Set the first admin password with user-secrets or an environment variable (never in appsettings):
dotnet user-secrets set "SuperAdmin:Seed:AdminPassword" "a-long-password"Run the app. On the first start it creates the user
adminwith that password. Without a password, inDevelopmentonly, a random password is printed to the console (never to the log). In other environments no admin user is created. Create one withdotnet <your app>.dll superadmin seed-admin(see 10.5).Open
/admin. You are redirected to/admin/auth/login.
Sign in. You must change the generated password first.

You land on the dashboard. The sidebar shows Admin → Users, Roles, Permissions, Menu, Routes, Operation log.

3.4 Try the sample
cd samples/Sample.Web
dotnet run
# open https://localhost:7191/admin
# admin / Admin#12345 (super administrator, development only)
# editor / Editor#12345 (Editor role: sees only Dashboard and Content > Posts)
cd samples/Sample.Blazor # the same with a Blazor Server app, see section 7
dotnet run
# open https://localhost:7192/admin/app
# analyst / Analyst#12345 (Analyst role: App home and Reports, not Orders)
Signed in as editor, the sidebar shows only the items the Editor role may open:

4. How access works
Request ──► in protected scope? ──no──► your endpoint (not touched)
│yes
▼
anonymous path / [AllowAnonymous]? ──yes──► endpoint
│no
▼
signed in (SuperAdmin cookie)? ──no──► 302 /admin/auth/login (API: 401)
│yes
▼
user active + security stamp valid? ──no──► sign out, 302 login
│yes
▼
must change password? ──yes──► 302 /admin/auth/setting/password
│no
▼
[SkipUrlPermission]? ──yes──► endpoint
│no
▼
super admin, or a held permission has a rule matching METHOD + path?
├─yes──► endpoint ([HasPermission] etc. are checked on top)
└─no───► 302 /admin/auth/denied (API: 403)
| Concept | Meaning |
|---|---|
| User | Admin panel account. Has roles and optional direct permissions |
| Role | Named group of permissions (editor). A role with Super administrator bypasses every check |
| Permission | A slug (posts.edit) with 0..n URL rules. A user's permissions = direct permissions + permissions of all roles. * grants everything |
| URL rule | HTTP methods (empty = any) + path pattern. The URL guard allows a request if any rule of any held permission matches |
| Menu item | Title, icon, URL, parent. Visible only if the user may GET its URL (switchable per item), plus optional "require permission" and "restrict to roles". Groups without visible children are hidden |
Changes made in the panel apply on the next request. Permissions are not stored in the cookie. They are cached per user and the cache is cleared on every change.
A signed-in user who opens a URL without a matching rule sees the denied page (here the editor opens /admin/auth/users):

To check what one user can open and see, go to Users and click the user name. The access view lists the roles, every effective permission with its source, and the visible menu:

5. Protect your own pages (no code)
Say you add a normal MVC controller:
[Route("admin/posts")]
public class PostsController : Controller
{
[HttpGet("")] public IActionResult Index() => View();
[HttpGet("{id:int}/edit")] public IActionResult Edit(int id) => View();
[HttpPost("{id:int}/edit")] public IActionResult Edit(int id, PostForm form) => ...;
[HttpPost("{id:int}/delete")] public IActionResult Delete(int id) => ...;
}
Because it lives under /admin, it is already protected. Only super admins can open it until you grant access. In the panel:
Admin → Routes. Your endpoints are listed and marked super admin only. Click the key icon next to an endpoint to create a permission pre-filled with its URL rule. The Covered by column shows which permissions already grant each endpoint.

You can also go to Permissions → New and enter the rules yourself:
Slug Name URL rules posts.listList posts GET /admin/postsposts.editEdit posts GET,POST /admin/posts/{id}/editposts.deleteDelete posts POST /admin/posts/{id}/delete
The Permissions list shows every slug with its URL rules:

Roles → New: create
Editorand tickposts.listandposts.edit.
Users → New: create a user with the
Editorrole.
Menu → New item: title
Posts, URL/admin/posts, iconicon-newspaper. Or click the menu icon on the Routes page.
The Menu page shows the whole tree. Use the arrows to reorder items:

The editor now sees Posts in the sidebar and can list and edit posts. A delete request returns 403. Other users do not see the menu item at all.

To render your page inside the admin shell (header + role-aware sidebar), use the admin layout:
@* Views/_ViewStart.cshtml (or per view) *@
@{ Layout = SuperAdmin.Rbac.SuperAdminDefaults.Layout; }
@* Views/_ViewImports.cshtml *@
@addTagHelper *, SuperAdmin.Rbac
Set ViewData["Title"] and optionally ViewData["Description"] in your view. The CSS classes sa-card, sa-table-wrap and sa-table, Bootstrap 5.3 and Font Awesome (icon-* classes) are available.
6. Use it from code
6.1 Attributes (MVC, Razor Pages)
using SuperAdmin.Rbac.Authorization;
[HasPermission("posts.publish")] // user must hold the slug (on top of the URL rule)
public IActionResult Publish(int id) { ... }
[AllowRoles("editor", "author")] // member of at least one role (super admins pass)
public class DraftsController : Controller { ... }
[DenyRoles("guest")] // members of these roles are refused
public IActionResult Export() { ... }
[SkipUrlPermission] // any signed-in admin user, no URL rule needed
public IActionResult Help() { ... }
[AllowAnonymous] // public even inside /admin
public IActionResult Status() { ... }
These attributes need app.UseAuthorization().
6.2 Minimal APIs
app.MapPost("/admin/api/posts/{id:int}/publish", Publish).RequirePermission("posts.publish");
app.MapGet("/admin/api/reports", Reports).AllowRoles("manager");
app.MapGet("/admin/api/ping", () => "pong").SkipUrlPermission();
Paths matching /admin/api/* get 401 / 403 status codes instead of redirects.
6.3 ICurrentAdmin (any service, controller or view)
public class PostsController(ICurrentAdmin admin) : Controller
{
public async Task<IActionResult> Index()
{
var me = await admin.GetAsync(); // AccessSnapshot? (id, name, roles, permissions)
var canDelete = await admin.CanAsync("posts.delete");
var canReports = await admin.CanAccessUrlAsync("/admin/reports");
var isEditor = await admin.IsInRoleAsync("editor");
...
}
}
6.4 Tag helpers (Razor)
<sa-can permission="posts.delete"> <button>Delete</button> </sa-can>
<sa-can roles="editor,author"> ... </sa-can>
<sa-can url="/admin/posts/@id/delete" method="POST"> ... </sa-can>
<sa-can permission="posts.publish" not="true"> You cannot publish. </sa-can>
<a href="/admin/reports" sa-hide-if-denied>Reports</a> @* removed if the user may not GET it *@
6.5 Menu anywhere
@await Component.InvokeAsync("SuperAdminMenu") @* the sidebar <ul>, filtered for the user *@
var tree = await menuService.GetVisibleTreeAsync(snapshot); // IMenuService, for custom rendering
For a SPA: GET /admin/api/me returns the user, roles and permission slugs. GET /admin/api/me/menu returns the visible menu tree as JSON.
6.6 Manage data from code (seeding, imports, jobs)
The panel uses public services. Each method takes the acting user, so the same safety rules apply. Use AccessSnapshot.System for trusted code:
using var scope = app.Services.CreateScope();
var permissions = scope.ServiceProvider.GetRequiredService<PermissionAdminService>();
var roles = scope.ServiceProvider.GetRequiredService<RoleAdminService>();
var users = scope.ServiceProvider.GetRequiredService<UserAdminService>();
var menu = scope.ServiceProvider.GetRequiredService<MenuAdminService>();
var system = AccessSnapshot.System;
var list = await permissions.CreateAsync(system, new PermissionInput
{
Name = "List posts", Slug = "posts.list", GroupName = "Posts",
Routes = { new RouteInput { Methods = "GET", Pattern = "/admin/posts" } },
});
var editor = await roles.CreateAsync(system, new RoleInput { Name = "Editor", Slug = "editor", PermissionIds = { list.Id } });
await users.CreateAsync(system, new UserInput { UserName = "jane", DisplayName = "Jane", Password = "S3cure#pass", RoleIds = { editor.Id } });
await menu.CreateAsync(system, new MenuInput { Title = "Posts", Icon = "icon-newspaper", Url = "/admin/posts" });
If you write to the sa_ tables directly, call IRbacCache.InvalidateAsync() afterwards.
The services create one short-lived DbContext per call (through IDbContextFactory<SuperAdminDbContext>), so they are safe to call concurrently, for example from several Blazor components of one circuit.
6.7 Import users from another system
UserInput accepts an existing ASP.NET Core Identity password hash (PasswordHasher v2 or v3, the format of AspNetUsers.PasswordHash), the old user id, an existing lockout and extra fields. Users keep their passwords:
foreach (var old in legacyUsers)
{
await users.CreateAsync(AccessSnapshot.System, new UserInput
{
Id = old.Id, // optional: keep the id (identity insert is handled on SQL Server and PostgreSQL)
UserName = old.UserName,
DisplayName = old.FullName,
Email = old.Email,
PasswordHash = old.PasswordHash, // instead of Password, never both
LockoutEnd = old.LockoutEnd, // UTC
MustChangePassword = old.MustChangePassword,
Attributes = new() { ["mobile"] = old.Mobile, ["employeeId"] = old.EmployeeId },
RoleIds = { editorRoleId },
});
}
6.8 Extra user fields
sa_users.Attributes stores host-defined fields (mobile, employee id, ...) as a JSON object of strings. Set them with UserInput.Attributes, read them with SaUser.GetAttributes() or from the cached snapshot:
var me = await admin.GetAsync();
var mobile = me?.Attributes.GetValueOrDefault("mobile");
6.9 Events and your own audit table
Implement only the methods you need and register the class. Several handlers may be registered. They run after the change is saved; an exception is logged and does not undo the change.
public sealed class AuditEvents(MyDbContext db) : ISuperAdminEvents
{
public async Task SignInFailedAsync(SignInFailedEvent e, CancellationToken ct)
{
db.AdminAuditLog.Add(new() { Action = "login-failed", UserName = e.UserName, Detail = e.Reason.ToString(), Ip = e.Ip, At = e.At });
await db.SaveChangesAsync(ct);
}
public async Task UserChangedAsync(UserChangedEvent e, CancellationToken ct) { /* Created, Updated, Deleted, PasswordChanged, ... */ }
}
builder.Services.AddScoped<ISuperAdminEvents, AuditEvents>();
Events: SignedIn, SignInFailed (with the reason: unknown user, wrong password, locked out, inactive, rate limited), SignedOut, UserChanged, RoleChanged, PermissionChanged, MenuChanged. Each carries the acting user (Actor) and the time.
The operation log (write requests with redacted input) can go to your table too. Sinks are additive; turn off the built-in table with OperationLog:WriteToDatabase = false:
public sealed class AuditSink(MyDbContext db) : IOperationLogSink
{
public async Task WriteAsync(IReadOnlyList<SaOperationLog> entries, CancellationToken ct)
{
db.AdminAuditLog.AddRange(entries.Select(e => new AdminAuditLog { Action = e.Method + " " + e.Path, UserName = e.UserName, Detail = e.Input, At = e.CreatedAt }));
await db.SaveChangesAsync(ct);
}
}
builder.Services.AddScoped<IOperationLogSink, AuditSink>();
7. Blazor Server
The URL guard is middleware, so it sees HTTP requests only. In Blazor Server (and Interactive Server render mode) a navigation inside the circuit sends no request. The Blazor layer closes that gap.
builder.Services.AddSuperAdmin(builder.Configuration.GetSection("SuperAdmin"), db => db.UseSqlServer(cs));
builder.Services.AddSuperAdminBlazor();
builder.Services.AddRazorComponents().AddInteractiveServerComponents();
...
app.UseAuthentication();
app.UseSuperAdmin();
app.UseAuthorization();
app.UseAntiforgery();
app.MapStaticAssets();
app.MapSuperAdmin();
app.MapRazorComponents<App>().AddInteractiveServerRenderMode();
"SuperAdmin": { "Auth": { "SetDefaultScheme": true } }
SetDefaultScheme makes the SuperAdmin cookie the default scheme, so the Blazor hub connection, [Authorize], AuthorizeView and HttpContext.User all see the admin user. Leave it off if your app signs users in with its own default scheme.
What AddSuperAdminBlazor() gives you:
| Piece | What it does |
|---|---|
Revalidating AuthenticationStateProvider |
Every Auth:RevalidationMinutes (default 1) the circuit re-checks that the user is active and the security stamp matches. Deactivate, force logout and password change end open circuits. |
[HasUrlPermission] |
Checks the permission URL rules for the page. AuthorizeRouteView runs it on every in-circuit navigation. Same as [Authorize(Policy = SuperAdminDefaults.UrlPolicy)]. Also works on MVC, Razor Pages and Minimal API endpoints. |
<SaCan> |
Razor component version of <sa-can>. |
<SuperAdminMenu /> |
The role-aware menu tree as a component. Renders the panel's sidebar markup; Variant="SuperAdminMenuVariant.Plain" gives a plain list (sa-menu classes) and ItemTemplate your own link markup. |
SuperAdminLayout |
The panel shell (header, user menu with logout, sidebar with search and menu). Same markup as the Razor Pages layout. |
<SuperAdminHead />, <SuperAdminScripts /> |
The panel's CSS, UI:Stylesheets and colour-mode script for <head>; Bootstrap and superadmin.js for <body>. |
Circuit-aware ICurrentAdmin |
Reads the current (revalidated) user on every call instead of keeping a snapshot for the whole circuit. |
Use AuthorizeRouteView in Routes.razor and put the attribute on each page:
@* Routes.razor *@
<Router AppAssembly="typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)">
<NotAuthorized>Access denied.</NotAuthorized>
</AuthorizeRouteView>
</Found>
</Router>
@* Pages/Reports.razor *@
@page "/admin/reports"
@attribute [HasUrlPermission]
<SaCan Permission="reports.export">
<ChildContent><button>Export CSV</button></ChildContent>
<Denied>You may read reports but not export them.</Denied>
</SaCan>
<SaCan Url="/admin/orders"><a href="admin/orders">Orders</a></SaCan>
Give Blazor pages the same shell as the admin panel. App.razor loads the package files:
@* App.razor *@
<head>
<base href="/" />
<SuperAdminHead /> @* theme CSS, UI:Stylesheets, colour mode *@
<HeadOutlet @rendermode="InteractiveServer" />
</head>
<body>
<Routes @rendermode="InteractiveServer" />
<SuperAdminScripts /> @* Bootstrap bundle + superadmin.js *@
<script src="@Assets["_framework/blazor.web.js"]"></script>
</body>
Then use SuperAdminLayout as the layout, either directly (DefaultLayout="typeof(SuperAdminLayout)") or under your own layout:
@* Layout/MainLayout.razor *@
@inherits LayoutComponentBase
@layout SuperAdminLayout
<ErrorBoundary>@Body</ErrorBoundary>
The sidebar menu, its search box, the collapse toggle and the user menu work in the circuit: superadmin.js uses delegated handlers, so Blazor re-renders do not break them. The active menu item follows in-circuit navigation. To build your own shell instead, use <SuperAdminMenu /> alone (sidebar markup) or <SuperAdminMenu Variant="SuperAdminMenuVariant.Plain" /> (a plain list to style yourself).
When the whole app is protected (Protection:Scope = All), the Blazor script (/_framework/*), the hub (/_blazor, /_blazor/*) and MapStaticAssets() files need a signed-in user but no URL rule, so every admin user gets a working circuit. The pages themselves stay protected by [HasUrlPermission]. Turn this off with Protection:SkipUrlRulesForAssets = false, or make the paths public with Protection:AnonymousPaths.
Add @using SuperAdmin.Rbac.Blazor and @using SuperAdmin.Rbac.Authorization to _Imports.razor. The Blazor sample runs all of this (analyst / Analyst#12345):


Blazor WebAssembly runs in the browser, so it cannot be trusted with authorization. Protect its server APIs with the URL guard and
[HasPermission].
8. URL pattern syntax
Patterns are app-relative paths. Matching is case-insensitive and ignores trailing slashes.
| Pattern | Matches | Does not match |
|---|---|---|
/admin/posts |
/admin/posts, /admin/posts/ |
/admin/posts/1 |
/admin/posts/{id} |
/admin/posts/7 |
/admin/posts/7/edit |
/admin/posts/{id}/edit |
/admin/posts/7/edit |
/admin/posts/edit |
/admin/posts/* |
/admin/posts/7, /admin/posts/7/edit |
/admin/posts |
* |
everything | - |
In the panel, write one rule per line: [METHODS] /path.
GET /admin/posts
GET,POST /admin/posts/{id}/edit
/admin/reports/* <- any method
GET,POST:/admin/legacy <- Laravel style also accepted
- To grant a whole area, use two rules:
/admin/postsand/admin/posts/*. - Avoid
/admin/posts*(no slash). It also matches/admin/postsecret. HEADrequests matchGETrules.- Use Permissions → URL tester to see which rules match a request and whether a given user is allowed.

9. Configuration reference
All keys live under the SuperAdmin section. You can also set them in code: AddSuperAdmin(config, db => ..., o => o.RoutePrefix = "backoffice").
| Key | Default | Description |
|---|---|---|
RoutePrefix |
admin |
URL prefix of the panel |
Title, Logo, LogoMini, LoginBackgroundImage |
Branding (logo values are HTML from config) | |
Protection:Scope |
Prefix |
Prefix protects Protection:Paths (default: the prefix). All protects the whole app |
Protection:Paths |
[] → /admin |
Path prefixes to protect when Scope = Prefix |
Protection:AnonymousPaths |
[] |
Extra public patterns. Login, denied and /_content/* are always public |
Protection:ApiPaths |
[] → /admin/api/* |
Patterns that get 401/403 instead of redirects |
Protection:SkipUrlRulesForAssets |
true |
MapStaticAssets() files and Blazor framework requests (/_framework/*, /_blazor) need login but no URL rule |
Auth:CookieName |
.SuperAdmin.Auth |
|
Auth:CookieSecurePolicy |
SameAsRequest |
Set Always in production |
Auth:ExpireMinutes / SlidingExpiration |
60 / true |
Session lifetime |
Auth:AllowRememberMe / RememberMeDays |
true / 14 |
|
Auth:MaxFailedAttempts / LockoutMinutes |
5 / 15 |
Per-user lockout |
Auth:LoginPermitLimit / LoginWindowSeconds |
10 / 60 |
Per-IP login rate limit (0 disables) |
Auth:PasswordMinLength / PasswordMaxLength |
8 / 128 |
|
Auth:SetDefaultScheme |
false |
Make the SuperAdmin cookie the default authentication scheme (Blazor, [Authorize], HttpContext.User) |
Auth:RevalidationMinutes |
1 |
Blazor Server: how often open circuits re-check the user |
Database:TablePrefix |
sa_ |
|
Database:Schema |
null | For example admin on SQL Server or PostgreSQL (on Oracle and MySQL the schema is the user/database) |
Database:Mode |
Auto |
Auto, Create, Migrate or None. See 10.2 |
Database:AutoMigrate |
true |
Obsolete. false is the same as Mode = None |
Cache:VersionCheckSeconds |
5 |
Web farm only: how often other instances notice changes. 0 = single instance |
Cache:UserSnapshotMinutes |
10 |
Sliding cache lifetime per user |
OperationLog:Enabled |
true |
|
OperationLog:Methods |
[] → POST, PUT, PATCH, DELETE |
|
OperationLog:Except |
[] |
Patterns never logged (the log page itself is always excluded) |
OperationLog:RedactKeys |
[] |
Extra keys to mask. password, secret, token, apikey and authorization are always masked |
OperationLog:MaxBodyBytes / RetentionDays |
65536 / 90 |
|
OperationLog:WriteToDatabase |
true |
false when only your IOperationLogSink should receive entries |
Seed:Enabled |
true |
Seeds only what is missing (idempotent) |
Seed:AdminUserName / AdminPassword |
admin / null |
Null: random password on the console in Development, no admin user elsewhere. Never logged |
Seed:ForcePasswordChange |
true |
|
UI:Enabled |
true |
false removes every built-in page. Guard, cookie and services keep working |
UI:Pages |
All |
Account (login, logout, denied, profile, password), Management (dashboard, users, roles, ...) or All |
UI:Stylesheets |
[] |
Extra CSS files loaded after the package CSS on every panel page (built-in pages, sign-in page, <SuperAdminHead />). ~/, / or absolute URLs. Local entries are public, so the sign-in page can load them under Scope = All. See Theme and colours |
UI:ColorMode |
Light |
Light, Dark or Auto (follows the browser) |
10. Database and migrations
Tables (with the default prefix): sa_users, sa_roles, sa_permissions, sa_permission_routes, sa_menus, sa_user_roles, sa_role_permissions, sa_user_permissions, sa_role_menus, sa_operation_logs, sa_settings.
All DateTime values are stored and read as UTC (DateTimeKind.Utc), so ToLocalTime() gives the right local time.
The plugin has its own SuperAdminDbContext and connection string. Its tables can live in your app database or in a separate one, even on another database server.
10.1 Supported databases
Install the EF Core 10 provider for your database and pass it to AddSuperAdmin:
| Database | Provider package | AddSuperAdmin(..., db => ...) |
Tested |
|---|---|---|---|
| SQL Server, Azure SQL, LocalDB | Microsoft.EntityFrameworkCore.SqlServer |
db.UseSqlServer(cs) |
Yes (LocalDB) |
| PostgreSQL | Npgsql.EntityFrameworkCore.PostgreSQL |
db.UseNpgsql(cs) |
Yes (17) |
| MySQL | MySql.EntityFrameworkCore (Oracle's provider) |
db.UseMySQL(cs) |
Yes (9.1) |
| Oracle 23ai | Oracle.EntityFrameworkCore |
db.UseOracle(cs) |
Script and model checks only |
| Oracle 19c / 21c | Oracle.EntityFrameworkCore |
db.UseOracle(cs, o => o.UseOracleSQLCompatibility(OracleSQLCompatibility.DatabaseVersion19)) |
Script and model checks only |
| SQLite | Microsoft.EntityFrameworkCore.Sqlite |
db.UseSqlite(cs) |
Yes |
| MongoDB | - | Not supported | - |
"Yes" means the provider test suite (tests/.../ProviderTests.cs: create, seed, users, roles, permissions, menus, import with explicit ids, UTC dates, log purge, install/re-run/upgrade scripts) passes against a real server. Run it against your own server with SA_TEST_SQLSERVER, SA_TEST_POSTGRES, SA_TEST_MYSQL or SA_TEST_ORACLE set to a connection string.
Notes:
- MySQL / MariaDB:
Pomelo.EntityFrameworkCore.MySqlhas no EF Core 10 release yet (latest 9.0.0), so useMySql.EntityFrameworkCore. For the SQL scripts through ADO.NET, addAllow User Variables=Trueto the connection string. MariaDB is not tested. - Oracle:
''isNULLin Oracle, so the "any method" columnsa_permission_routes.HttpMethodsis nullable there. JSON attributes, logged input and settings areNCLOB. The shippedsql/oraclescripts useBOOLEAN(23ai); for 19c/21c set the compatibility option above and generate the script withsuperadmin sql-script. - MongoDB: the plugin needs a relational database (joins, integer identities, transactions). If your app data is in MongoDB, keep the plugin tables in a small relational database, for example SQLite or PostgreSQL. Only the admin users, roles and permissions live there.
10.2 Modes
InitializeSuperAdminAsync() handles the schema according to Database:Mode, then checks every plugin table and column and stops the app with a clear error if one is missing, instead of failing on the first request.
| Mode | What it does |
|---|---|
Auto (default) |
Apply your EF Core migrations if the app has them, otherwise like Create |
Create |
Create the plugin tables if none exist, and add nullable columns introduced by newer package versions. Works in a database that already has your tables |
Migrate |
Apply your EF Core migrations only |
None |
Touch nothing, only check. For teams that create schemas with reviewed SQL scripts |
10.3 EF Core migrations
Keep the migrations in your app:
builder.Services.AddSuperAdmin(builder.Configuration.GetSection("SuperAdmin"),
db => db.UseSqlServer(cs, sql => sql.MigrationsAssembly(typeof(Program).Assembly.GetName().Name)));
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet ef migrations add SuperAdminInit --context SuperAdminDbContext --output-dir Data/SuperAdminMigrations
dotnet ef migrations add SuperAdminVNext --context SuperAdminDbContext --output-dir Data/SuperAdminMigrations # after package upgrades
When migrations exist, InitializeSuperAdminAsync() applies them. Use Mode = None to apply them yourself, for example with dotnet ef database update --context SuperAdminDbContext in CI/CD.
10.4 SQL scripts (no EF migrations)
The package contains ready scripts for the default prefix sa_ and the default schema, in its sql folder (~/.nuget/packages/superadmin.rbac/<version>/sql/):
| Folder | 0001_init.sql |
0002_user_attributes.sql |
|---|---|---|
sqlserver, postgresql, mysql, oracle, sqlite |
Creates all tables and indexes, and adds columns of newer versions to existing tables | Upgrade from 0.1.x: adds sa_users.Attributes |
Every script is safe to run again: SQL Server wraps each statement in an existence check (and sets ANSI_NULLS / QUOTED_IDENTIFIER), PostgreSQL and SQLite use IF NOT EXISTS, MySQL checks information_schema, and Oracle ignores "already exists" errors (ORA-00955, ORA-01408, ORA-01430). SQLite has no ADD COLUMN IF NOT EXISTS, so its upgrade statements are comments you run once.
For another prefix, schema or Oracle 19c, generate the script from your configuration (no database connection is opened):
var sql = app.GenerateSuperAdminSqlScript(); // or IServiceProvider.GenerateSuperAdminSqlScript()
The generated script always contains the upgrade statements too, so after a package upgrade you can regenerate and re-run it. Run the script with your usual tooling, then set Database:Mode to None. With Mode = None the app stops at startup and lists any missing table or column.
10.5 Command line
Add one line after builder.Build():
var app = builder.Build();
if (await app.RunSuperAdminCommandAsync(args)) return;
dotnet run -- superadmin sql-script --output superadmin.sql # the create script for this configuration
dotnet MyApp.dll superadmin seed-admin --user admin # create the schema (per Mode) and an admin user
seed-admin reads the password from the SUPERADMIN_ADMIN_PASSWORD environment variable or asks for it without echoing it. The password is never written to the log.
11. Customize the UI
The panel is a Razor Class Library. Any file can be overridden by a file with the same path in your app:
| To change | Create in your app |
|---|---|
| Layout (header, sidebar) | Areas/SuperAdmin/Pages/Shared/_AdminLayout.cshtml |
| Sidebar menu markup | Views/Shared/Components/SuperAdminMenu/Default.cshtml (model: SuperAdmin.Rbac.Menu.MenuViewModel) |
| Login page | Areas/SuperAdmin/Pages/Auth/Login.cshtml (keep @model SuperAdmin.Rbac.UI.Pages.Auth.LoginModel) |
| Dashboard | Areas/SuperAdmin/Pages/Index.cshtml (keep @model SuperAdmin.Rbac.UI.Pages.IndexModel) |
To use only the login, the guard and the services with your own management screens, turn pages off:
"SuperAdmin": { "UI": { "Pages": "Account" } } // login, logout, denied, profile, password change
"SuperAdmin": { "UI": { "Enabled": false } } // no built-in pages at all
Static files are served from /_content/SuperAdmin.Rbac/ (super-admin/css/styles.css, superadmin.css, superadmin.js, color-mode.js, Bootstrap 5.3 and Font Awesome 5, using icon-* class names). The paths are also constants on SuperAdminAssets.
Theme and colours
The panel uses Bootstrap 5.3 with the super-admin theme. Its colours are CSS variables, so your app can apply its brand without replacing the package views. Put the variables in a stylesheet and list it in UI:Stylesheets. It then loads on the sign-in page, the built-in pages and Blazor pages with <SuperAdminHead />:
"SuperAdmin": { "UI": { "Stylesheets": [ "~/css/admin-brand.css" ], "ColorMode": "Auto" } }
/* wwwroot/css/admin-brand.css */
:root {
--sa-accent: #e11d48; /* primary buttons, checkboxes, pagination, active menu bar */
--sa-sidebar-bg: #1f2937; /* sidebar, logo area, user menu header */
}
| Variable | Default (light) | Used for |
|---|---|---|
--sa-accent |
#3a96ff |
.btn-primary, .btn-outline-primary, checked checkboxes, pagination, pills, active menu bar |
--sa-sidebar-bg / --sa-sidebar-active-bg / --sa-sidebar-darker-bg |
#263544 / #212d3a / #1c2631 |
Sidebar, logo area and its hover |
--sa-sidebar-text / --sa-sidebar-text-hover / --sa-sidebar-link-active |
#a7a7be / #fff / #72afd2 |
Menu links |
--sa-sidebar-border |
#424d5a |
Line next to sub-menus |
--sa-main-bg |
#ecf0f5 |
Page background |
--sa-surface-bg |
body background | Cards, tables, header |
--sa-hover-bg |
#f8f8f8 |
Header item hover |
--sa-text-color |
#515151 |
Table text |
--sa-table-border-color, --sa-input-border-color, --sa-check-border-color |
Table, input and checkbox borders | |
--sa-menu-width / --sa-menu-closed-width |
280px / 55px |
Sidebar width, open and collapsed |
UI:ColorMode = Dark or Auto switches Bootstrap's data-bs-theme, and every --sa-* variable has a dark value. To change a colour in dark mode only, use [data-bs-theme=dark] { --sa-main-bg: #111; }.
Other Bootstrap colours (.btn-success, .text-bg-warning, ...) are compiled in. The theme is built from theme/ in the repository (npm install && npm run build); edit theme/_settings.scss there for deeper changes.
If you run with an environment other than
Developmentstraight from the build output (not published), callbuilder.WebHost.UseStaticWebAssets();so that/_content/...files are found. Published apps do not need this.
12. Security
What the plugin does for you:
Default deny inside the protected scope. Endpoints without a matching rule are reachable only by super admins. The guard runs for every request, even on endpoints that carry their own
[Authorize].Login protection: per-IP rate limit plus per-user lockout. Unknown users and wrong passwords get the same message and similar timing.
returnUrlmust be local. Logout is POST with an antiforgery token.Sessions: HttpOnly cookie with no permissions inside. Password change, deactivation and "force logout" rotate the user's security stamp. Old sessions end on the next request, and open Blazor circuits at the next revalidation.
Seeding: the first admin password is never written to the log (log files and aggregators keep it forever).
Server-side safety rules (not only hidden buttons):
- you cannot delete or deactivate yourself;
- the last active super admin cannot be removed;
- only super admins can change super-admin users or roles, or grant the super-admin flag;
- non-super-admins can grant only permissions they hold themselves (no privilege escalation);
- only super admins (or holders of
*) can create or change permissions and their URL rules; - system roles and permissions cannot be deleted.
Menu URLs accept only app paths or
http(s)URLs, sojavascript:links are rejected. Sidebar search uses the already filtered menu.Operation log masks secrets recursively in form and JSON bodies.

Production checklist:
-
Auth:CookieSecurePolicy = Alwaysand HTTPS only. - Admin password from user-secrets, environment or a vault. Never commit it.
- Behind a proxy: configure
ForwardedHeadersso the rate limit and the log see the real client IP. - Web farm: share the ASP.NET Core Data Protection keys (otherwise cookies are invalid across instances) and keep
Cache:VersionCheckSeconds> 0. - Review Routes for endpoints marked super admin only that should be granted, and for public ones that should not be.
13. Build and publish the package
dotnet test # unit + integration tests
dotnet pack src/SuperAdmin.Rbac/SuperAdmin.Rbac.csproj -c Release -o artifacts
# -> artifacts/SuperAdmin.Rbac.0.2.3.nupkg (+ .snupkg symbols with Source Link)
Releases to nuget.org run from GitHub Actions with Trusted Publishing (no stored API key). Push a SemVer tag; the version comes from the tag:
git tag v0.2.1
git push origin v0.2.1
Use three-part SemVer versions (0.2.1, 1.0.0-beta.1). The workflow refuses other tags. A published version cannot be deleted or reused, only unlisted.
Manual publishing to other feeds:
# nuget.org (public). Create an API key at https://www.nuget.org/account/apikeys
dotnet nuget push artifacts/SuperAdmin.Rbac.0.2.3.nupkg --api-key <KEY> --source https://api.nuget.org/v3/index.json
# GitHub Packages (private to your org)
dotnet nuget push artifacts/SuperAdmin.Rbac.0.2.3.nupkg --api-key <GITHUB_PAT> --source https://nuget.pkg.github.com/<OWNER>/index.json
# Azure Artifacts
dotnet nuget push artifacts/SuperAdmin.Rbac.0.2.3.nupkg --api-key az --source https://pkgs.dev.azure.com/<ORG>/_packaging/<FEED>/nuget/v3/index.json
# Shared folder / file server (no server needed)
copy artifacts\SuperAdmin.Rbac.0.2.3.nupkg \\fileserver\nuget\
The package ID
SuperAdmin.Rbacmust be free on nuget.org before the first push. If it is taken, change<PackageId>(for exampleYourCompany.SuperAdmin.Rbac).
14. Limitations
- Blazor WebAssembly: authorization must stay on the server. Protect its APIs; see Blazor Server for interactive server apps.
- Relational databases only (see 10.1); MongoDB is not supported.
- Users are stored in the plugin's own
sa_userstable. ASP.NET Core Identity integration is not included, but Identity password hashes can be imported (6.7). - No two-factor login, OpenID Connect or JWT yet.
- Menu ordering uses up/down buttons (no drag and drop yet).
- English UI only.
License
MIT. The admin theme CSS comes from the MIT-licensed super-admin project and includes Bootstrap 5.3 (MIT) and Font Awesome Free (fonts: SIL OFL 1.1; see wwwroot/fontawesome/LICENSE.txt).
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.EntityFrameworkCore.Relational (>= 10.0.10)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
0.2.3: Blazor SuperAdminMenu and SuperAdminLayout write root-relative links (/admin/sync, path base kept) instead of absolute http:// links. Local UI:Stylesheets entries need no login, so the sign-in page loads them under Protection:Scope = All. 0.2.2 added the Blazor shell (SuperAdminLayout, SuperAdminHead, SuperAdminScripts), Bootstrap 5.3.8, --sa-* colour variables, UI:Stylesheets and UI:ColorMode; its SuperAdminMenu renders the sidebar markup by default (breaking: use Variant="SuperAdminMenuVariant.Plain" for the old list). Full list: CHANGELOG.md in the repository.