Orchard Core Permission Providers - Prompt Templates
Create a Permission Provider
You are an Orchard Core expert. Generate permission-provider code that follows Orchard Core conventions and CrestApps project structure.
Guidelines
- Declare reusable permissions as
static readonlyfields of astatic*Permissionsclass (for exampleTeamPermissions) in the feature's*.Coreor*.Abstractionsproject, so other modules can reference them without depending on the module. - Keep the provider separate: an
internal sealed class PermissionProvider : IPermissionProviderin the module project that only lists the permissions and stereotypes. - Create descriptions with
LocalizationSource.Create("...", typeof(DeclaringType))(namespaceOrchardCore.Localization). The type is the PO translation context. - Register the provider with
services.AddPermissionProvider<PermissionProvider>()(it usesTryAddEnumerable, so double registration is harmless). - Use
OrchardCoreConstants.Roles.Administratorinstead of hard-coded"Administrator". - Mark permissions that grant broad or dangerous access with
isSecurityCritical: true. - Use implied permissions (
impliedBy) so a broader permission grants the narrower one. - Place reusable content-part models shared by services, drivers, and other features in the
*.Coreproject too; keep the module focused onStartup, drivers, controllers, and views.
Recommended Project Placement
src/Core/{{FeatureName}}.Core/Permissions/{{FeatureName}}Permissions.cssrc/Core/{{FeatureName}}.Core/Models/{{ContentPart}}.cssrc/Modules/{{FeatureName}}/PermissionProvider.cssrc/Modules/{{FeatureName}}/Startup.cs
Static Permission Definitions in a Core Project
using OrchardCore.Localization;
using OrchardCore.Security.Permissions;
namespace CrestApps.Sports.Teams.Core.Permissions;
public static class TeamPermissions
{
public static readonly Permission ManageTeams = new(
"ManageTeams",
LocalizationSource.Create("Manage teams", typeof(TeamPermissions)),
isSecurityCritical: true);
public static readonly Permission ViewTeams = new(
"ViewTeams",
LocalizationSource.Create("View teams", typeof(TeamPermissions)),
[ManageTeams]);
}
Use typeof() here: a static class cannot be the T of LocalizationSource.Create<T>(). The constructors taking a plain string description (new Permission("ManageTeams", "Manage teams")) are [Obsolete] (CS0618) since Orchard Core 4.0; they create a context-free source that is translated only through Data Localization, not PO files.
PermissionProvider Class
using CrestApps.Sports.Teams.Core.Permissions;
using OrchardCore;
using OrchardCore.Security.Permissions;
namespace CrestApps.Sports.Teams;
internal sealed class PermissionProvider : IPermissionProvider
{
private readonly IEnumerable<Permission> _allPermissions =
[
TeamPermissions.ManageTeams,
TeamPermissions.ViewTeams,
];
public Task<IEnumerable<Permission>> GetPermissionsAsync()
=> Task.FromResult(_allPermissions);
public IEnumerable<PermissionStereotype> GetDefaultStereotypes() =>
[
new PermissionStereotype
{
Name = OrchardCoreConstants.Roles.Administrator,
Permissions = _allPermissions,
},
new PermissionStereotype
{
Name = "Coach",
Permissions =
[
TeamPermissions.ViewTeams,
],
},
];
}
Registering the Provider
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Modules;
using OrchardCore.Security.Permissions;
namespace CrestApps.Sports.Teams;
public sealed class Startup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddPermissionProvider<PermissionProvider>();
}
}
Default stereotypes are granted to the roles of the same name when the feature is installed (first enabled), and to a role when it is created, for the enabled features. A role created while an installed feature is disabled remembers that feature, and gets its stereotype permissions when the feature is enabled again. Since Orchard Core 4.0 this also works for internal providers: every installed but disabled feature is tracked when a role is created, and its providers are resolved when it is re-enabled (previously only features whose public types included an IPermissionProvider were tracked, so the stereotypes of an internal provider were never granted to such roles).
Displaying and Translating Descriptions
Permission.Description is a LocalizationSource, not a string. Show it with stringLocalizerFactory.Localize(permission.Description)?.Value ?? permission.Name, and read permission.Description?.Value for the original text. The roles editor and the admin menu and menu item permission pickers translate typed descriptions with PO files, using the type's full name as msgctxt:
msgctxt "CrestApps.Sports.Teams.Core.Permissions.TeamPermissions"
msgid "Manage teams"
msgstr "Gérer les équipes"
Typed descriptions are not listed in Data Localization; context-free descriptions, permissions built from templates (for example "Edit Article"), and categories still are. orchardcore-localization-source covers the API, the Data Localization interaction, and migration in detail.
Dynamic Permission Templates
Declare the template of a family of dynamic permissions (one per team, role, content type...) as a PermissionTemplate, not as a Permission. A template is never listed by a provider or granted to a role; it only creates permissions:
using OrchardCore.Localization;
using OrchardCore.Security.Permissions;
namespace CrestApps.Sports.Teams.Core.Permissions;
public static class TeamPermissionTemplates
{
private static readonly PermissionTemplate s_manageTeam = new(
"ManageTeam_{0}",
LocalizationSource.Create("Manage team {0}", typeof(TeamPermissionTemplates)),
TeamPermissions.ManageTeams);
public static Permission CreateManageTeamPermission(string teamName, string teamDisplayName) =>
s_manageTeam.CreateDynamicPermission(teamName, teamDisplayName);
}
- Constructors:
PermissionTemplate(name, description, category = null, params Permission[] impliedBy)andPermissionTemplate(name, description, params Permission[] impliedBy).Name, the description value andCategoryuse{0};Categorycan also use{1}for the description value. CreateDynamicPermission(nameValue)uses the same value for both;CreateDynamicPermission(nameValue, descriptionValue)formatsNamewith the first value andDescription.Valuewith the second.ImpliedBylists static permissions; the init-onlyImpliedByTemplateslists other templates, created with the same values, for example "Edit own {0}" implied by "Edit {0} for others". SetIsSecurityCriticalwith an object initializer.- The created permission's description is
LocalizationSource.Create(formattedText)without a type, so it is translated through Data Localization, not PO files. Data Localization skips values that still contain{0}. - Cache created permissions (for example in a
ConcurrentDictionary) when they are requested often, asIndexingPermissions.CreateDynamicPermission(indexProfile)does.
Content type permissions use the same model: ContentTypePermissionsHelper.PermissionTemplates (namespace OrchardCore.Contents.Security) is a Dictionary<string, PermissionTemplate> keyed by the global permission name. Use ContentTypePermissionsHelper.CreateDynamicPermissionOf(CommonPermissions.EditContent, typeDefinition), or its (string basePermissionName, ContentTypeDefinition) and (string basePermissionName, string contentType) overloads, and GetPermissionTemplate(name).
Content Part Placement Guidance
When a content part model is reused by services or other projects, move it into the matching *.Core project:
using OrchardCore.ContentManagement;
namespace CrestApps.Sports.Teams.Core.Models;
public sealed class TeamPart : ContentPart
{
public string AgeGroup { get; set; }
public string Level { get; set; }
}
The feature project should reference the core project and use that shared model from drivers, services, and startup wiring.
Upgrading from 3.x
Permission.Descriptionchanged fromstringtoLocalizationSource. Replacepermission.Descriptionstring usage withpermission.Description.Value(raw text) orIStringLocalizerFactory.Localize(permission.Description)(translated), and create descriptions withLocalizationSource.Create("...", typeof(MyPermissions)). Modules compiled against 3.x must be recompiled. Seeorchardcore-localization-source.- The
[Obsolete]permission members were removed. Build on the latest 3.x, fix everyCS0618warning, then upgrade. Stored role claims use the same permission names, so no data migration is needed. Common replacements: OrchardCore.Users.CommonPermissions.*becomesOrchardCore.Users.UsersPermissions.*OrchardCore.Deployment.CommonPermissions.*becomesOrchardCore.Deployment.DeploymentPermissions.*OrchardCore.Apis.GraphQL.CommonPermissions.*becomesOrchardCore.Apis.GraphQL.GraphQLPermissions.*OrchardCore.Media.Permissions.*andSecureMediaPermissions.*becomeOrchardCore.Media.MediaPermissions.*OrchardCore.Workflows.Permissions.*becomesOrchardCore.Workflows.WorkflowsPermissions.*OrchardCore.Settings.Permissions.*becomesOrchardCore.Settings.SettingsPermissions.*OrchardCore.ReCaptcha.Permissions.ManageReCaptchaSettingsbecomesOrchardCore.ReCaptcha.ReCaptchaPermissions.ManageReCaptchaSettingsOrchardCore.Security.StandardPermissions.SiteOwneris gone; assign users to theAdministratorsystem role instead.- See
references/permission-provider-examples.mdfor the full table. - Beware of 3.x members that returned the wrong permission. Replace them with the member of the same name, not the one in the obsolete message:
AdminMenu.Permissions.ManageAdminMenuandViewAdminMenuAllwere swapped; useAdminMenuPermissions.ManageAdminMenuandAdminMenuPermissions.ViewAdminMenuAlland re-check what each call site intends.CommonPermissions.CreateAssignRoleToUsersPermission(role)actually returned the edit-users-in-role permission.UsersPermissions.CreateAssignRoleToUsersPermission(role)now returns the real assign-role permission, so code relying on the old behavior must useUsersPermissions.CreateEditUsersInRolePermission(role).- Provider classes such as
OrchardCore.Workflows.Permissionsare still registered; only their static members were removed. - The
Permission(string name, string description, ...)constructors are[Obsolete]. PassLocalizationSource.Create("...", typeof(MyPermissions)). - Templates declared as a
Permission(for examplenew("ManageTeam_{0}", "Manage team {0}", [...])) and formatted by hand becomePermissionTemplatefields andCreateDynamicPermission(...)calls. ContentTypePermissionsHelper.PermissionTemplatesvalues arePermissionTemplateinstead ofPermission.CreateDynamicPermission(Permission template, ContentTypeDefinition),CreateDynamicPermission(Permission template, string contentType)andConvertToDynamicPermission(Permission)are[Obsolete]; useCreateDynamicPermissionOf(...)andGetPermissionTemplate(...).DeploymentStep.CategoryandTitleare alsoLocalizationSourcenow, exposed as read-only virtual properties that a step overrides (seeorchardcore-deployments).