Abp authorization

From burakdmir/abp-skills · View interactive version

Abp authorization is an AI agent skill from the GitHub repository burakdmir/abp-skills. ABP Framework v10.x (10.4–10.6) authorization: defining permissions (PermissionDefinitionProvider), [Authorize], CheckPolicyAsync/IsGrantedAsync, CurrentUser, IPermissionManager, resource-based auth, multi-tenancy permissions. Use when you need permission, role or access checks in ABP.

How to use this skill

Skill file

ABP Authorization Skill

Trigger

User asks about permissions, authorization, roles, policies, permission groups, resource-based authorization, or access control in ABP Framework.


Core Concepts

ABP extends ASP.NET Core Authorization with a Permission System that auto-registers permissions as policies. Two permission types exist:

  1. Standard (Global) Permissions — Apply globally (e.g., "can create documents")
  2. Resource-Based Permissions — Target specific instances (e.g., "can edit Document #123")

Permission System

Defining Permissions

Create a class inheriting PermissionDefinitionProvider:

using Volo.Abp.Authorization.Permissions;

namespace Acme.BookStore.Permissions
{
    public class BookStorePermissionDefinitionProvider : PermissionDefinitionProvider
    {
        public override void Define(IPermissionDefinitionContext context)
        {
            var myGroup = context.AddGroup(
                "BookStore",
                LocalizableString.Create<BookStoreResource>("BookStore")
            );

            myGroup.AddPermission(
                "BookStore_Author_Create",
                LocalizableString.Create<BookStoreResource>("Permission:BookStore_Author_Create")
            );
        }
    }
}

Permission Groups

Permission Options

myGroup.AddPermission(
    "BookStore_Books_Manage",
    LocalizableString.Create<BookStoreResource>("Permission:ManageBooks"),
    multiTenancySide: MultiTenancySides.Tenant  // Host, Tenant, or Both (default)
);

Multi-tenancy side options:

Child Permissions

Permissions can have parent-child relationships for hierarchical UI display:

var booksPermission = myGroup.AddPermission("BookStore_Books_Manage");
booksPermission.AddChild("BookStore_Books_Create");
booksPermission.AddChild("BookStore_Books_Edit");
booksPermission.AddChild("BookStore_Books_Delete");

Enable/Disable Permissions

myGroup.AddPermission("BookStore_Feature", isEnabled: false); // Disabled by default

Permission Depending on a Condition

// Depending on Features
myGroup.AddPermission("BookStore_Advanced")
    .WithFeatureDependency("AdvancedFeature");

// Depending on Global Features
myGroup.AddPermission("BookStore_Preview")
    .WithGlobalFeatureDependency("PreviewModule");

// Custom condition
myGroup.AddPermission("BookStore_Special")
    .WithStateChecker(() => MyStaticChecker.IsSpecialEnabled);

Overriding Permissions with Custom Policies

myGroup.AddPermission("BookStore_Special")
    .WithPolicyDependency(new MyCustomPolicyRequirement());

Changing Permission Definitions of Dependent Modules

[DependsOn(typeof(AbpIdentityModule))]
public class MyModule : AbpModule
{
    public override void PreConfigureServices(ServiceConfigurationContext context)
    {
        PreConfigure<PermissionDefinitionContext>(options =>
        {
            // Modify identity module permissions before they're finalized
        });
    }
}

Using Permissions

In Controllers / Page Models

[Authorize("BookStore_Author_Create")]
public async Task<IActionResult> CreateAsync(CreateAuthorDto input)
{
    // ...
}

In Application Services

public class AuthorAppService : ApplicationService, IAuthorAppService
{
    public async Task<AuthorDto> CreateAsync(CreateAuthorDto input)
    {
        await AuthorizationService.CheckAsync("BookStore_Author_Create");
        // or
        if (!await AuthorizationService.IsGrantedAsync("BookStore_Author_Create"))
        {
            throw new AbpAuthorizationException("...");
        }
        // ...
    }
}

Using IAuthorizationService

public class MyService : ITransientDependency
{
    private readonly IAuthorizationService _authorizationService;

    public MyService(IAuthorizationService authorizationService)
    {
        _authorizationService = authorizationService;
    }

    public async Task DoWorkAsync()
    {
        await _authorizationService.CheckAsync("BookStore_Author_Create");
    }
}

Shortcut methods in base classes: await CheckPolicyAsync("...") (throws an exception if not granted) and await IsGrantedAsync("...") (returns a bool, does not throw).


Current User

Authenticated user information is accessed via the CurrentUser property — it is available out of the box in base classes (ApplicationService, DomainService, AbpController) and requires no injection:

public class BookAppService : ApplicationService
{
    public async Task DoSomethingAsync()
    {
        var userId   = CurrentUser.Id;             // Guid?
        var userName = CurrentUser.UserName;
        var email    = CurrentUser.Email;
        var isAuth   = CurrentUser.IsAuthenticated;
        var roles    = CurrentUser.Roles;
        var tenantId = CurrentUser.TenantId;
    }
}

// Inject ICurrentUser in services that don't derive from a base class
public class MyService : ITransientDependency
{
    private readonly ICurrentUser _currentUser;
    public MyService(ICurrentUser currentUser) => _currentUser = currentUser;
}

Ownership Verification

public async Task UpdateMyBookAsync(Guid bookId, UpdateBookDto input)
{
    var book = await _bookRepository.GetAsync(bookId);

    if (book.CreatorId != CurrentUser.Id)
    {
        throw new AbpAuthorizationException();
    }
    // update...
}

