Web Security
This page covers the web-layer security helpers Serenity ships for template applications: reCAPTCHA (bot protection on public forms), data-protector tokens (for links like email confirmation / password reset), the membership provider helper, and Content Security Policy (CSP) support. The core permission/user model is covered in Authentication & Authorization.
reCAPTCHA
Serenity provides server-side reCAPTCHA integration for public forms such as sign-up. It uses Google reCAPTCHA V2 keys.
Configuration
RecaptchaSettings holds the keys, bound from the Recaptcha configuration section (via [DefaultSectionKey]):
{
"Recaptcha": {
"SiteKey": "your-site-key",
"SecretKey": "your-secret-key"
}
}
Get the keys from the Google reCAPTCHA admin — generate keys for V2, not V3.
The Recaptcha editor
RecaptchaAttribute marks a form property to use the Recaptcha editor type. In the template's SignUpForm:
[FormScript("Membership.SignUp")]
public class SignUpForm
{
// ...
// make sure you have configured Recaptcha:SiteKey and Recaptcha:SecretKey in appsettings.json
[DisplayText(""), Recaptcha]
public string? Recaptcha { get; set; }
}
RecaptchaPropertyProcessor is a PropertyProcessor that runs when the form script is generated. It passes the configured SiteKey to the client-side editor via the siteKey editor parameter. If neither SiteKey nor SecretKey is configured, it hides the field and disables it (so the form still works without reCAPTCHA configured).
Server-side validation
RecaptchaValidation validates the token the client sends back. Validate(secretKey, token, localizer) posts the token to Google's siteverify endpoint and throws a ValidationError (code Recaptcha) if the token is empty or verification fails.
The template's sign-up action calls it only when reCAPTCHA is configured:
[HttpPost, JsonRequest]
public Result<SignUpResponse> SignUp(SignUpRequest request,
[FromServices] IEmailSender emailSender,
// ...
[FromServices] IOptions<RecaptchaSettings> recaptchaOptions,
// ...
)
{
return this.UseConnection("Default", connection =>
{
ArgumentNullException.ThrowIfNull(request);
if (!string.IsNullOrEmpty(recaptchaOptions?.Value?.SiteKey) ||
!string.IsNullOrEmpty(recaptchaOptions?.Value?.SecretKey))
{
RecaptchaValidation.Validate(recaptchaOptions.Value.SecretKey, request.Recaptcha, Localizer);
}
// ...
});
}
Data-Protector Tokens
DataProtectorBinaryTokenExtensions extends ASP.NET Core's IDataProtector to create and read tokens that carry binary data:
ProtectBinary(callback)— writes a token with aBinaryWriter(via the callback), protects it with the data protector, and returns it as a base64-url-encoded string.UnprotectBinary(token)— decodes and unprotects the token, returning aBinaryReaderover the decrypted data.
These are used for one-time tokens in links — for example, email confirmation or password reset links that carry a user ID and an expiry. The token is opaque to the client and tamper-proof (it is encrypted/signed by the data protector).
SiteMembershipProvider
SiteMembershipProvider is a legacy name — it used to be a membership provider but now only contains a single helper:
public static string ComputeSHA512(string s)
It computes the SHA512 hash of a string and returns it as base64 with padding stripped. It is used for hashing values that need a stable, non-reversible digest (e.g. comparing tokens or keys) without storing them in plain text.
Content Security Policy (CSP)
Serenity's CSP support lives in HtmlCspExtensions — the CspNonce(), AddCspDirective(), and GetCspDirective() helpers that generate per-request nonces and build the CSP header/meta tag. These are documented with the layout helpers in Script & CSS Bundling.
Account Rate Limiting
The account actions (login, forgot and reset password, sign up, elevate) are the ones an attacker can hammer, so the Serenity.Extensions package can limit them per client IP address and path with ASP.NET Core's rate limiting:
services.AddAccountRateLimiter(); // in ConfigureServices
// ...
app.UseRateLimiter(); // in the pipeline, after UseRouting
They are configured in the AccountRateLimit section (AccountRateLimitOptions):
{
"AccountRateLimit": {
"Enabled": true,
"PermitLimit": 20,
"WindowSeconds": 60,
"Paths": {
"/Account/Login": { "PermitLimit": 10 },
"/Account/SignUp": { "PermitLimit": 0 }
}
}
}
Pathslists the request paths (without the path base) that are limited for POST requests. Each path has its own limit, so failed logins do not use up the forgot password limit. Configuration is merged into the defaults (the five account paths above), so you can override or add one without repeating the others.PermitLimit/WindowSecondsare the defaults (20 requests per 60 seconds), overridable per path.PermitLimit: 0turns a path off, andEnabled: falseturns the limiter off altogether.- A rejected request gets a
429 Too Many Requestsresponse with aRetry-Afterheader and aServiceResponsewhose error has theTooManyRequestscode and the localizedValidation.TooManyRequestsmessage, so the page shows it like any other service error.
Users behind the same proxy or NAT share an IP address, so keep the limits loose enough for a shared office network. If the
application is behind a reverse proxy, configure forwarded headers (e.g. UseForwardedHeaders), otherwise every client shares
the proxy's address and one. This limiter complements the per-username Throttler of the password
validator; it stops the flood before any account logic runs.
ESM Access Control
The JavaScript modules under the esm folders of the application and of the feature packages are served by static file
middleware, so by default anyone can download every page module, and read the pages they cannot open from the code. The
ESM access control serves a file only to users who may load an entry point (e.g. a page) that reaches it, using the
build.esm-manifest that tsbuild writes next to the files. See
ESM Access Control for the settings and the manifest.
See Also
- Authentication & Authorization — permissions, users, and the security service abstractions
- Script & CSS Bundling — CSP helpers (
HtmlCspExtensions), nonces, and layout rendering - Static Assets — how the client files of packages are served, and the ESM access control
- Antivirus Scan — ClamAV upload scanning
- Feature Toggles — gating features behind toggles