Orchardcore users roles

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore users roles is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for managing users, roles, and permissions in Orchard Core. Covers login, registration, and external authentication settings recipes, persistent authentication cookies, email confirmation resend, ILoginFormEvent and ILogoutFormEvent, the User Loggedout workflow event, RegistrationOptions and E

How to use this skill

Skill file

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

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>();

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

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

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.