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:readThis example checks metadata; account authorization is covered below. The host’s catalog must use the RPC store serving HTTP requests.
| Entry point | Information 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:
- Declare
[Permission("devices:read")]on the protected method and configure its WebApi route.Permissiontargets methods; a class-level declaration is not a substitute. - 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. - Read the registered API catalog and grant the permission to a role.
- Connect menu paths, component keys and button permissions to the frontend; match the complete button code to the server code.
- 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.
| Object | Responsibility |
|---|---|
/api/devices/List | HTTP route that selects an action |
devices:read | Stable business capability used by role grants and server checks |
Menu Path / ComponentKey | Frontend navigation and trusted component mapping |
| Button permission code | Page action visibility; the same code can also participate in server authorization |
| Query predicates | Restrict 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 grants | Expected result for /api/devices/List |
|---|---|
| No valid logged-in identity | Authorization rejects the call; the host adapts it to an unauthenticated response |
| Logged in without the API or matching button grant | Reject execution |
API codes or button codes contain devices:read | Allow after other identity restrictions pass |
| Only menu visibility is granted | Does not grant API access |
| Mandatory password change is pending | The business API remains restricted despite its role grant |
| A successful caller requests another realm or excluded records | Trusted realm resolution and business queries still restrict returned records |
| Symptom | Check first |
|---|---|
| New action missing from the catalog | Registration in the current HTTP store, catalog store identity, and anonymous metadata |
401 / Unauthorized | Valid session and identity populated by the authentication pipeline |
403 / PasswordChangeRequired | Mandatory password-change state; only Me, ChangePassword, Logout and LogoutAll are allowed |
Super administrator succeeds, ordinary role gets 403 | Method permission, role grant, complete button code and permission snapshot version |
| Hidden button but callable API | Check the actual server grants; page visibility does not establish API authorization |
| Authorized call returns another realm’s records | Trusted realm resolution and business predicates; API authorization does not add record filters |
Modules and seeds
| Extension point | Host-supplied data |
|---|---|
IAdminModuleProvider | Stable module key, bilingual names and controlled frontend root |
IAdminSeedDataProvider | Module-owned users, roles, menus, translated labels and buttons |
IAdminMenuPathPrefixProvider | Host path prefix for core administration menus |
IAdminMenuModuleProvider | Module owning the core menus |
IMenuRouteProvider | Trusted 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.