Development noteson C#, .NET Core and Orchard Core CMS. Useful bits of information, code snippets, tips, and tricks worth remembering!

Orchard Core Search and Query Lucene Search Index Permissions

Orchard Core has a search feature that allows Orchard Core developers to provide search functionality for the Orchard Core website. Search is automatically enabled as soon as you enable the Lucene feature. The fact that search is automatically enabled is unfortunate and will hopefully be changed, because Lucene queries are useful for a lot more than just search in Orchard Core, and a developer will often want to use Lucene queries without wanting search. As soon as you enable Lucene, when you navigate to "/search" on your Orchard Core website you will be greeted with an unfriendly, but necessary, message:

Search is not configured.

At this point you will want to create and properly configure a Lucene Search Index, making sure you have included the necessary Orchard Core content types and fields as part of the search index. Full-text search requires a bit more configuration if you have searchable content in places other than body parts and display text.

Once you have properly configured search for the Orchard Core website there is a step that is often forgotten and overlooked by the Orchard Core Developer - making sure the Query Lucene Search Index is allowed by the anonymous role! This is easily overlooked by the Orchard Core developer because the developer is often a part of the administrator role and authenticated when developing the website. As such, when the developer searches the Orchard Core website, the search results for the search terms will display accordingly. However, anonymous users will not be able to search the Orchard Core website. Instead, anonymous users will be greeted with the Orchard Core login page, requesting them to authenticate in order to search the Orchard Core website.

As such, the Orchard Core developer needs to allow the anonymous role to have permissions to query the Lucene Search Index. This can be done in the Orchard Core Admin Dashboard. Navigate to Security -> Roles -> Anonymous in Orchard Core and allow permissions to Query Lucene Search Index.

Query Lucene Search Index - Orchard Core

Anonymous users will now be able to search the Orchard Core website for content.

VS Code's Monaco Editor in Orchard Core

A good part of my day is spent in the backend of Orchard Core managing content for clients as well as myself. Although I like to use markup whenever possible for adding content to Orchard Core websites, there are times when you need to enter HTML.

Orchard Core supports multiple HTML editors for entering content. One can go old school with a simple multiline textarea for adding HTML content in Orchard Core, or pick a lightweight WYSIWYG editor, like Trumboyg or TinyMCE.

I've been developing with HTML for decades so I typically use the standard editor for HTML in Orchard Core, called Code Mirror. It's not a WYSIWYG editor, which saves me from having the editor alter the code behind the scenes or add extra HTML when performing copy and paste. If you're not as familiar with HTML or won't suffer from the small issues I mention above, one of the WYSIWYG editors is your best bet. I talked more about Code Mirror and other HTML editors in the Orchard Core developer note: HTML Field and Text Field Editors for Orchard Core CMS.

Recently, and by recently I mean yesterday :), another editor was added to Orchard Core, the Monaco editor. The Monaco editor is the same editor used in Visual Studio Code and enjoyed by millions of developers. I use Visual Studio code a lot, thanks in part to the Monaco editor! It has a number of really cool features that make it a joy for development, and now we have the Monaco editor in Orchard Core!

VS Codes Monaco Editor in Orchard Core

If you haven't used the Monaco editor in VS Code, I guarantee you will enjoy a few of its features out-of-the-box in addition to the rich syntax highligthing and code completion. There is the ability to change all occurrences of a pattern, jump to a symbol while navigating around your content, format a document to beautify your code in nanoseconds, and more.

If you're an Orchard Core developer or administrator responsible for adding content to an Orchard Core website, I encourage you to experiment with the various HTML and code editors available in Orchard Core to see which best fits your needs. Sometimes you just need a simple multiline textarea or Code Mirror, other times you will want a WYSIWYG editor like Trumboyg or TinyMCE, and then there are times you may need a proven code editor used by Visual Studio Code, like Monaco!

Orchard Core .NET5 and C# 9

If you're a freelance Microsoft developer such as myself and have the pleasure of working on a lot of new projects that can be developed using .NET5 and C# 9, you'll love the fact that Orchard Core now supports multi-targeting and can target the .NET5 framework. This allows Orchard Core developers to use the new features in .NET5 as well as the new language features in C# 9 for their Orchard Core websites! This is great news for me in particular as I develop a lot of websites using ASP.NET Core Razor Pages and ASP.NET Core Web API's using .NET5 and C# 9, and it's nice to be able to focus on a single framework and language version.

Well after .NET5 was released, Orchard Core only supported .NET Core 3.1. If you were to create a new Orchard Core website from scratch and view the project file, you would see that indeed the Orchard Core website targeted .NET Core 3.1.

<PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    ...
</PropertyGroup>

