Skip to content

Authorization ​

GrydAuth provides a flexible authorization system combining Role-Based Access Control (RBAC) and Permission-Based Access Control (PBAC) with support for custom policies.

Authorization Models ​

Role-Based Access Control (RBAC) ​

Roles group users with similar access requirements:

csharp
[Authorize(Roles = "Admin")]
public IActionResult AdminOnly() { ... }

[Authorize(Roles = "Admin,Manager")]
public IActionResult AdminOrManager() { ... }

Permission-Based Access Control (PBAC) ​

Fine-grained permissions for specific actions:

csharp
[RequirePermission("create:products")]
public IActionResult CreateProduct() { ... }

[RequirePermission("read:products", "update:products")]
public IActionResult ViewOrUpdateProducts() { ... } // OR (default)

[RequirePermission(PermissionMatchMode.All, "read:products", "update:products")]
public IActionResult ManageProducts() { ... } // AND

Permission Format ​

GrydAuth uses the convention {action}:{entity}:

PermissionDescription
create:productsCan create products
read:productsCan view products
update:productsCan update products
delete:productsCan delete products
manage:usersCan manage users
verify:user-identityCan propose, approve and read the verified identity of a user (no default role)
reveal:user-identity-documentCan reveal a user's CPF, with a reason (no default role)
receive:tenant-admin-noticesReceives the warnings addressed to the tenant's administrator; opens no route (Admin)

No permission is a wildcard (ADR 0011, D11): a permission satisfies only a gate that names it.

Scope: tenant, group, global (ADR 0011) ​

