Security
This guide walks through what Osirion.Blazor does to keep rendered content safe, what you must do yourself, and how to configure the pieces a production site needs: a Content Security Policy, secrets, rate limiting and antiforgery. It is for developers who are about to put a site on the internet.
It states what the code does. It does not promise that a site is secure: your own components, your hosting and your configuration decide that.
Before you start
- A running site on Osirion.Blazor 4.1.0 (see Getting started).
- Content from a source you do not fully control, such as pull requests to a content repository, is the case this guide protects against. Content that only you write is lower risk, but the same steps apply.
Keep sanitizing on
Markdown is rendered to HTML, and that HTML is sanitized with an allow-list (HtmlSanitizer on the AngleSharp HTML5
parser) in two places: when content is ingested from a provider, and again where it is written into the page as raw
markup (OsirionHtmlRenderer, ContentView, LocalizedContentView, DocumentPage). AddOsirion registers the
sanitizer with its default allow-list.
By default the sanitizer keeps common content markup, class, id, role, every aria-* attribute, the
text-align of table cells, and the URL schemes http, https, mailto and tel plus relative URLs. It removes
forms and form controls, iframes, style elements and inline styles (except text-align in table cells), the
name attribute, event handler attributes and the javascript:, vbscript: and data: schemes. The elements
script, svg, math, template, object, embed, applet, meta, base, link, frame, frameset and
noscript can never be allowed, whatever the options say.
If your content needs more, extend the allow-list instead of turning sanitizing off:
using Osirion.Blazor.Core.Extensions;
builder.Services.AddOsirionHtmlSanitizer(options =>
options.AllowElement("chart", "type", "title", "caption", "colors"));
AllowElement keeps the attributes you list on that element only, in addition to the attributes every element may carry. An element you allow becomes your
responsibility: if your own script writes one of its attribute values into innerHTML, the browser can turn escaped
text back into markup. Read such values with textContent or setAttribute.
OsirionHtmlRenderer.SanitizeHtml defaults to true. Set it to false only for markup your application built
itself, never for content, user input or anything read from a repository:
<OsirionHtmlRenderer HtmlContent="@fromYourCode" SanitizeHtml="false" />
Front matter json_ld (under seo_properties) is parsed and written again with <, > and & escaped before it goes into a script element;
invalid JSON-LD is dropped and a warning is logged.
Know the URL rules
Links and image addresses can come from content or configuration, so components check them before they write an
href or src:
| Where | Allowed |
|---|---|
| Sanitized HTML (rendered Markdown) | Relative URLs, http, https, mailto, tel |
Menu, MenuItem, MenuGroup footer, MenuPanelLink, MenuImageCard, MenuCallToAction and the brand link |
Relative URLs, http, https, mailto, tel; any other scheme renders no href |
OsirionAuthorCard (avatar, profile and link addresses), OsirionPricingTable (button address) and OsirionCallToActionSection (button addresses) |
A path on the site, a fragment of the page (#section), or an absolute http, https, mailto or tel address (tel: and fragments from the release after 4.2.0) |
A path on the site starts with one / and is not protocol-relative (//host). The check behind the last row is
SafeLink.IsSafe in Osirion.Blazor.Core.Utils; it is internal up to 4.2.0 and public in the release after 4.2.0, for
links you render yourself. InfiniteLogoCarousel applies the same check in the release after 4.1.0; in 4.1.0 it writes
any Url into href, so pass it only addresses you control. The OsirionSiteLayout call to action, which arrives in
the release after 4.2.0, applies it when the application starts and again when the layout renders.
HeroSection and OsirionBaseSection escape the image address before they write it into a CSS url(), so a front
matter featured_image cannot add style rules.
Pass only trusted text to raw HTML parameters
A few parameters are written into the page as raw HTML, without sanitizing, so you can use inline markup in them. Pass only text you wrote:
| Component | Raw HTML parameters |
|---|---|
OsirionFooter |
Description, Copyright |
OsirionBaseSection |
Title, Description |
OsirionContactForm |
PrivacyPolicyText |
OsirionSubscriptionCard |
Title, Description, PrivacyPolicyText |
ContentPage |
FooterContent, ShareLink.Icon |
OsirionStyles |
CustomVariables, written as raw CSS |
Never bind these to visitor input or to text from a content repository. For a title that must contain content you do
not control, use the component's template parameter (TitleContent on OsirionBaseSection) instead.
Write a Content Security Policy
OsirionStyles takes a Nonce parameter and writes it on its inline script and inline style elements, so a site that
uses only OsirionStyles and ThemeToggle or ThemePicker can run a policy without 'unsafe-inline' for them (see
the nonce example below). The other components in the table still write inline script or style and add no nonce, so a
site that uses them still needs 'unsafe-inline' or must leave them out. The table shows what each component needs:
| Component | Needs |
|---|---|
OsirionStyles |
An inline script that sets the theme attributes before first paint, and inline style elements when CustomVariables or generated theme variables are written. All of them carry the Nonce parameter as a nonce attribute, so 'nonce-...' allows them. osirion-styles.js is a file from your own origin |
ThemeToggle |
Nothing inline: a click listener in theme-toggle.js does the work, and the page needs OsirionStyles as well |
ThemePicker |
Nothing inline: no inline script and no event handler attribute |
ScrollToTop, EnhancedNavigation |
One inline script each |
OsirionHtmlRenderer |
An inline onclick on the Copy button (EnableCopyButton). The accessible code theme (UseAccessibleTheme) is part of css/osirion-html-renderer.min.css, a file from your own origin, in the release after 4.2.0, and an inline style element up to 4.2.0; Prism from cdnjs.cloudflare.com, or from your own site with AddOsirionPrism (see Content Security Policy) |
OsirionFooter |
Nothing inline in the release after 4.2.0; up to 4.2.0, an inline style element and a style attribute on the brand |
Components with a Style parameter |
style-src that allows inline style attributes |
| Analytics: GA4, Clarity, Matomo, Plausible, Yandex Metrica | An inline script, and the provider's own script host |
| Analytics: Umami | An external script tag only |
Matomo and Yandex Metrica with AutoTrackPageViews |
An external script from your own site, /_content/Osirion.Blazor.Analytics/js/osirion-analytics.js |
OsirionCookieConsent and the trackers with consent evaluated in the browser (Evaluation Browser) |
Nothing inline for the consent itself: osirion-consent.js is a file from your own origin and uses no event handler attribute or eval. The trackers keep their needs above: the held inline snippet runs with its text unchanged, so its hash allows it |
A site exported to static files cannot send a new nonce with every response, so allow the inline tracker snippets by
hash: 'sha256-...' of each snippet's text in script-src, next to 'self' and the provider hosts. The text depends
on the tracker's settings and on the library version, so recompute the hashes when either changes; the browser console
names the expected hash of a blocked script. With the hashes in place, the trackers that run after consent are
allowed and an injected inline script is still blocked. That holds for a policy of hosts and hashes, not for one with
'strict-dynamic': there the trust in osirion-consent.js passes to every script it starts, and it starts every held
script (type="text/plain" with data-osirion-consent) anywhere on the page once the visitor's answer includes its
category, which for necessary is every answer. A held script that an HTML injection puts on the page then runs,
where the same script injected directly is blocked. The sanitizer removes script elements from content, so this needs
an injection elsewhere, such as raw HTML from a parameter; with 'strict-dynamic', treat keeping such markup out of
the page as the defense. See Sites exported to static files.
The practical policy for 4.1.0 allows inline script and style from your own origin, and adds the hosts of the services you use:
app.Use(async (context, next) =>
{
context.Response.Headers.ContentSecurityPolicy =
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'";
await next();
});
Be clear about what this gives you: with 'unsafe-inline' in script-src, the policy no longer stops an injected inline
script. The sanitizer (Keep sanitizing on) is then the defense that matters, so do not weaken it. The script of OsirionStyles
contains the current theme, so its text changes between requests and a fixed hash would not cover it; use a nonce.
A strict policy for OsirionStyles needs a new random nonce for every response, the same value in the header and in the
Nonce parameter. Generate it in middleware and hand it to the layout:
app.Use(async (context, next) =>
{
var nonce = Convert.ToBase64String(RandomNumberGenerator.GetBytes(16));
context.Items["csp-nonce"] = nonce;
context.Response.Headers.ContentSecurityPolicy =
$"default-src 'self'; script-src 'self' 'nonce-{nonce}'; style-src 'self' 'nonce-{nonce}'";
await next();
});
@* App.razor, a static server rendered component *@
<OsirionStyles Nonce="@(HttpContext?.Items["csp-nonce"] as string)" />
@code {
[CascadingParameter]
private HttpContext? HttpContext { get; set; }
}
The nonce does not cover inline style attributes: a component with a Style parameter, or one that writes a style
attribute, still needs style-src-attr 'unsafe-inline' or style-src 'unsafe-inline' without a nonce, or the hash of
each attribute value with 'unsafe-hashes', as below.
Inline style attributes
In the release after 4.2.0, the defaults of OsirionHtmlRenderer, OsirionFooter, Menu, HeroSection,
OsirionCookieConsent, OsirionContentNotFound, OsirionTestimonialCard and OsirionReadMoreLink write no style
attribute and no style element: the sticky Menu's z-index, HeroSection's min-height: 60vh, the
OsirionFooter rules, the Customize button of OsirionCookieConsent, the buttons of OsirionContentNotFound, the
read more link of OsirionTestimonialCard and the accessible code theme of OsirionHtmlRenderer moved into
stylesheets, and OsirionReadMoreLink no longer writes an empty style="". Other components still write a style
attribute with their defaults; they are listed below the table. What the components on a typical page leave is
fixed text, so a site exported to static files can allow each value by its hash. A hash of a style attribute needs
'unsafe-hashes' next to it; it allows only that exact value, not any other inline style:
| Source | Attribute value | Hash |
|---|---|---|
BlazorJSComponents, which loads the library's scripts: one bl-script element per script |
display: none; !important |
'sha256-EXrMEQM0mPkgnkB6KboseHKD5Hs/aDUfUef9LAWu4uA=' |
| Markdown table column alignment, the one inline style the sanitizer keeps | text-align: left |
'sha256-6l+tpow5lGPV0MHWZlDv8nD7HrL77FGFldqQ7zc5gxY=' |
text-align: center |
'sha256-Y9v1MZrln1N8aPBY5lmpxYKwFkcp/nyBMMEnn7WFjuw=' |
|
text-align: right |
'sha256-i0JPB0qmRu5AViJTxOIzqXnfGoiWFw+oNAm4uJd7ZQk=' |
|
ScrollToTop, which also needs an inline script |
display: none; |
'sha256-biLFinpqYMtWHmXfkA1BPeCY0/fNt46SAZ+BBk5YUog=' |
BlazorJSComponents is a third-party package; its attribute only hides the element and the page looks the same when
the browser blocks it, so leaving the hash out costs one console report per page and nothing else. A typical page of
the library, with a policy that also serves Prism from your own site
(AddOsirionPrism):
style-src 'self' 'unsafe-hashes' 'sha256-EXrMEQM0mPkgnkB6KboseHKD5Hs/aDUfUef9LAWu4uA=';
Add the three alignment hashes when your Markdown has aligned table columns. These components write a style
attribute even with their default parameters, because the value carries custom properties that the component works
out from its parameters and items: OsirionImageGallery (columns and gap), InfiniteLogoCarousel (speed and logo
sizes), OsirionTestimonialCarousel (speed and card sizes), OsirionResponsiveShowcaseSection (the viewport size)
and the feature list of LandingPage (its column count). On a page that uses one, allow the exact value by its hash
with 'unsafe-hashes', or use style-src-attr 'unsafe-inline'. Values that you pass in parameters are written
inline as given, so they are yours to allow or to move into your stylesheet: Style on any component,
HeroSection's MinHeight other than 60vh, BackgroundColor, TextColor and a background ImageUrl, the
background settings of OsirionBaseSection, a Menu StickyZIndex other than 1000 or a Menu with a Style,
OsirionStickySidebar's TopOffset, the non-default sizes of the components above, and the call to action color of
LandingPage. When the browser blocks one, its console names the hash it expected. OsirionStyles writes CustomVariables and the
configured variables in style elements, which take the Nonce; on a static export, where no nonce is possible, the
element's text is fixed by your configuration, so its hash (without 'unsafe-hashes') allows it.
Know which cookies the library sets
| Cookie | Set by | Flags |
|---|---|---|
osirion-preferred-theme |
ThemeService on the server; ThemeToggle in the browser |
Path /, one year, SameSite=Lax, not HttpOnly (the page script reads and replaces it). Secure from the server; the toggle's script adds Secure on HTTPS pages |
osirion-preferred-palette |
ThemeService on the server; ThemePicker in the browser |
Path /, one year, SameSite=Lax, not HttpOnly. Secure from the server; the picker's script adds Secure on HTTPS pages |
osirion_cookie_consent |
The cookie consent endpoint (MapOsirionCookieConsent); with consent evaluated in the browser, osirion-consent.js |
Path /, HttpOnly, Secure, SameSite=Lax from the endpoint. From the script: path /, SameSite=Lax, Secure on HTTPS pages, not HttpOnly (script writes and reads it), same value format. Lifetime comes from ConsentExpiryDays (default 365) |
osirion_announcement_<id> |
The announcement endpoint (MapOsirionAnnouncements) |
Path /, HttpOnly, Secure, SameSite=Lax, essential. 30 days unless the form posts 1 to 365 |
The theme and palette cookies hold a short name such as dark, no personal data. Every cookie the server sets is
Secure, so a browser drops it on plain HTTP other than localhost, which browsers treat as secure: serve the site
over HTTPS, or the banners can return on every page.
The consent and announcement endpoints require an antiforgery token, which their forms carry. See Protect the contact form.
Keep secrets out of source
Tokens and keys do not belong in appsettings.json. These settings are secrets:
| Setting | Key |
|---|---|
| GitHub token for a content provider | Osirion:Cms:Web:GitHub:<Name>:ApiToken |
| GitHub webhook secret | Osirion:Cms:Web:GitHub:<Name>:WebhookSecret |
| SendGrid key | Osirion:Email:SendGrid:ApiKey |
| SMTP password | Osirion:Email:Smtp:Password |
| Infobip key | Osirion:Email:Infobip:ApiKey |
<Name> is the name of the provider in your configuration, for example Site. In development, store them with user
secrets:
dotnet user-secrets init
dotnet user-secrets set "Osirion:Cms:Web:GitHub:Site:ApiToken" "<your token>"
dotnet user-secrets set "Osirion:Email:SendGrid:ApiKey" "<your key>"
In production, use environment variables, where : becomes __ (Osirion__Cms__Web__GitHub__Site__ApiToken), or your
secret store. For a site that only reads content, give the GitHub token access to read that repository's contents and
nothing more.
Protect the contact form
The OsirionContactForm has three layers, and only one of them is automatic:
- Antiforgery. The form is an
EditForm, which adds an antiforgery token for you. The token is checked only when your pipeline callsapp.UseAntiforgery(). The cookie consent and announcement endpoints also need it: without the middleware, ASP.NET Core throws for every post to them. - A honeypot. The form has a hidden
Websitefield that people do not see and that is off screen,aria-hiddenand out of the tab order. A submission with that field filled is treated as spam and answered with the spam message. This stops simple bots that fill every field. It does not stop a person or a bot that leaves the field empty. - A rate limit, which you add. The library has none. Without one, anyone can post the form as often as they like, and each post sends an email through your provider. Limit posts per address with the ASP.NET Core rate limiter:
using System.Threading.RateLimiting;
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(context =>
HttpMethods.IsPost(context.Request.Method)
? RateLimitPartition.GetFixedWindowLimiter(
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 5,
Window = TimeSpan.FromMinutes(1),
})
: RateLimitPartition.GetNoLimiter("not-a-post"));
});
var app = builder.Build();
app.UseRateLimiter();
app.UseAntiforgery();
The numbers are an example; choose your own. The limiter counts every post from an address, including the cookie
consent and announcement forms, and it sees the contact form only when the page handles it as a post, which is what
happens without an interactive render mode. Under Interactive Server the submit travels over the circuit, so limit it in
your OnSubmit handler instead. Behind a reverse proxy, RemoteIpAddress is the proxy's address unless you
configure forwarded headers, and then every visitor shares one limit.
Check that it works
- A post that contains
<script>alert(1)</script>in its Markdown shows the text or nothing, and no script runs. curl -s -D - -o /dev/null https://your-site/shows yourContent-Security-Policyheader. AHEADrequest (curl -I) answers 405 on a page, so read the headers of aGET.- In the browser's cookie view,
osirion_cookie_consentshowsHttpOnly,SecureandLaxafter you accept the banner (with consent evaluated in the browser:Lax,Secureon HTTPS, and notHttpOnly). - With consent evaluated in the browser, the browser's network panel shows no request to a tracker host before you answer the banner, and none after Decline.
git grep -n -e ghp_ -e github_pat_finds no GitHub token in your repository.- The sixth rapid post of the contact form from one address gets status 429.
Next steps
OsirionHtmlRenderer: the sanitizing parameters and the Prism hosts.OsirionContactFormandOsirionCookieConsent.- Analytics package: the consent gate and what each tracker writes.
- Troubleshooting: symptoms and fixes, including a theme toggle that does nothing.