Security: never trust client input for the user identity — always use CurrentUser and verify ownership inside the application service.


Resource-Based Authorization

For fine-grained, per-instance permissions:

// Define a resource permission
var booksGroup = context.AddGroup("BookStore_Books");
var bookPermission = booksGroup.AddResourcePermission(
    "BookStore_Books_Edit",
    typeof(Book),
    LocalizableString.Create<BookStoreResource>("Permission:EditBook")
);

Resource-based permissions are managed through the Resource Permission Management Dialog on individual resource instances (not the global permissions dialog).

See: Resource-Based Authorization


Multi-Tenancy Integration


UI Integration


Best Practices

  1. Naming convention: ModuleName_Entity_Action (e.g., BookStore_Books_Create)
  2. Always localize permission display names using LocalizableString.Create<TResource>()
  3. Group logically — one group per module or feature area
  4. Use child permissions for hierarchical UI (Manage > Create/Edit/Delete)
  5. Set multi-tenancy side explicitly if your app is multi-tenant
  6. Use resource-based permissions for instance-level access control
  7. Check permissions early in application service methods to fail fast

Common Patterns

CRUD Permissions

var books = myGroup.AddPermission("BookStore_Books_Manage");
books.AddChild("BookStore_Books_Create");
books.AddChild("BookStore_Books_Edit");
books.AddChild("BookStore_Books_Delete");
books.AddChild("BookStore_Books_ViewList");

Permission Check in App Service Base Class

public abstract class BookStoreAppService : ApplicationService
{
    protected BookStoreAppService()
    {
        LocalizationResource = typeof(BookStoreResource);
    }

    protected virtual async Task CheckPolicyAsync(string policyName)
    {
        await AuthorizationService.CheckAsync(policyName);
    }
}

What's New in v10.5

Single-Active Identity Token Providers (v10.5+)

ABP replaces ASP.NET Core Identity's default DataProtectorTokenProvider with AbpDefaultTokenProvider, and LinkUserTokenProvider uses the same single-active infrastructure. Tokens are now single-active per user/purpose: generating a new token invalidates the previous one. Default lifetime is 10 minutes:

Configure<AbpDefaultTokenProviderOptions>(options =>
{
    options.TokenLifespan = TimeSpan.FromMinutes(10);
});

Configure<AbpLinkUserTokenProviderOptions>(options =>
{
    options.TokenLifespan = TimeSpan.FromMinutes(10);
});

After upgrading to 10.5, re-test login, two-factor, forced/periodic password change, and link-user flows. If a flow sends multiple tokens for the same purpose and expects older ones to stay valid, switch it to use only the latest token.

OpenIddict Default Scope Fallback (v10.5+, opt-in)

For client_credentials, password, and token-exchange grants, ABP can fall back to the client application's registered scopes when the request omits the scope parameter. Disabled by default:

Configure<AbpOpenIddictAspNetCoreOptions>(options =>
{
    options.UseDefaultScopesForClientCredentials = true;
    options.UseDefaultScopesForPassword = true;
    options.UseDefaultScopesForTokenExchange = true;
});

After enabling, re-test token issuance for the affected grant types and confirm the resulting scopes/resources match authorization expectations.

What's New in v10.6

Antiforgery User Id Claim Issuer Normalization (v10.6+, default on)

ABP normalizes the user id claim issuer when generating and validating antiforgery tokens, and Razor Pages use ABP's antiforgery validation path. This fixes token mismatches when a token-authenticated SPA and cookie-authenticated MVC/Razor Pages share the same origin. Re-test mixed-auth flows after upgrading; opt out only if you intentionally rely on the issuer-specific identity:

Configure<AbpAntiForgeryOptions>(options =>
{
    options.NormalizeUserIdClaimIssuer = false;
});

OpenIddict & Token Forwarding Fixes (v10.6+)

Dynamic Claims

Claims in a token/cookie are frozen until re-authentication — a revoked role stays effective until re-login. The dynamic claims feature overrides the configured claim values with their latest values on each request. Disabled by default at the framework level, but enabled by default in startup templates since v8.0.

Enable it and add the middleware to every application that performs authentication (including the auth server):

public override void ConfigureServices(ServiceConfigurationContext context)
{
    context.Services.Configure<AbpClaimsPrincipalFactoryOptions>(options =>
    {
        options.IsDynamicClaimsEnabled = true;
        // Tiered solution (separate UI app): point to the auth server
        options.RemoteRefreshUrl = configuration["AuthServerUrl"] + options.RemoteRefreshUrl;
    });
}

public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
    //...
    app.UseDynamicClaims(); // before UseAuthorization
    app.UseAuthorization();
}

Contributors (IAbpDynamicClaimsPrincipalContributor, pre-built):

Custom contributor: implement IAbpDynamicClaimsPrincipalContributor and register it in DI — ContributeAsync runs on every HTTP request, so cache inside it.

Key options (AbpClaimsPrincipalFactoryOptions): IsDynamicClaimsEnabled, RemoteRefreshUrl (default /api/account/dynamic-claims/refresh), IsRemoteRefreshEnabled (the Identity module sets it to false, so remote contributors are not registered there), DynamicClaims (only listed claim types are overridden), ClaimsMap (auth-server↔client claim type mapping).

Related Modules

Related

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.