Skip to Content
TAdminPermissions and host extensions

Permissions, menus and host extensions

On this page

Resource types

API permissions protect server actions. Menus define navigation resources. Buttons represent grantable actions in administration pages. Hiding a button does not protect an API from direct invocation.

Declare stable permission codes on business endpoints and run them through the authorization pipeline:

using TAdmin; using TouchSocket.Http; using TouchSocket.WebApi; /// <summary>宿主设备目录的受控读取入口。</summary> [Router("/api/devices/[action]")] public sealed class DeviceApi : IPluginApiServer { /// <summary>读取当前接口示例中的设备编码。</summary> [Permission("devices:read")] [WebApi(Method = HttpMethodType.Post)] public string[] List() => ["P-001"]; }

Register the controller in the RPC store and publish AdminApiPermissionCatalog. Real device queries must also apply realm and data-scope restrictions.

Inspect registration and the permission catalog independently

Create a .NET 10 console project and install TAdmin. Save the controller above as DeviceApi.cs and this code as Program.cs, then run dotnet run to inspect the catalog:

using TAdmin; using TouchSocket.Core; using TouchSocket.Rpc; var container = new Container(); var store = new RpcStore(container); store.RegisterServer<DeviceApi>(); AdminApiPermissionCatalog.SetRpcStore(store); var codes = AdminApiPermissionCatalog.GetAllPermissionCodes(); Console.WriteLine($"Codes: {string.Join(", ", codes)}"); var methods = AdminApiPermissionCatalog.GetCurrentApiMethods(); Console.WriteLine($"Registered APIs: {methods.Count}"); foreach (var method in methods) { Console.WriteLine($"{method.MethodName}: {method.PermissionCode}"); }

Expected output:

Codes: devices:read Registered APIs: 1 List: devices:read

This example checks metadata; account authorization is covered below. The host’s catalog must use the RPC store serving HTTP requests.

Entry pointInformation to read
GetAllPermissionCodes()Deduplicated stable codes from the current store; avoids constructing routes and localized display data when only codes are needed
GetCurrentApiMethods(language)Methods, routes and display information from the published store
GetApiMethods(store, language)Inspect a particular store without replacing the global store

Codes are deduplicated without case sensitivity and may be shared by multiple actions. Anonymous methods are excluded; a non-anonymous method without Permission throws. Before SetRpcStore, the code-only entry point returns an empty list and the current-method entry point reports an uninitialized catalog.

Connect a permission from declaration to verification

For devices:read, the permission code identifies a business capability while /api/devices/List identifies a route. Maintain both:

  1. Declare [Permission("devices:read")] on the protected method and configure its WebApi route. Permission targets methods; a class-level declaration is not a substitute.
  2. Register the controller in the RPC store that actually serves HTTP APIs. After registration, publish that store with AdminApiPermissionCatalog.SetRpcStore(store). See hosting and WebApi for installation order.
  3. Read the registered API catalog and grant the permission to a role.
  4. Connect menu paths, component keys and button permissions to the frontend; match the complete button code to the server code.
  5. Call the API as an ordinary role, checking rejection before a grant and success after it. Then verify that queries return only the allowed realm and data scope.
ObjectResponsibility
/api/devices/ListHTTP route that selects an action
devices:readStable business capability used by role grants and server checks
Menu Path / ComponentKeyFrontend navigation and trusted component mapping
Button permission codePage action visibility; the same code can also participate in server authorization
Query predicatesRestrict individual records; API access does not grant access to every device

See build a business module for matching seeds, routes, controllers and frontend integration.

How requests are evaluated

AllowAnonymous on a method or its declaring class skips this authorization check. Other requests require a valid user identity, pass the mandatory password-change gate, then load a permission snapshot. Super administrators pass through the snapshot. Ordinary users pass when API codes contain * or the required code, or button codes contain that code.

Verify authorization in the complete host

Use the sample host’s login flow and an ordinary role to call the API directly:

Identity and grantsExpected result for /api/devices/List
No valid logged-in identityAuthorization rejects the call; the host adapts it to an unauthenticated response
Logged in without the API or matching button grantReject execution
API codes or button codes contain devices:readAllow after other identity restrictions pass
Only menu visibility is grantedDoes not grant API access
Mandatory password change is pendingThe business API remains restricted despite its role grant
A successful caller requests another realm or excluded recordsTrusted realm resolution and business queries still restrict returned records
SymptomCheck first
New action missing from the catalogRegistration in the current HTTP store, catalog store identity, and anonymous metadata
401 / UnauthorizedValid session and identity populated by the authentication pipeline
403 / PasswordChangeRequiredMandatory password-change state; only Me, ChangePassword, Logout and LogoutAll are allowed
Super administrator succeeds, ordinary role gets 403Method permission, role grant, complete button code and permission snapshot version
Hidden button but callable APICheck the actual server grants; page visibility does not establish API authorization
Authorized call returns another realm’s recordsTrusted realm resolution and business predicates; API authorization does not add record filters

Modules and seeds

Extension pointHost-supplied data
IAdminModuleProviderStable module key, bilingual names and controlled frontend root
IAdminSeedDataProviderModule-owned users, roles, menus, translated labels and buttons
IAdminMenuPathPrefixProviderHost path prefix for core administration menus
IAdminMenuModuleProviderModule owning the core menus
IMenuRouteProviderTrusted component keys for actual routes

The sample’s SampleMenuProvider implements these contracts for its sample module. Browser headers cannot register a module absent from the backend catalog.

Keep menu Path, ComponentKey and Module aligned with frontend routes. Names and icons are presentation data. Never build arbitrary dynamic import paths from database strings.

Consistency and uniqueness

After role permissions change, refresh authentication / menu snapshots and invalidate cached permissions. The API filter reads shared, immutable grant sets by user permission version instead of rebuilding complete role and menu data per request. Host-owned cache keys must include realm, user and permission version; a numeric user ID alone is insufficient across realms.

Database uniqueness constraints protect menu codes, paths and complete button permission-code sets within a menu. Different actions may reuse an API permission code.

Bootstrap, seed updates and protection of the last super administrator depend on the existing service transactions and concurrency controls. Host extensions should use those commands instead of updating tables directly.

Administration realms

IAdminRealmContextAccessor supplies the current realm. IAdminTenantResolver resolves its scoped connection and ensures initialization. Realm resolution, permission caches and session revocation must share the same identity boundary.

Frontend role panels are supplied through getRoleExtensionPanels. See Vue integration for save, close confirmation and dirty-state contracts.