Reach is not a permission. A scoped route takes ?scope=tenant|group|global on the same route (there is no /admin/* track), and one resolver decides it — IScopeResolver, which validates the scope against the domain's declaration in ScopedDomains and delegates to one IScopeAuthority per scope. The same resolver feeds the capabilities block of GET /auth/session, so what the session announces and what the route accepts cannot drift (D6).

ScopeAuthorityWhere the grant lives
tenantTenantScopeAuthoritythe action's permission in the session's tenant (tenant_id claim)
groupGroupScopeAuthoritythe group right in the group tenant and the domain's read permission in every active branch (D5)
globalGlobalScopeAuthoritya platform role on the user — platform-operator or platform-support — carried as the platform_permission claim, never in permission (D3/D4)

global exists only for entities that have no tenant (users, tenants, product files — D2). Platform roles are fixed in AuthorizationCatalogDefinitions.PlatformRoles and granted through POST/DELETE /api/v1/users/{id}/platform-roles/{key}, capped by the granter's own platform permissions and audited. Platform operations with no tenant behind them (secret protection, circuit breakers, security state, OIDC discovery validation, product files) require a platform-exclusive permission, which is never a row of a tenant's catalog (D9).

OutcomeHTTPCode
Scope unknown, or not declared by the domain400SCOPE_NOT_SUPPORTED
No authority over the requested scope403SCOPE_FORBIDDEN
Group not fully covered (missingTenants lists the branches)403GROUP_SCOPE_INCOMPLETE
Platform session asking for tenant/group403TENANT_CONTEXT_REQUIRED
The session's tenant belongs to no group422SCOPE_GROUP_UNAVAILABLE

The codes live in Gryd.Application.Abstractions.Tenancy.ScopeErrorCodes and are written by ScopeProblemDetails, at the edge and in the pipeline alike. A route without [ScopedEndpoint] serves the session's tenant only; UnscopedRouteScopeGuard (registered by AddGrydApiVersioning()) answers any other ?scope= there with 400 SCOPE_NOT_SUPPORTED, so asking for the group never silently returns one company.

Removed (ADR 0011, US 9.1). admin:system, manage:all-users, manage:all-tenants, read:all-users, the SystemAdmin role and every /admin/* route are gone from the catalog, the database (migration RemoveLegacyPlatformGrants) and the code; the banned-identifier gate keeps them out. Every live SystemAdmin link became platform-operator (migration AddUserPlatformRoles); a holder of the other three through any other path was not converted and is reported by the cleanup migration as a PostgreSQL WARNING, for the operator to grant a platform role by hand (D14).

The anti-escalation ceiling has no override. Granting to oneself is capped on every permission; granting to another person or composing a role is capped on the catalog's permissions (a permission the tenant invented for its own business is not). Exceeding it answers 403 ROLE_ASSIGNMENT_ESCALATION_BLOCKED. Under a granted global scope the ceiling is the action's platform permission, already checked by the scope model.

One door widens a role. IRolePermissionComposer is the only application path that puts a permission on a role. POST /roles with permissionIds, the list of PUT /roles/{id} (the permissions it adds; removing one is not capped) and POST /roles/{roleId}/permissions/{permissionId} all go through it, so they run the same rule and give the same answer: the ceiling is checked once for the whole set, and an excess refuses the request as a whole, with every excess name in the security log and no rejected grant persisted by the handler. Provisioning a tenant's catalog roles has no caller, so it uses the composer's system entry (ComposeFromCatalogTemplate), which skips the ceiling but still applies the rule below. An architecture test fails the build when any other type calls Role.AssignPermission, or when anything but the tenant bootstrap reaches the system entry. A host that composes roles in its own code calls the composer too; Role.AddPermission, an alias of AssignPermission, was removed.

Committed tenant grant ceiling ​

The tenant branch of RoleAssignmentGuard uses an independent primary RepeatableRead/read-only snapshot bound to the original authenticated subject, generation and session origin. It resolves permissions without cache for RoleGrantContext.TenantId, the calculation tenant, which may differ from both origin and resource tenants. The read grants no reach and never promotes the generation. A complete empty set is valid evidence. Tenant-assignability deny, global/platform shortcuts and the catalog/self/business rules above remain unchanged.

Invalid or ineligible identity/generation returns 401 SESSION_INVALIDATED; excess returns 403 ROLE_ASSIGNMENT_ESCALATION_BLOCKED; unavailable primary/schema/deadline/cleanup evidence returns 503 ROLE_GRANT_AUTHORITY_UNAVAILABLE, without a cached fallback. The snapshot does not fence a later Save/commit. PUT may already have changed tracked fields before refusal: its handler does not save the rejected grant, but a continued outer unit of work is not automatically rolled back. Cancellation is honored where passed; controllers do not universally forward RequestAborted. See ADR 0014 for identity binding and manual-host composition.

Permissions not assignable in a tenant (GrydAuth:Roles:TenantAssignable:Deny) ​

A catalog permission is a tenant permission, so by default the tenant administrator composes roles with it. A product that authorizes a resource by its owner — not by the module's permission — declares the module's permissions not assignable in a tenant:

json
{
  "GrydAuth": {
    "Roles": {
      "TenantAssignable": {
        "Deny": [ "upload:files", "read:files", "retain:files", "purge:files",
                  "release-hold:files", "purge-permanent:files" ]
      }
    }
  }
}

With the option, no tenant grant confers a listed permission: adding it to a role (POST /roles/{id}/permissions/{permId}), the permission list of PUT /roles/{id} and of POST /roles, a direct grant to a person (POST /users/{id}/permissions/{permId}), and assigning a role that carries one. The refusal answers 403 ROLE_ASSIGNMENT_ESCALATION_BLOCKED, the same code as the ceiling, with its own message. It is not a ceiling of the caller: it applies whatever the caller holds, under a global scope and on a platform route too. Without the option nothing changes.

The list is validated at startup, and the host does not start when an entry is blank, is not a tenant permission of the catalog (a typo would deny nothing), or is granted by a seeded role template (the seed provisions those grants from static data, so the denial could not hold). So no seeded role holds a denied permission, in the default tenant or in a tenant created later. Grants made before the option was turned on stay in the database: the option prevents new ones.

Behavior change (security fix). POST /roles used to apply only this rule to its initial permission list, not the anti-escalation ceiling: a tenant administrator could create a role already carrying a catalog permission it did not hold, which PUT /roles/{id} refused to add. It now runs the ceiling like PUT and answers 403 ROLE_ASSIGNMENT_ESCALATION_BLOCKED; the role is not created. A permission the tenant invented stays free, and a global scope or a platform authority keeps its ceiling. A client that created roles with catalog permissions its caller lacks must grant them to the caller first, or create the role from a session that holds them.

Group-scoped reads (ADR 0006) ​

Two permissions gate reading a group — the tenant of the token plus its group siblings — from the ordinary (non-admin) routes, via ?scope=group:

PermissionGrantsDoes NOT grant
read:group-analyticsAggregates over the group: counts, sums, per-tenant breakdowns.Reading the rows behind the numbers.
read:group-dataRecords owned by other tenants of the group, inside the normal filters/sort/paging.Anything outside the group; any write.

Both are in the GroupAdmin role template (AuthorizationCatalogDefinitions.GroupAdminRolePermissions), so every tenant's GroupAdmin is provisioned with them. Neither is in the Admin template: a tenant Admin administers its own tenant and is not, by that fact, a reader of its siblings.

Evaluated in the group tenant (G4), with full coverage (ADR 0011, D5). GroupScopeAuthority resolves the caller's effective permissions in the group tenant — the tenant of the token is used to find the group and for nothing else — and also requires an active link with the domain's read permission in every active branch; otherwise 403 GROUP_SCOPE_INCOMPLETE with missingTenants. A permission granted inside a child company therefore cannot open its sibling's data; the segregation is structural, not a consequence of who granted what, where.

G5 is revoked (ADR 0011). A platform session does not read a group (TENANT_CONTEXT_REQUIRED); platform-wide reads are scope=global with a platform role. The error codes are in the table of the previous section; no response names a member tenant except missingTenants of a caller who already holds the group right.

Cache of the group-scope decision (US 2.4) ​

Keygrydauth:smartfed:group-scope:{userId}:{tenantId}:{tokenVersion} (CacheKeys.Users.GroupScope)
Valuethe group's id and name, its active member ids, and the two verdicts (CanReadAggregates, CanReadRecords)
TTL5 minutes (CachePolicies.Users.GroupScope)
Invalidationonly the token_version bump that every authorization change performs (AuthorizationAffectingEventHandler). A new version is a new key, so the old entry is unreachable. There is no dedicated eviction path.
  • tenantId in the key is the token's tenant, not the group's: the group is the answer the entry holds, so it is unknown at lookup time. The mapping is deterministic, so a caller in a child and one in the group tenant simply hold two entries for the same group.
  • A refusal and a "no group" answer are cached too, so an unauthorized caller cannot make every request pay for two queries.
  • scope=tenant reads nothing: no cache lookup, no token-version lookup, no query.
  • The TTL is deliberately shorter than TenantPermissions (1 hour). The entitlement half of the entry is covered by the version bump, but the membership half is topology — a child deactivated, a tenant moved out of a group — and tenant lifecycle events do not bump anyone's token version. Five minutes bounds how long a just-deactivated sibling can stay inside a consolidated read. Making tenant lifecycle and group assignment bump the affected users' version would allow aligning this TTL with TenantPermissions; that is tracked as debt in F7.
  • Fail-secure. A cache that cannot be read behaves as a miss (the decision is resolved from the database), never as "authorized". A token version that cannot be determined skips the cache entirely rather than guessing a key.

Trace and log of the scope (US 5.1) ​

A group-scoped read publishes three facts, on the span and on every log line written while the scope is in force. ITenantScopeTelemetry (Core abstraction, implemented by Gryd.Observability.Tenancy.TenantScopeTelemetry) is the only component that writes them, and ScopeBehavior — the pipeline step of the single scope model (ADR 0011) — is its only caller.

FactSpan attributeSerilog property
Reading mode (always group)gryd.scope.modeScopeMode
Group tenantgryd.scope.group_idScopeGroupId
Size of the setgryd.scope.tenant_countScopeTenantCount

The span attribute follows the dotted OpenTelemetry convention the ADR names; the Serilog property follows the shape of every other property in LoggingConstants.Properties, which are addressed by name inside message templates. The pairs are declared side by side in TracingConstants and LoggingConstants.

  • scope=tenant publishes nothing — not mode=tenant, nothing. Every request served today is tenant-scoped, so a constant attribute on all of them would be volume rather than signal, and the question an operator asks ("which reads crossed company lines") is answered by the attribute's presence. The behavior short-circuits before the enricher is even reached.
  • The member ids are never published. The count is what detects an anomaly; the group id is already not a secret (it travels in the token as group_id). The list of siblings is the one part that would turn a log aggregator into a map of which companies belong to which group.
  • The enrichment wraps the applier, so a log line written during the query and the exception that escapes the handler both carry the scope — the failing read is the one an operator goes looking for.

Scope audit trail (ADR 0011, D15) ​

Every scope decision beyond the session's tenant (scope=group, scope=global) and every refusal (any scope) writes one audit entry through IAuditStore, the shared abstraction — so a host that composes GrydAudit gets it persisted and one that does not gets NullAuditStore. IScopeAuditor (Core abstraction, Gryd.Observability.Scoping.ScopeAuditor) is the only writer, and IScopeDecisionPoint is its only caller: the HTTP edge and the ScopeBehavior both take their decision there, so a decision is audited when it is taken and never again when the pipeline reuses it — one request, one entry per decision. A grant of scope=tenant is the ordinary case and is not recorded.

FieldValue
EntityTypeScopeDecision
EntityIdthe scoped domain name
ChangeTypeAccessed
CategorySecurity
UserIdthe caller — the only personal data in the entry (no e-mail, IP or user agent)
TenantIdthe session's tenant, or null for a platform session
Metadatascope.scope, scope.session_kind, scope.decision (granted/denied/incomplete), scope.code (the refusal code, null on a grant), scope.tenant_count (members of a granted group, 0 for global and for refusals), scope.group_id (granted group only), scope.trace_id

The compliance question — who reached beyond their tenant on this screen between two dates — is one filter: EntityType = ScopeDecision, EntityId = <domain>, FromDate/ToDate. A group's reads carry the group in scope.group_id.

Aggregates are recorded too. ADR 0006 exempted read:group-analytics; D15 records every decision beyond the tenant, so the exemption is gone. The policy (what goes in) lives inside ScopeAuditor and is pinned by ScopeAuditorTests and, against the persisted trail, by ScopeAuditTrailPersistenceTests.

The write is fail-closed, and it happens when the decision is taken — before any handler. If the trail cannot be written, the request fails and no decision is kept for the pipeline to reuse, so the tenant set is never applied. That is a deliberate departure from FederationAuditor, which swallows and logs: a read of another legal entity's records that goes unrecorded costs the only answer there will ever be to "who saw our data".

The member ids are not recorded, for the same reason they are not logged. The group's composition at any point in time is recoverable from the tenant hierarchy; the trail does not need a copy per read.

A platform session's entries have no tenant, so the tenant-scoped /api/v1/audit-logs does not list them; they are platform events.

Known gap. AuditLog.FromEntry keeps CorrelationId and drops the typed AuditEntry.TraceId and AuditEntry.Category — the entity has no column for either. CorrelationId here is ASP.NET's TraceIdentifier, not the W3C trace the span carries, so the auditor also puts the trace id in scope.trace_id metadata; without it the durable trail could not be joined to the trace at all. When AuditLog gains a TraceId column, drop that metadata entry.

Platform-role audit trail (ADR 0011, D15; US 8.2) ​

Granting or revoking a platform role (POST/DELETE /api/v1/users/{id}/platform-roles/{key}) writes one entry through IAuditStore; IPlatformRoleAuditor (PlatformRoleAuditor) is the writer.

  • Applied changes are recorded by PlatformRoleAuditHandler from the PlatformRoleGrantedEvent / PlatformRoleRevokedEvent the entity raises — so every path that changes a role is recorded, not only the routes. The events are dispatched inside the transaction that persists the change: a trail that cannot be written rolls the change back. An idempotent call that changes nothing records nothing.
  • Refused attempts — beyond the caller's own platform grant (ROLE_ASSIGNMENT_ESCALATION_BLOCKED), revoking one's own role (PLATFORM_ROLE_SELF_REVOCATION_CONFLICT), the last granter (PLATFORM_ROLE_LAST_GRANTER_CONFLICT) — are recorded by PlatformRoleGrantService as security events. A role or user that does not exist is a 404 and is not recorded; a caller without grant:platform-roles is refused at the edge (403) before the service runs.
FieldValue
EntityTypeUserPlatformRole
EntityIdthe target user id
ChangeTypeCreated (grant applied), Deleted (revocation applied), Accessed (refused — nothing changed)
CategorySecurity
UserIdthe actor (null when the system made the change) — no e-mail, IP or user agent
TenantIdalways null: a platform event, read by no tenant
Metadataplatform_role.key, platform_role.action (grant/revoke), platform_role.outcome (applied/refused), platform_role.code (refusals), platform_role.session_kind and platform_role.session_tenant_id (the actor's session, when the actor is the signed-in user), platform_role.trace_id

Ceiling on the size of the set (US 5.3) ​

MultiTenancyOptions.MaxGroupScopeTenants bounds how many tenants one group-scoped read may touch. Default 200, configurable per environment under the MultiTenancy section; Validate() refuses zero or less at startup, because a ceiling of zero would turn every group read into an empty set — fail-closed and silent about why.

The ceiling is deliberately generous. The hierarchy is one level deep by construction, so a group is its direct children — dozens, not thousands. This is a backstop against a pathological group turning one query into an unbounded IN list, not a product limit anyone should hit.

When it does bite:

  • the set is cut and TenantScope.Truncated is true — applied inside TenantScope.Group, so there is no way to build a scope that was cut and does not say so;
  • GroupScopeAuthority logs a warning naming the group, the limit and the real size;
  • the response's scope block carries truncated: true. A complete read omits the field, so the client reads its presence rather than comparing against a default;
  • scope.tenantCount becomes the limit, not the size of the group.

The group tenant stays in the set, first — its own rows are what a group read can least afford to lose — but it is never inserted when it was absent from the membership: reordering must not widen a read. Everything after it keeps the order the membership arrived in (GetActiveGroupMembersAsync orders by name), so the cut is deterministic and two consecutive pages agree about which tenants they came from.

The ceiling is applied to the resolved scope, not to the cached decision: the cache entry holds the group's real membership, so the warning fires on every request that is actually served short — not only on the one that happened to miss the cache.

POST /auth/switch-tenant needs an active UserTenant link in the target tenant, for everyone. Belonging to the target's group does not substitute for it, and neither does a platform role: reaching DATA across tenants (scope=global) and BEING a tenant are separate questions with separate gates.

Two paths used to exist. switch:any-group-tenant, evaluated in the parent, let a group admin assume a sibling with no link — and SwitchTenantCommandHandler was the only component that knew that rule. GrydAuthTokenProcessor validates tenant access with UserTenantRepository.HasAccessAsync, a link lookup with no notion of group, so the switch succeeded, issued a token for the sibling, and every request made with that token answered 403. The permission was removed rather than taught to the middleware, for the reason recorded in ADR 0007: inheritance is only safe when the effective set is enumerable and each grant is an explicit object, and here it was neither — creating a child tenant silently widened the reach of every group admin, with no grant event and no trail.

What this buys: "which tenants does this person act in?" is a SELECT over UserTenants.

Reading consolidated across a group is a different act and is unchanged — ?scope=group still resolves entitlement in the group tenant (ADR 0006, G4), and read:group-analytics / read:group-data are untouched. A group admin sees the group's numbers and rows; it does not become a member of the branch.

The GroupAdmin role inside a Company tenant ​

Every tenant is provisioned with every role in the catalog, so a company has a GroupAdmin role too. Holding it there grants nothing, and that is intended: a group-scoped read resolves the entitlement in the group tenant (G4) — a question that assignment cannot answer.

It is documented rather than suppressed. Not provisioning it in companies would put a tenant-type conditional back inside the provisioning loop — which iterates the catalog knowing no role names on purpose (US 2.2, OCP) — and would require retroactively stripping the role from companies already provisioned, for zero difference in what anyone is authorized to do.

BeginSystemScope is not the group path ​

Switching the tenant filter off is fail-open: with it off, the code is the only thing between the caller and the whole platform. That is why its single door, ITenantAmbient.BeginSystemScope(reason), is audited (reason, caller, duration) and forbidden in request handlers and controllers by an architecture test (ADR 0011, D21) — it serves jobs, hosted services and provisioning.

A group read narrows to a set and is fail-closed: the scope pipeline step begins the granted scope with TenantSnapshot.WithScope, and an empty set means no rows rather than all rows.

Role Management ​

Built-in Roles ​

GrydAuth comes with predefined roles:

RoleDescription
AdminTenant administrator: the granular set over its own tenant
GroupAdminGroup rights (read:group-data, read:group-analytics, …) evaluated in the group tenant
VisitorNo permission

Every tenant — the platform tenant included — is provisioned with the same roles, from AuthorizationCatalogDefinitions.Roles. Platform power is not a tenant role: it is a platform role on the user (platform-operator, platform-support).

Creating Roles ​

http
POST /api/v1/roles
Authorization: Bearer {admin-token}
Content-Type: application/json

{
  "name": "Manager",
  "description": "Department manager with elevated permissions",
  "permissionIds": [
    "3f2c8a10-0000-0000-0000-000000000001",
    "3f2c8a10-0000-0000-0000-000000000002"
  ]
}

The initial list runs the same anti-escalation ceiling as PUT /roles/{id}: a catalog permission the caller does not hold answers 403 ROLE_ASSIGNMENT_ESCALATION_BLOCKED and no role is created.

Assigning Roles to Users ​

http
POST /api/v1/users/{userId}/roles
Authorization: Bearer {admin-token}
Content-Type: application/json

{
  "roleNames": ["Manager", "User"]
}

Programmatic Role Management ​

csharp
public class RoleService
{
    private readonly IRoleRepository _roleRepository;
    private readonly IUserRepository _userRepository;
    
    public async Task AssignRoleAsync(Guid userId, string roleName)
    {
        var user = await _userRepository.GetByIdAsync(userId);
        var role = await _roleRepository.GetByNameAsync(roleName);
        
        user.AssignRole(role);
        
        await _userRepository.UpdateAsync(user);
    }
}

Permission Management ​

Creating Permissions ​

http
POST /api/v1/permissions
Authorization: Bearer {admin-token}
Content-Type: application/json

{
  "code": "export:reports",
  "description": "Can export reports to PDF/Excel",
  "category": "Reports"
}

Auto-Generated Permissions ​

Use [AutoPermission] attribute to automatically generate and enforce permissions for your controllers:

csharp
using Gryd.API.Attributes;

[ApiController]
[Route("api/[controller]")]
[AutoPermission("products")] // Generates AND enforces: create:products, read:products, etc.
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult GetAll() { ... } // read:products
    
    [HttpPost]
    public IActionResult Create() { ... } // create:products
    
    [HttpPut("{id}")]
    public IActionResult Update() { ... } // update:products
    
    [HttpDelete("{id}")]
    public IActionResult Delete() { ... } // delete:products
}

Automatic Enforcement with GrydCrud ​

When using GrydCrud.Auth with autoPermissions: true, controllers that inherit from CrudController or CqrsCrudController get permissions enforced automatically — no method overrides needed:

csharp
// Program.cs
builder.Services.AddGrydCrudAuth(autoPermissions: true);
csharp
// Controller — zero boilerplate
[AutoPermission("departments")]
[Route("api/[controller]")]
public class DepartmentsController : CrudController<Department, CreateDeptDto, UpdateDeptDto, DeptDto, DeptQueryParams>
{
    public DepartmentsController(ICrudService<...> service) : base(service) { }

    // ✅ All inherited CRUD endpoints are protected automatically:
    // GetAll   → Permission:read:departments
    // GetById  → Permission:read:departments
    // Create   → Permission:create:departments
    // Update   → Permission:update:departments
    // Delete   → Permission:delete:departments
}

The CrudPermissionConvention respects existing [Authorize] / [RequirePermission] attributes and will not override them. See the GrydCrud Permissions documentation for full details.

The flag is for the host's own controllers. Gryd's controllers (/users, /roles, /permissions, /tenants, …) never carry [AutoPermission]: every action declares its own rule ([ScopedEndpoint], [RequirePermission], [RequireTenantOrPlatformPermission], …), so turning autoPermissions on or off never changes how they authorize. An inferred policy is a tenant-only {action}:{entity}; on a Gryd route it ignored the platform permissions and refused with an empty 403 from an MVC filter (ForbidResult), which is how POST /tenants/{id}/members/bulk failed for a platform operator in a host with the flag on.

Permission Generation Service ​

Generate all permissions for seeding:

csharp
using GrydCrud.Auth.Abstractions;

public class PermissionSeeder
{
    private readonly ICrudPermissionGenerator _permissionGenerator;
    private readonly IPermissionRepository _permissionRepository;
    
    public async Task SeedPermissionsAsync()
    {
        // Scan all controllers for [AutoPermission] attributes
        // Includes inherited CRUD methods from base controllers
        var permissions = _permissionGenerator.GeneratePermissions(
            typeof(ProductsController).Assembly,
            typeof(UsersController).Assembly
        );
        
        foreach (var permission in permissions)
        {
            await _permissionRepository.CreateIfNotExistsAsync(permission);
        }
    }
}

Authorization Attributes ​

[Authorize] ​

Standard ASP.NET Core authorization:

csharp
[Authorize] // Any authenticated user
public class SecureController : ControllerBase { }

[Authorize(Roles = "Admin")]
public class AdminController : ControllerBase { }

[RequirePermission] ​

GrydAuth permission-based authorization:

csharp
using GrydAuth.Application.Authorization;

// Single permission
[RequirePermission("read:products")]
public IActionResult GetProducts() { ... }

// Multiple permissions (OR - default)
[RequirePermission("read:products", "export:products")]
public IActionResult ReadOrExportProducts() { ... }

// Multiple permissions (AND)
[RequirePermission(PermissionMatchMode.All, "read:products", "export:products")]
public IActionResult ExportProducts() { ... }

Behavior summary:

  • 1 permission: same behavior as previous versions.
  • 2+ permissions without PermissionMatchMode: OR (Any).
  • 2+ permissions with PermissionMatchMode.All: AND (All).
  • Internal policy format is versioned (Permission:v2:*) and backward-compatible with legacy Permission:<code>.

Stale claims and token revocation ​

Permission claims are authorization snapshots. GrydAuth bounds their lifetime with access tokens that expire after 10 minutes by default (configurable from 1 to 15 minutes), while refresh tokens preserve session continuity.

Every change to an existing user's effective permissions increments User.TokenVersion. The token processor compares the JWT token_version claim with the current version on every request and rejects obsolete tokens globally. This includes direct permissions, user roles, permissions attached to roles, tenant access changes and user deactivation. User deletion performs complete session invalidation. Role permission changes fan out the version increment to every user assigned to that role.

Authorization remains declarative through [RequirePermission]; endpoints do not perform live permission queries. This keeps database/cache I/O out of the authorization hot path and avoids endpoint-specific revocation behavior.

[AllowAnonymous] ​

Skip authorization:

csharp
[AllowAnonymous]
public IActionResult PublicEndpoint() { ... }

Policy-Based Authorization ​

Defining Policies ​

csharp
builder.Services.AddAuthorization(options =>
{
    // Simple permission policy
    options.AddPolicy("CanReadProducts", policy =>
        policy.RequirePermission("read:products"));
    
    // Multiple permissions (ALL required)
    options.AddPolicy("CanManageProducts", policy =>
        policy.RequirePermission("create:products", "update:products", "delete:products"));
    
    // Role-based policy
    options.AddPolicy("AdminOnly", policy =>
        policy.RequireRole("Admin", "SuperAdmin"));
    
    // Combined policy
    options.AddPolicy("ProductManager", policy =>
        policy.RequireRole("Manager")
              .RequirePermission("read:products", "update:products"));
    
    // Custom requirement
    options.AddPolicy("MinimumAge", policy =>
        policy.Requirements.Add(new MinimumAgeRequirement(18)));
});

Using Policies ​

csharp
[Authorize(Policy = "CanManageProducts")]
public IActionResult ManageProducts() { ... }

Custom Authorization Handlers ​

csharp
public class MinimumAgeRequirement : IAuthorizationRequirement
{
    public int MinimumAge { get; }
    public MinimumAgeRequirement(int minimumAge) => MinimumAge = minimumAge;
}

public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        MinimumAgeRequirement requirement)
    {
        var dateOfBirthClaim = context.User.FindFirst(c => c.Type == "date_of_birth");
        
        if (dateOfBirthClaim != null)
        {
            var dateOfBirth = DateTime.Parse(dateOfBirthClaim.Value);
            var age = DateTime.Today.Year - dateOfBirth.Year;
            
            if (age >= requirement.MinimumAge)
            {
                context.Succeed(requirement);
            }
        }
        
        return Task.CompletedTask;
    }
}

// Register handler
builder.Services.AddSingleton<IAuthorizationHandler, MinimumAgeHandler>();

Checking Permissions in Code ​

Using IAuthorizationService ​

csharp
public class ProductService
{
    private readonly IAuthorizationService _authorizationService;
    private readonly IHttpContextAccessor _httpContextAccessor;
    
    public async Task<Result> DeleteProductAsync(Guid productId)
    {
        var user = _httpContextAccessor.HttpContext!.User;
        
        var authResult = await _authorizationService.AuthorizeAsync(
            user, 
            null, 
            new PermissionRequirement("delete:products"));
        
        if (!authResult.Succeeded)
        {
            return Result.Failure("ACCESS_DENIED", "You don't have permission to delete products");
        }
        
        // Proceed with deletion...
    }
}

Using ICurrentUserService ​

csharp
public class ProductService
{
    private readonly ICurrentUserService _currentUser;
    
    public bool CanUserEditProduct(Product product)
    {
        // Check if user has update permission
        if (_currentUser.HasPermission("update:products"))
            return true;
        
        // Or is the owner
        if (product.CreatedBy == _currentUser.UserId)
            return true;
        
        return false;
    }
}

ICurrentUserService Methods ​

MethodDescription
HasPermission(string)Check single permission
HasAnyPermission(params string[])Check if user has any of the permissions
HasAllPermissions(params string[])Check if user has all permissions
IsInRole(string)Check if user is in role
IsInAnyRole(params string[])Check if user is in any of the roles

Resource-Based Authorization ​

For complex scenarios where authorization depends on the resource:

csharp
public class DocumentAuthorizationHandler : 
    AuthorizationHandler<OperationAuthorizationRequirement, Document>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        OperationAuthorizationRequirement requirement,
        Document resource)
    {
        var userId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        
        if (requirement.Name == Operations.Read.Name)
        {
            // Anyone in the same department can read
            if (resource.DepartmentId == GetUserDepartment(context.User))
            {
                context.Succeed(requirement);
            }
        }
        else if (requirement.Name == Operations.Update.Name)
        {
            // Only owner or admin can update
            if (resource.OwnerId.ToString() == userId || 
                context.User.IsInRole("Admin"))
            {
                context.Succeed(requirement);
            }
        }
        
        return Task.CompletedTask;
    }
}

// Usage
var document = await _documentRepository.GetByIdAsync(id);
var authResult = await _authorizationService.AuthorizeAsync(
    User, document, Operations.Update);

if (!authResult.Succeeded)
    return Forbid();

Hierarchical Permissions ​

Implement permission hierarchies:

csharp
public class HierarchicalPermissionHandler : AuthorizationHandler<PermissionRequirement>
{
    private readonly Dictionary<string, string[]> _hierarchies = new()
    {
        ["admin:*"] = new[] { "create:*", "read:*", "update:*", "delete:*" },
        ["manage:products"] = new[] { "create:products", "read:products", "update:products" },
    };
    
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        PermissionRequirement requirement)
    {
        var userPermissions = context.User.Claims
            .Where(c => c.Type == "permissions")
            .Select(c => c.Value)
            .ToHashSet();
        
        // Check direct permission
        if (userPermissions.Contains(requirement.Permission))
        {
            context.Succeed(requirement);
            return Task.CompletedTask;
        }
        
        // Check hierarchical permissions
        foreach (var (parent, children) in _hierarchies)
        {
            if (userPermissions.Contains(parent) && 
                children.Contains(requirement.Permission))
            {
                context.Succeed(requirement);
                break;
            }
        }
        
        return Task.CompletedTask;
    }
}

Best Practices ​

  1. Principle of Least Privilege - Grant minimum permissions needed
  2. Use Permissions over Roles - Roles group permissions, but check permissions
  3. Avoid Hardcoded Roles - Use configuration or database
  4. Audit Permission Changes - Log all authorization changes
  5. Regular Permission Review - Periodically review user permissions
  6. Use Resource-Based Auth - For complex scenarios, check the resource itself

Released under the MIT License.