Orchard Core Users & Roles - Prompt Templates
Manage Users, Roles, and Permissions
You are an Orchard Core expert. Generate code and configuration for user management, roles, and permissions.
Guidelines
- Enable
OrchardCore.UsersandOrchardCore.Rolesfor user and role management. - Declare permissions in a static
*Permissionsclass and expose them through anIPermissionProvider(seeorchardcore-permission-providers). - Create permission descriptions with
LocalizationSource.Create("...", typeof(MyPermissions)). - Use
IAuthorizationService.AuthorizeAsync(User, permission)for permission checks andhas_permissionin Liquid. - Reference built-in user permissions through
OrchardCore.Users.UsersPermissionsand role permissions throughOrchardCore.Roles.RolesPermissions. - Customize login, logout, registration, and password recovery with
ILoginFormEvent,ILogoutFormEvent,IRegistrationFormEvents, andIPasswordRecoveryFormEvents. - Read
RegistrationOptionsandExternalLoginOptionsthroughIOptionsMonitor<T>.CurrentValue; they refresh when site settings change. - Enable
OrchardCore.RateLimitsto throttle login, registration, password recovery, and confirmation-email endpoints (seeorchardcore-rate-limits). - Passkeys, two-factor authentication and the user Security page (
/Security) are covered byorchardcore-passkeys. - External authentication providers live in their own skills (
orchardcore-google,orchardcore-microsoft-auth,orchardcore-facebook,orchardcore-github-authentication,orchardcore-twitter,orchardcore-openid).
Enabling User and Role Features
{
"steps": [
{
"name": "Feature",
"enable": [
"OrchardCore.Users",
"OrchardCore.Users.Registration",
"OrchardCore.Users.ResetPassword",
"OrchardCore.Users.CustomUserSettings",
"OrchardCore.Roles"
],
"disable": []
}
]
}
Other Users features include OrchardCore.Users.ExternalAuthentication, Users Change Email, User Time Zone, User Localization, Users Authentication Ticket Store (server-side tickets in memory or distributed cache), Users Audit Trail, the Two-Factor Email, Authenticator App, and SMS methods (OrchardCore.Users.2FA.Email, OrchardCore.Users.2FA.AuthenticatorApp, OrchardCore.Users.2FA.Sms), and Passkeys (OrchardCore.Users.Passkeys). The two-factor methods and Passkeys enable User Security (OrchardCore.Users.Security, the Security page) by dependency; see orchardcore-passkeys.
Defining Custom Permissions
using OrchardCore.Localization;
using OrchardCore.Security.Permissions;
namespace MyModule;
public static class MyFeaturePermissions
{
public static readonly Permission ManageMyFeature = new(
"ManageMyFeature",
LocalizationSource.Create("Manage my feature", typeof(MyFeaturePermissions)));
public static readonly Permission ViewMyFeature = new(
"ViewMyFeature",
LocalizationSource.Create("View my feature", typeof(MyFeaturePermissions)),
[ManageMyFeature]);
}
using OrchardCore;
using OrchardCore.Security.Permissions;
namespace MyModule;
internal sealed class PermissionProvider : IPermissionProvider
{
private readonly IEnumerable<Permission> _allPermissions =
[
MyFeaturePermissions.ManageMyFeature,
MyFeaturePermissions.ViewMyFeature,
];
public Task<IEnumerable<Permission>> GetPermissionsAsync()
=> Task.FromResult(_allPermissions);
public IEnumerable<PermissionStereotype> GetDefaultStereotypes() =>
[
new PermissionStereotype
{
Name = OrchardCoreConstants.Roles.Administrator,
Permissions = _allPermissions,
},
new PermissionStereotype
{
Name = "Editor",
Permissions = [MyFeaturePermissions.ViewMyFeature],
},
];
}
Registering Permission Provider
public sealed class Startup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddPermissionProvider<PermissionProvider>();
}
}
Checking Permissions in Code
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
public sealed class MyController : Controller
{
private readonly IAuthorizationService _authorizationService;
public MyController(IAuthorizationService authorizationService)
{
_authorizationService = authorizationService;
}
public async Task<IActionResult> Index()
{
if (!await _authorizationService.AuthorizeAsync(User, MyFeaturePermissions.ViewMyFeature))
{
return Forbid();
}
return View();
}
}
Role-specific user permissions are created from UsersPermissions, for example UsersPermissions.CreateAssignRoleToUsersPermission("Editor"), CreateEditUsersInRolePermission, CreateDeleteUsersInRolePermission, CreateListUsersInRolePermission, and CreatePermissionForManageUsersInRole. They are built from internal PermissionTemplates, so their descriptions ("Edit users in Editor role") are context-free and translated through Data Localization.
Checking Permissions in Liquid
{% if User | has_permission: "ViewMyFeature" %}
<p>You have access to this feature.</p>
{% endif %}
The Administrator role does not receive permission claims during login. Use has_permission instead of checking a permission claim with has_claim.
Login Settings via Recipe
{
"steps": [
{
"name": "Settings",
"LoginSettings": {
"UseSiteTheme": false,
"DisableLocalLogin": false,
"AllowRememberMe": true,
"UsePersistentAuthenticationCookie": false,
"AllowChangingUsername": false,
"AllowChangingEmail": false,
"AllowChangingPhoneNumber": true
}
}
]
}
Login settings are edited in Settings → Security → User Login, whose tabs are General, Two-Factor Authentication (TwoFactorLoginSettings), Security Page (UserSecuritySettings.UseSiteTheme, the theme of the Security page and the pages it links to) and External Login. UseSiteTheme of LoginSettings only themes the login page; TwoFactorLoginSettings.UseSiteTheme was replaced by UserSecuritySettings.UseSiteTheme.
UsePersistentAuthenticationCookie (Use persistent authentication cookies by default) controls whether local and external sign-ins survive browser restarts. With AllowRememberMe enabled it is the default value of the Remember me checkbox; with AllowRememberMe disabled it decides persistence for every sign-in.
Registration and External Authentication Settings via Recipe
{
"steps": [
{
"name": "Settings",
"RegistrationSettings": {
"UsersMustValidateEmail": true,
"UsersAreModerated": false,
"UseSiteTheme": false
},
"ResetPasswordSettings": {
"AllowResetPassword": true,
"UseSiteTheme": false
},
"ExternalLoginSettings": {
"UseExternalProviderIfOnlyOneDefined": false,
"UseScriptToSyncProperties": false,
"SyncPropertiesScript": ""
},
"ExternalRegistrationSettings": {
"DisableNewRegistrations": false,
"NoPassword": false,
"NoUsername": false,
"NoEmail": false,
"UseScriptToGenerateUsername": false,
"GenerateUsernameScript": ""
}
}
]
}
With OrchardCore.Deployment enabled, Login, Registration, Reset Password, Change Email, External login, and External registration settings each have a deployment step. The Change Email settings step exports ChangeEmailSettings; in 3.x it exported the wrong type, so plans exported with it did not carry the Change Email settings.
The Generate username script receives context with userName, loginProvider, and externalClaims; set context.userName. The Sync properties script receives context and fills rolesToAdd, rolesToRemove, claims, and properties. Orchard passes the per-login data through the scoped externalLoginContext() global, so write scripts against context and never build script text from user data.
Email Confirmation
When UsersMustValidateEmail is enabled, an unconfirmed user who signs in with a valid password lands on a page with Send confirmation email. The action is offered for about 10 minutes in the same browser (a short-lived cookie, not a sign-in), at most once per minute per user, and, with Rate Limits enabled, 2 requests per minute on the ResendEmailConfirmation route (email-confirmation policy), counted against the user who passed the password check, not the IP address.
A user also receives at most one password reset email per minute; further requests during that minute show the same confirmation page without sending an email, so the page does not reveal whether the account exists. Linking an external login to an existing account with its password counts a failed password check toward the account lockout, like the login page.
Login, Logout, and Registration Events
using OrchardCore.Users;
using OrchardCore.Users.Events;
public sealed class AuditLogoutFormEvent : LogoutFormEventBase
{
public override Task LoggingOutAsync(IUser user, CancellationToken cancellationToken = default)
{
// Runs before sign-out, while the principal is still available.
return Task.CompletedTask;
}
public override Task LoggedOutAsync(IUser user, CancellationToken cancellationToken = default)
{
// Runs after sign-out.
return Task.CompletedTask;
}
}
services.AddScoped<ILogoutFormEvent, AuditLogoutFormEvent>();
services.AddScoped<IRegistrationFormEvents, MyRegistrationEvents>();
ILoginFormEventincludesTask<IActionResult> ValidatingLoginAsync(IUser user).IRegistrationFormEventsincludesTask RegisteringAsync(UserRegisteringContext context); derive fromRegistrationFormEventsBaseto override only what you need.- With
OrchardCore.Workflows, the User Loggedout Event (UserLoggedOutEvent) complements User Loggedin Event. - External-login forms post to
ExternalAuthenticationsController, notAccountController.
Reading Settings-Backed Options
using Microsoft.Extensions.Options;
using OrchardCore.Users.Models;
public sealed class RegistrationGate
{
private readonly IOptionsMonitor<RegistrationOptions> _registrationOptions;
public RegistrationGate(IOptionsMonitor<RegistrationOptions> registrationOptions)
{
_registrationOptions = registrationOptions;
}
public bool RequiresEmailConfirmation()
=> _registrationOptions.CurrentValue.UsersMustValidateEmail;
}
Rate-Limited User Endpoints
When OrchardCore.RateLimits is enabled, Users registers these route limits (per minute). The anonymous endpoints are counted per IP address and sized for users who share a network; account lockout and the one-email-per-minute rules protect each account.
| Endpoint (POST) | Limit | Counted against |
|---|---|---|
| Login, link external login (password-authentication policy, shared with the OpenID password grant) | 100, sliding window | IP address |
| Registration, external registration | 20 | IP address |
| Forgot password, reset password | 20 | IP address |
| Resend confirmation email | 2 | User who passed the password check |
| Two-factor code / recovery code | 5 / 3 | User who passed the password check |
| Email or SMS authenticator send code | 2 | User who passed the password check |
| Passkey login (Passkeys/Login, password-authentication policy) | 10, sliding window | IP address |
See orchardcore-rate-limits to tune them.
Configuration Sections
{
"OrchardCore": {
"Users": {
"LoginPath": "Login",
"LogoffPath": "Users/LogOff",
"ChangePasswordUrl": "ChangePassword",
"ChangePasswordConfirmationUrl": "ChangePasswordConfirmation",
"ExternalLoginsUrl": "ExternalLogins",
"SecurityPath": "Security",
"TwoFactorAuthenticationPath": "TwoFactor"
},
"Roles": {
"AdminRoleName": "Administrator"
}
}
}
Creating Roles via Recipe
{
"steps": [
{
"name": "Roles",
"Roles": [
{
"Name": "{{RoleName}}",
"Description": "{{RoleDescription}}",
"PermissionBehavior": "Replace",
"Permissions": [
"ViewMyFeature",
"AccessAdminPanel"
]
}
]
}
]
}
PermissionBehavior is Replace (default), Add (append missing permissions), or Remove (remove listed permissions).
AssignRoleToUsers is not implied by EditUsers. Grant AssignRoleToUsers explicitly, or a role-specific AssignRoleToUsers_{RoleName} permission.
Roles Admin
ViewRoles(implied byManageRoles) gives read-only access to the roles list and a role's permissions.- The role Create page has Save & Configure to go straight to the permission editor; the Edit page has Save and continue.
- System roles (
Administrator,Anonymous,Authenticated) cannot be deleted, andAdministratorcannot be edited. - Permission descriptions are translated with PO files; only context-free descriptions, templated permissions such as "Edit Article", and categories use Data Localization.
Enabling and Disabling Users
await _userService.EnableAsync(user);
await _userService.DisableAsync(user);
Creating Users from a Recipe
{
"steps": [
{
"name": "command",
"Commands": [
"createUser /UserName:admin /Password:{{Password}} /Email:admin@example.com /Roles:Administrator"
]
}
]
}
Custom User Settings
Use the CustomUserSettings stereotype for per-user fields. See orchardcore-custom-user-settings.
User Editor Password Generator
The Generate password button of the user editor uses the generatePassword default export of @orchardcore/bloom/helpers/passwordGenerator, which draws characters with crypto.getRandomValues() (a cryptographically secure RNG) instead of Math.random(). The password-generator script resource (window.passwordManager) is still registered but deprecated and will be removed in a future major version; custom editors should import the Bloom helper instead.
Upgrading from 3.x
OrchardCore.Users.CommonPermissionswas removed; useOrchardCore.Users.UsersPermissions(same member names).CommonPermissions.CreateAssignRoleToUsersPermission(role)returned the edit-users-in-role permission in 3.x.UsersPermissions.CreateAssignRoleToUsersPermission(role)returns the real assign-role permission; code that relied on the old result must callCreateEditUsersInRolePermission(role).StandardPermissions.SiteOwneris gone; use theAdministratorrole.Permission.Descriptionis aLocalizationSource; use.ValueorIStringLocalizerFactory.Localize(permission.Description).IOptions<RegistrationOptions>andIOptions<ExternalLoginOptions>becomeIOptionsMonitor<T>withCurrentValue.- Rename configuration sections
OrchardCore_UserstoOrchardCore:UsersandOrchardCore_RolestoOrchardCore:Roles(old names still work but are deprecated). - Rate limits of the user endpoints were raised (login 10 to 100, registration 3 to 20, password recovery 5 to 20 per minute) and the confirmation-email and two-factor limits are counted per user instead of per IP. Re-check tenant policies that relied on the old values.
- Stop depending on the
password-generatorscript resource; use the BloomgeneratePasswordhelper. - The two-factor page became a section of the Security page:
TwoFactorAuthentication/Index.cshtmlis now theUserSecurityTwoFactorshape,UserMenuItems-TwoFactorisUserMenuItems-Security,/TwoFactorredirects to/Security, and recipes setUserSecuritySettings.UseSiteThemeinstead ofTwoFactorLoginSettings.UseSiteTheme(seeorchardcore-passkeys). - The users list rows changed: the user name is a title link, the email an outlined badge, and
UserRolesMetamoved from theDescriptionzone toMeta(SummaryAdmin).UserDisplayName.SummaryAdminGridrenders users as badges in Grid lists. Re-check overrides ofUserFields.cshtmlandUserRolesMeta.cshtml.