ICurrentAdmin, tag helpers and menu
ICurrentAdmin
Inject ICurrentAdmin into any service, controller or view to ask about the signed-in user.
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");
...
}
}
| Method | Returns |
|---|---|
GetAsync() | AccessSnapshot?: id, user name, roles, permission slugs, extra fields. null when nobody is signed in |
CanAsync(slug) | true if the user holds the permission (super admins and * always pass) |
IsSignedInAsync() | true if an admin user is signed in |
CanAccessUrlAsync(path, method = "GET") | true if a held URL rule matches the method and path |
IsInRoleAsync(params slugs) | true if the user is in at least one of the roles |
Tag helpers (Razor)
Register the tag helpers once in _ViewImports.cshtml:
@addTagHelper *, SuperAdmin.Rbac
Then show or hide markup by permission, role or URL:
<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 *@
tip
Hiding a button is not a security check. The guard and the attributes protect the endpoint itself. Tag helpers only keep the UI tidy.
Menu anywhere
Render the sidebar <ul>, filtered for the current user:
@await Component.InvokeAsync("SuperAdminMenu")
For custom rendering, get the tree from IMenuService:
var tree = await menuService.GetVisibleTreeAsync(snapshot);
JSON endpoints for a SPA
| Endpoint | Returns |
|---|---|
GET /admin/api/me | The user, roles and permission slugs |
GET /admin/api/me/menu | The visible menu tree as JSON |