In the latest pre-release of Orchard Core, Orchard Core developers now have the option of targeting .NET Core 3.1 or .NET5. There are numerous ways to specify that Orchard Core target .NET5, but the easiest way is to use the code generation tools and specify the .NET5 framework when creating the Orchard Core website using the Orchard Core project templates.


$ dotnet new occms -n Web -fm net5.0

Although the Orchard Core documentation suggests that Orchard Core will target .NET Core 3.1 by default, I haven't experienced that in my development. When I create a new Orchard Core CMS website from scratch and do not specify the framework, it also defaults to using .NET5.


$ dotnet new occms -n Web

It may be that the Orchard Core documentation needs to be updated, but to ensure your Orchard Core website targets .NET5 just check the project file.

<PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
    ...
</PropertyGroup>

As a freelance .NET developer, you can now focus all your development efforts on the .NET5 framework and C# 9 to develop Orchard Core websites, ASP.NET Core Razor Pages websites, ASP.NET Core Web API's, and Blazor apps!

Bootstrap Dashboard Theme for Orchard Core

I am receiving more and more requests from clients and freelance Orchard Core developers for training on themes related to dashboards and Admin Themes. Dashboard and Admin Themes are often composed of widgets that retrieve data from numerous different data sources, like queries, API's, custom database tables, event handlers, etc. There is also a fair amount of caching to balance busy dashboards and performance.

While on holiday break, I developed an Orchard Core dashboard theme based on the free HTML Admin Dashboard Template from Start Bootstrap. This is a great starter dashboard theme for beginning Orchard Core developers to get there feet wet with creating dashboards. The techniques and code are applicable to developing Admin Themes for Orchard Core as well. I'll be using this dashboard theme along with others for various Orchard Core presentations, developer workshops, and training of developers new to Orchard Core theme development.

Orchard Core Theme Developer - Bootstrap Dashboard Theme

The theme is intentionally built using a variety of data source and features in Orchard Core: Lucene and SQL Queries, Liquid Filters and EventHandlers, API's, custom services and database tables, Bag Part, List Part, etc. In addition to numerous data sources, the dashboad theme also includes custom menu items, admin menu items, shortcodes and shortcode templates, a custom setup recipe, custom content parts and content types, various data migrations including recipe migrations, etc. I've demonstrated as many Orchard Core features and techniques as possible to expose the beginning Orchard Core developer to the myriad of possibilities open to Orchard Core theme development with an emphasis on creating dashboards with custom widgets.

UserOptions in Orchard Core

Orchard Core allows you to customize the URL’s for user login, logoff, change password, and external logins. This is done by overriding the default UserOptions. The default UserOptions are defined in a UserOptions Class. As you can see below, the default URL's for user login, logoff, change password, and external logins are not only well documented, but quite intuitive and easy to guess.

public class UserOptions
{
    private string _loginPath = "Login";
    private string _logoffPath = "Users/LogOff";
    private string _changePasswordUrl = "ChangePassword";
    private string _externalLoginsUrl = "ExternalLogins";

    public string LoginPath
    {
        get => _loginPath;
        set => _loginPath = value.Trim(' ', '/');
    }

    public string LogoffPath
    {
        get => _logoffPath;
        set => _logoffPath = value.Trim(' ', '/');
    }

    public string ChangePasswordUrl
    {
        get => _changePasswordUrl;
        set => _changePasswordUrl = value.Trim(' ', '/');
    }

    public string ExternalLoginsUrl
    {
        get => _externalLoginsUrl;
        set => _externalLoginsUrl = value.Trim(' ', '/');
    }
}

Accepting the default UserOptions is probably fine if you're using Orchard Core CMS as a personal blog or marketing website that contains no sensitive or personal data and you're using a highly secure username and password. However, if you're running an Orchard Core website that contains personal data on customers or users of your website, I highly recommend you customize and override the default UserOptions for additional security. I think customizing UserOptions should be part of your new Orchard Core CMS website checklist in all cases.

Although you can override UserOptions using code, the easiest way to override UserOptions is via your appsettings.json file in your Orchard Core website. Again, choose less obvious URL's, but this gives you the idea.


"OrchardCore_Users": {
    "LoginPath": "SecureLogin",
    "LogoffPath": "Users/SecureLogOff",
    "ChangePasswordUrl": "SecureChangePassword",
    "ExternalLoginsUrl": "SecureExternalLogins"
}

Just like AdminUrlPrefix, creating custom URL's to your user login, logoff, change password, and external login adds additional security to your Orchard Core website. As a popular open source ASP.NET Core CMS, malicious visitors may target your Orchard Core CMS website for nefarious reasons. Don’t allow them to easily find the location of the user account and security pages and allow them to either take advantage of vulnerabilities in Orchard Core or attempt brute-force attacks.

