Orchardcore security

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore security is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for configuring security and authorization in Orchard Core. Covers declaring permissions with LocalizationSource descriptions, PermissionTemplate dynamic permissions, permission providers and stereotypes, IAuthorizationService checks, content authorization handlers, security headers through Se

How to use this skill

Skill file

Orchard Core Security - Prompt Templates

Configure Security and Authorization

You are an Orchard Core expert. Generate security and authorization configurations for Orchard Core.

Guidelines

Enabling Security Features

{
  "steps": [
    {
      "name": "feature",
      "enable": [
        "OrchardCore.Security",
        "OrchardCore.Https",
        "OrchardCore.Cors",
        "OrchardCore.ReverseProxy",
        "OrchardCore.RateLimits"
      ]
    }
  ]
}

Security Headers via Recipe

{
  "steps": [
    {
      "name": "settings",
      "SecuritySettings": {
        "ContentTypeOptions": "nosniff",
        "ReferrerPolicy": "strict-origin-when-cross-origin",
        "ContentSecurityPolicy": {
          "default-src": "'self'",
          "script-src": "'self'",
          "style-src": "'self' 'unsafe-inline'",
          "frame-ancestors": "'self'"
        },
        "PermissionsPolicy": {
          "camera": "()",
          "microphone": "()",
          "geolocation": "()"
        }
      }
    }
  ]
}

frame-ancestors replaces the obsolete X-Frame-Options header. Admin scripts in 4.0 load as ES modules without jQuery; test a strict script-src against the admin before removing 'unsafe-inline' for the whole site.

Security Headers from Configuration

Call ConfigureSecuritySettings() to let configuration override the admin values. The settings page then shows that values come from configuration.

builder.Services
    .AddOrchardCms()
    .ConfigureSecuritySettings();
{
  "OrchardCore": {
    "Security": {
      "ContentSecurityPolicy": {
        "default-src": "'self'"
      },
      "PermissionsPolicy": {
        "fullscreen": "self"
      },
      "ReferrerPolicy": "no-referrer"
    }
  }
}

Declaring Permissions

using OrchardCore;
using OrchardCore.Localization;
using OrchardCore.Security.Permissions;

namespace MyModule;

public static class InvoicePermissions
{
    public static readonly Permission ManageInvoices = new(
        "ManageInvoices",
        LocalizationSource.Create("Manage invoices", typeof(InvoicePermissions)),
        isSecurityCritical: true);

    public static readonly Permission ViewInvoices = new(
        "ViewInvoices",
        LocalizationSource.Create("View invoices", typeof(InvoicePermissions)),
        [ManageInvoices]);
}

public sealed class Permissions : IPermissionProvider
{
    private readonly IEnumerable<Permission> _allPermissions =
    [
        InvoicePermissions.ManageInvoices,
        InvoicePermissions.ViewInvoices,
    ];

    public Task<IEnumerable<Permission>> GetPermissionsAsync()
        => Task.FromResult(_allPermissions);

    public IEnumerable<PermissionStereotype> GetDefaultStereotypes() =>
    [
        new PermissionStereotype
        {
            Name = OrchardCoreConstants.Roles.Administrator,
            Permissions = _allPermissions,
        },
    ];
}

Register it with services.AddPermissionProvider<Permissions>(); (an internal sealed provider works too). The third constructor argument lists permissions that imply this one. Stereotypes are granted when the feature is installed and when a matching role is created; a role created while an installed feature is disabled gets them when the feature is enabled again, including for internal providers since 4.0 (see orchardcore-permission-providers). Display a description with IStringLocalizerFactory.Localize(permission.Description); read the raw text with permission.Description.Value.

Checking Permissions in a Controller

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OrchardCore.ContentManagement;
using OrchardCore.Contents;

namespace MyModule.Controllers;

public sealed class InvoiceController : Controller
{
    private readonly IAuthorizationService _authorizationService;
    private readonly IContentManager _contentManager;

    public InvoiceController(
        IAuthorizationService authorizationService,
        IContentManager contentManager)
    {
        _authorizationService = authorizationService;
        _contentManager = contentManager;
    }

    public async Task<IActionResult> Display(string contentItemId)
    {
        var contentItem = await _contentManager.GetAsync(contentItemId);

        if (contentItem == null)
        {
            return NotFound();
        }

        if (!await _authorizationService.AuthorizeAsync(User, CommonPermissions.ViewContent, contentItem))
        {
            return Forbid();
        }

        return View(contentItem);
    }
}

Custom Authorization Handler

using Microsoft.AspNetCore.Authorization;
using OrchardCore.ContentManagement;
using OrchardCore.Security;

namespace MyModule.Security;

public sealed class InvoiceOwnerAuthorizationHandler : AuthorizationHandler<PermissionRequirement>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        PermissionRequirement requirement)
    {
        if (requirement.Permission.Name == InvoicePermissions.ViewInvoices.Name &&
            context.Resource is ContentItem contentItem &&
            contentItem.Owner == context.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value)
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

Register with services.AddScoped<IAuthorizationHandler, InvoiceOwnerAuthorizationHandler>();. ContentItem.Owner stores the user ID.

API Endpoints and Error Responses

Secure API endpoints with the Api scheme and return Problem Details:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OrchardCore;

namespace MyModule.Controllers;

[ApiController]
[Route("api/invoices")]
[Authorize(AuthenticationSchemes = OrchardCoreConstants.AuthenticationSchemes.Api)]
public sealed class InvoiceApiController : ControllerBase
{
    private readonly IAuthorizationService _authorizationService;

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

    [HttpGet("{id}")]
    public async Task<IActionResult> Get(string id)
    {
        if (!await _authorizationService.AuthorizeAsync(User, InvoicePermissions.ViewInvoices))
        {
            return this.ApiForbidProblem();
        }

        return this.ApiNotFoundProblem();
    }
}

Anti-Forgery

Orchard Core forms include anti-forgery tokens automatically. Only bypass validation for endpoints that authenticate with bearer tokens:

[HttpPost]
[IgnoreAntiforgeryToken]
[Authorize(AuthenticationSchemes = OrchardCoreConstants.AuthenticationSchemes.Api)]
public IActionResult Import()
{
    return Ok();
}

Minimal APIs use .DisableAntiforgery() together with the Api scheme.

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.