You may want to peek at additional developer notes and tutorials on Orchard Core Security, too.

Orchard Core Forms and Workflow

Although I had followed the development of Orchard Core CMS for quite sometime, it wasn't until Orchard Core was released as beta 1 in June 2018 did I start developing Orchard Core Themes and Modules. One of the first themes I developed was the Coming Soon Theme from Start Bootstrap. This was before Coming Soon was added to Orchard Core CMS. The Coming Soon Theme is a one-page landing page announcing the upcoming Orchard Core CMS website with a simple signup form that allows one to be notified of the launch of the website. The form is simply an email field with an optional reCAPTCHA field to reduce spam. At the time I hadn't created a form in Orchard Core CMS and documentation was sparse. I decided to not create the form until there was more documentation.

At some point Coming Soon was bundled with Orchard Core CMS and I was excited to see how the form was implemented in the theme. It turns out creating a form in Orchard Core CMS is surprisingly simple and straight forward using the Form Part and Form Widget. What wasn't so simple and is still not simple is the workflow the Orchard Core Developer needs to create to process the form. Below is the workflow in Orchard Core CMS used for the subscriber form as of Orchard Core 1.0.0 rc2. This is a bit complex for a simple subscription form in Orchard Core asking for one's email address.

Orchard Core Worflow for a Form

Luckily the majority of my clients use separate online services, like JotForm, WuFoo, MailChimp, etc., and I've been able to avoid this complexity on most occasions by developing custom modules for Orchard Core CMS that integrate with these online services.

I look forward to future improvements in the way Orchard Core CMS handles forms such that the workflows are much simpler.

HTML Field and Text Field Editors for Orchard Core CMS

I spend a lot of time entering content into Orchard Core CMS as well as assisting clients with content management. The editor chosen for HTML Fields and Text Fields in Orchard Core makes a huge difference in the backend experience and each editor has its pros and cons.

I typically tend to avoid Wysiwyg editors in a CMS for 2 reasons. First, if you copy and paste into a Wysiwyg editor if often copies the HTML styles and tags from the source document in addition to the text. This is especially troublesome when copying and pasting from a word processor, like Microsoft Word. Second, a Wysiwyg editor often alters the HTML you might want to add to the contents of the HTML Field or Text Field, causing one to have to work around the editor. For simple needs and more experienced content contributors none of this may be a problem, but I've seen issues with this way too many times.

Although you may have to know a bit of HTML, I was delighted to see the addition of the Code Mirror editor in Orchard Core CMS for both HTML Fields and Text Fields. At one point I thought something broke in Orchard Core when the Code Mirror option was removed for HTML Fields. This occurred somewhere in the 1.0.0 RC2 builds. I was about to create an issue on the Orchard Core Issue tracker, but after some digging, I learned the Code Mirror option was removed because it was now the Standard editor for HTML Fields. Great choice!

If you like Code Mirror for HTML Fields in Orchard Core, you can also use it as an editor for Text Fields by modifying the properties of the Text Field. At this time, Code Mirror is not the Standard editor for Text Fields so you would need to modify the Text Field's settings manually and/or modify the theme's Orchard Core Recipe, depending on your situation.

Code Mirror Text Field Editor in Orchard Core CMS

I'm sure we'll see new editors added for the Text Field, HTML Field, and other Content Fields as Orchard Core CMS matures and more Orchard Core Developers come on board. It's really easy to create new editors for Orchard Core CMS and I look forward to new and other editors!

And just like that we have a new editor for managing content in Orchard Core. The Monaco editor used by Visual Studio Code is now in Orchard Core!

HTML Sanitizer and Sanitize Html Field Settings in Orchard Core CMS

An HTML Sanitizer is part of the Orchard Core Framework and used to protect the Orchard Core CMS website from accidental or malicious input from users that could lead to XSS attacks. It's automatically enabled by default for certain Content Parts and Content Fields in Orchard Core:

  • HTML Body Part
  • HTML Field
  • Markdown Body Part
  • Markdown Field

The Orchard Core Developer can enable and disable HTML sanitizing by modify the Content Part and Content Field settings. It's as simple as toggling the Sanitize Html checkbox.

Sanitize HTML in Orchard Core CMS

Unless you're having an issue, it's best to keep the Sanitize Html setting enabled. And even if you are having an issue, you may want to keep the Sanitize HTML setting enabled, and just modifying the configuration of the HTML Sanitizer to allow for the specific HTML tags or attributes that you wish to not be blocked by the sanitizer.

A perfect real-world scenario where we modified the configuration of the HTML Sanitizer in Orchard Core CMS was when developing an Orchard Core CMS website that used HTML data attributes to store extra information on standard, semantic HTML elements. As of right now, the default configuration of the HTML Sanitizer in Orchard Core CMS will remove the HTML data attributes. In our case, it was simply a data-id attribute on section tags. Below is an example for illustration purposes. Attempting to publish this HTML in an HTML Field in Orchard Core CMS with Sanitize HTML enabled will cause the data-id attribute to be removed from the section tag.

<section data-id="home">
    <div class="container">
        <div class="row">
            <div class="col">
                <p class="text-center">...</p>
            </div>
            <div class="col">
                <p class="text-center">...</p>
            </div>
        </div>
    </div>
</section>

We could disable sanitizing the HTML, but this seemed unnecessary for such a small need. Instead, we re-configured the HTML Sanitizer in Orchard Core to allow HTML data attributes.

public void ConfigureServices(IServiceCollection services) {
    services
        .AddOrchardCms()
        .ConfigureServices(tenantServices =>
            tenantServices.ConfigureHtmlSanitizer((sanitizer) =>
            {
                sanitizer.AllowDataAttributes = true;
            })
        );
}

With this small change we still have the protection against XSS attacks in the Content Parts and Content Fields in the Orchard Core CMS website, while allowing the use of HTML data attributes.

OpenID Connect and Token Validation in Orchard Core CMS

There are several Orchard Core tutorials showing how to use the GraphQL API via Postman to execute GraphQL queries in Orchard Core CMS. Some of these tutorials walk the Orchard Core Developer through configuring OpenID Connect in Orchard Core CMS to issue authentication tokens that can be submitted as part of the GraphQL query request.

Orchard Core CMS has several OpenID Connect features that can be enabled depending on the scenario. It's clear from the tutorials that the developer has to enable the OpenID Authorization Server feature, which will automatically enable both the OpenID Core Components and OpenID Management Interface.

At this point everything looks good and the Orchard Core Developer is able to create the application via the OpenID Management Interface and use Postman to retrieve the authentication token, but is unable to successfully execute a GraphQL query using the GraphQL API. Assuming the role has the proper permissions (claims) to execute GraphQL queries in Orchard Core CMS, it may be that the client is not authenticated because the developer hasn't enabled the OpenID Token Validation feature.

If this is the case, try the GraphQL query again via the GraphQL API once the OpenID Connect Token Validation feature has been enabled in Orchard Core CMS.

Orchard Core CMS and OpenID Connect Token Validation

GraphQL Permissions in Orchard Core CMS

The GraphQL feature in Orchard Core CMS includes GraphiQL, which is a snazzy GraphQL IDE that allows you to create and run GraphQL queries in the Orchard Core CMS administrative backend. However, it might not be obvious to you at the time, but the reason you can use GraphiQL and run the GraphQL queries is because you have the proper permissions. Most likely you have been assigned the Administrator role in Orchard Core, which by default gives you the ability to both execute GraphQL queries and GraphQL mutations.

Immediately after using GraphiQL, most Orchard Core Developers want to try the GraphQL API in Orchard Core CMS to run queries from Postman or similar API client. Unless you have the proper permissions, however, it won't work, and the GraphQL API hasn't always been forthcoming when it comes to letting you know it's a permissions problem.

If you're just getting your feet wet with GraphQL and the GraphQL API in Orchard Core using a test Orchard Core CMS Website, you can give the Anonymous Role permissions to execute GraphQL queries and mutations. This will allow you to sidestep OpenId or other authentication method for testing purposes. Once the Anonymous role in Orchard Core has permissions to execute GraphQL queries, you can easily execute the queries using the GraphQL API via Postman or other API client.

GraphQL Permissions in Orchard Core CMS

AdminUrlPrefix and appsettings.json in Orchard Core Tenants

Orchard Core allows you to customize the route to the backend on a tenant-by-tenant basis using the AdminUrlPrefix in the appsettings.json file. Using a custom prefix adds extra security so that visitors to your Orchard Core CMS website can't easily guess the location of the backend and allow them to either take advantage of vulnerabilities in Orchard Core or attempt brute-force attacks against your administrative login page.

Simply add AdminUrlPrefix to your tenant's appsettings.json file below with the prefix you would like to append to the admin backend. It is recommended for security reasons that you don't pick a prefix commonly used by other content management systems or host providers.

{
  "DatabaseProvider": "...",
  "RecipeName": "...",
  "OrchardCore_Admin": {
    "AdminUrlPrefix": "arugula"
  }
}

In addition to modifying AdminUrlPrefix, I highly recommend you override the UserOptions in your Orchard Core website to create custom and secure URL's for user login, logoff, change password, and external logins.

You can view more developer notes and tutorials on Orchard Core Security.