---
url: /saas-starter/v0.10.0/guide/security.md
---
# Security

::: tip What this page covers
Every choice of `--Persistence`, `--Auth`, `--IncludeTests` and `--Aspire`: a label says
which options a part is for. The copy in your app's `docs/` folder has only the parts for yours.
`ApiHost` stands for your app's name.
:::

What the app does to protect its users and data, and what's left to you when you deploy it.
[OWASP ASVS level 2](./asvs.md) maps the same protections to the standard's requirements, one by
one.

## Built in

* **Browser security headers** on every response: a Content-Security-Policy that only allows
  scripts, styles and connections from the app's own origin, plus protections against MIME
  sniffing, framing (clickjacking) and leaking URLs in the Referer header
  (`src/ApiHost/Security/SecurityHeaders.cs`). API responses carry `Cache-Control: no-store`, so
  browsers and proxies don't keep people's data. The app's pages start with a few inline scripts
  that the build writes; the policy allows exactly those, by their hashes, and no others
  (`src/ApiHost/ClientApp/ClientAppHosting.cs`). If you add a third-party script, font or
  analytics service, add its origin to the policy.
* **Uploaded files can't run as the app.** Browsers upload and download through short-lived
  signed URLs whose key, operation and expiry can't be changed. Every download comes as an
  attachment, so an uploaded HTML page or SVG drawing is saved rather than opened as a page, on
  every provider. With local disk storage, where files come from the app's own address, each
  download is also sandboxed by its own Content-Security-Policy. Keys can't leave the storage
  folder. Todo attachments are checked after the upload too (size, count), and the browser
  can't change which file it finishes (an encrypted upload token). See
  [File storage](./file-storage.md).
* **HTTPS only in production:** requests are redirected to HTTPS and browsers are told to keep
  using it, for the app's host and its subdomains, for a year (HSTS). Serve every subdomain over
  HTTPS before going live.
* **Development-only tools stay out of production:** the OpenAPI document and the API reference
  page (`/scalar`) are only served in Development, and the React app's scripts are served from the
  app itself, not a CDN.
* **No runtime code compilation in production:** Wolverine's code is generated at publish time
  and the app fails at startup if any of it is missing.

::: info With accounts

## Accounts and sign-in

* **Passwords** are hashed by ASP.NET Core Identity (PBKDF2) and never logged or returned. New
  ones need 8 characters, of any kind, and mustn't be one of the 10,000 most common or made from
  the email or the app's name ([details](./accounts.md#passwords)).
* **Short-lived access tokens, rotating refresh tokens.** Access tokens (signed JWTs) expire after
  a few minutes. Refresh tokens are stored only as hashes, replaced on every use, and reusing an
  old one after a 30-second grace period (a sign it was stolen) signs the user out everywhere. A
  session ends after 14 days unused, and 30 days after signing in however much it's used
  (`Jwt:RefreshTokenLifetimeDays`, `Jwt:SessionLifetimeDays`).
* **No token where page scripts can read it.** The browser keeps the access token in memory and
  the refresh token in an HttpOnly, Secure, `SameSite=Strict` cookie, never in `localStorage` or
  `sessionStorage`, so an injected script can't steal a session to use elsewhere. The API only
  reads the cookie when the request also has the `X-Refresh-Token-Cookie` header, which another
  site can't add without a CORS preflight the API never allows: that stops cross-site requests
  (CSRF) from using it. Mobile and desktop apps get the refresh token in the response body instead,
  for the platform's secure storage ([details](./accounts.md#signing-in)).
* **The signing key is checked at startup:** outside Development the app refuses to start with a
  missing, too-short or development key.
* **Email ownership is verified.** New accounts must confirm their email before they can log in,
  and a changed email only takes effect once the new address is confirmed.
* **One-time, short-lived links.** Confirmation, password reset and invitation links carry tokens
  that expire, stop working once used, and are created only when the email is sent, so they're
  never stored in the database's message tables or written to logs. The links point at
  `App:ClientUrl`, never at the request's `Host` header, so a forged host can't redirect them
  (the app won't start without the setting outside Development).
* **No account enumeration where it matters:** "forgot password" and "resend confirmation" answer
  the same whether or not an account exists, and a login only says an email is unconfirmed to
  someone who knows the password.
* **Account lockout** (ASP.NET Core Identity's): repeated wrong passwords lock the account for a
  while, whichever addresses they come from. A locked account can't refresh its tokens. A password
  reset lifts a lockout from failed logins. Tune it in `src/ApiHost/Identity/IdentityJwtSetup.cs`.
* **Rate limiting:** endpoints that check passwords, send email or create accounts allow a small
  number of attempts per client address per minute (`src/ApiHost/Identity/AuthRateLimiting.cs`,
  and `Accounts:AuthAttemptsPerMinute`).
* **Sessions end when they should:** changing or resetting a password, deleting the account, and
  an admin lock all revoke the user's refresh tokens.
* &#x20;**Each organisation's data is kept apart** by multi-tenancy in the data layer, not by filters in each endpoint, so a forgotten filter can't leak another organisation's data; its records answer
  404\. A token is only accepted while its user is still a member of its organisation. Deleting an
  organisation deletes its data, including Todo event history; deleting an account deletes the
  organisations the user was alone in.
* &#x20;**Organisation roles** are checked on every change (only owners make owners or delete the organisation), and invitation links are single-use, expire after a week, and are stored only as a hash. Invitations are limited per user per hour and per organisation, so the app can't be used to send spam.
* &#x20;**API keys** are stored only as a hash, shown once, scoped (read or write), rate limited per key, and refused everywhere but the paths they're for (no account, organisation, billing or admin endpoints). They stop at once when revoked, when their creator leaves, or when the organisation is suspended ([integrations](./integrations.md#api-keys)).
* &#x20;**Webhooks can't reach your network:** in production the sender refuses localhost, private and link-local addresses (including cloud metadata services), checked after DNS, and never follows redirects. Deliveries are signed, so receivers can check them.
* &#x20;**Customers' secrets** (and webhook signing secrets) are encrypted with Data Protection and never sent back by the API. Back up the Data Protection keys with the database.
* &#x20;**Each user sees only their own data:** another user's records answer 404, so their existence isn't revealed. Deleting an account (which needs the password again) deletes the user's data too, including Todo event history.
* **Pictures are checked, not trusted.** An uploaded profile picture or logo must be a PNG, JPEG
  or WebP picture by its bytes (not its name or declared type), at most 512 KB and 1024 pixels a
  side; it's stored under a new random name and served sandboxed. Uploads are rate limited per
  user (`Pictures:UploadsPerMinute`), so nobody can fill storage by uploading in a loop. Gravatar
  is off unless you turn on `Pictures:Gravatar`, which shares a hash of the user's email and
  viewers' IP addresses with Gravatar ([details](./accounts.md#profile-pictures)).

## Roles and the admin page

* Roles are checked by the API on every admin request; hiding the admin page in the browser is
  only for convenience.
* Admins can't lock their own account or remove their own Admin role, so an admin always remains.
* `Accounts:AdminEmails` only grants Admin once that email has been confirmed, so nobody can claim
  it by registering the address first.
* Registration can be made invitation-only (`Accounts:AllowRegistration=false`).

## Google, GitHub and passkeys

* **External sign-in** only trusts email addresses the provider has verified. If someone had
  registered that email without confirming it, their password is removed before the account is
  linked, so they can't get in afterwards (account pre-hijacking). Linking a provider from Settings
  uses a short-lived encrypted ticket, and the tokens handed back to the browser are passed in the
  URL fragment (never sent to a server) and exchanged immediately.
* **Passkeys** use ASP.NET Core Identity's WebAuthn support, which checks the challenge, the site's
  origin, the signature and the passkey's counter. The ceremony state the browser holds is
  encrypted, expires after a few minutes, and is tied to the user when adding a passkey.
* **Two-factor authentication** (an authenticator app's codes, through Identity) asks for a code
  after the password or Google/GitHub. The step between is a ticket, encrypted, valid for five
  minutes and tied to the user's security stamp; wrong codes count towards the lockout. Turning it
  off needs a current code. `Accounts:RequireTwoFactorForAdmins` keeps the Admin role out of the
  tokens of admins without it.
* **Sessions** can be reviewed and signed out in Settings, one device at a time or all but the
  current one.
* &#x20;**Organisations can require two-factor authentication** of their members, checked on every request.
* **Security emails** tell people when their password, email, two-factor authentication,
  passkeys or linked Google/GitHub sign-ins change, a recovery code is used, the account is locked
  after wrong guesses, or someone signs in from a device the account hasn't used before, so a
  change they didn't make doesn't go unnoticed. A changed email is
  reported to the old address.
* **Changing the email or deleting the account asks again** for the password and, with
  two-factor on, a code, so a session left open or a stolen access token isn't enough to take the
  account over. Wrong answers count towards the lockout.
* **Breached passwords can be refused** (`Accounts:RejectBreachedPasswords`), checked with Have I
  Been Pwned without sending the password or its whole hash.
* Settings won't remove a user's last way to sign in.
  :::

## Cookies and consent

The app needs no cookie banner as it comes. Under the GDPR and the ePrivacy rules, consent is
needed for cookies and browser storage that aren't strictly necessary (analytics, advertising,
third-party embeds), and the app uses none.

::: info With accounts
What it keeps in the browser is strictly necessary, or remembers a choice the person made
themselves (the theme), which needs no consent either:

| What | Where | Why it needs no consent |
|---|---|---|
| `__Secure-refresh_token` | HttpOnly cookie, sent only to `/api` | Keeps the user signed in: it's the session |
| `__Secure-known_device` | HttpOnly cookie, sent only to `/api/auth`, encrypted | Recognises a device that signed in before, for the "new sign-in" email: a security measure |
| `auth.signedIn` | `localStorage`, `1` or absent | Saves a request on page loads when nobody is signed in |
| `theme` | `localStorage`, `light`, `dark` or absent | Remembers the theme the person picked in the footer |
| `.AspNetCore.Correlation.*` | Cookie, during Google or GitHub sign-in only | Protects that sign-in against forgery |

Nothing loads from another site (the fonts are served by the app), and Gravatar is off by
default. You still need a privacy policy saying what personal data you keep and why.
:::

::: info Without accounts
It sets no cookies and loads nothing from another site (the fonts are served by the app). It
keeps one thing in the browser: `theme` in `localStorage`, when someone picks a theme in the
footer.
:::

**Turning on analytics adds a banner.** Setting `Analytics:GoogleTagManagerId` makes the app ask
each visitor which optional cookies they accept, and load Tag Manager only once they've accepted
some. The choice is kept in a `cookie_consent` cookie, which is itself strictly necessary
([analytics and cookie consent](./analytics.md)). If you add a chat widget, ads or another tool
outside Tag Manager, check consent before loading it in the same way. Prefer analytics that need
no consent (counting page views on the server, or a cookieless tool such as Plausible) when they
do the job.

## When you deploy

* Keep secrets out of source control: use environment variables, `deploy/.env` (on the server
  only) or a secret store.
* Expose only the reverse proxy. In `deploy/docker-compose.yml` only Caddy is reachable; the app
  and database aren't.
* &#x20;Set `ASPNETCORE_FORWARDEDHEADERS_ENABLED=true` behind a reverse proxy (the production compose file does), so rate limits apply to each client's real address and HTTPS is detected.
* &#x20;Use a long random `Jwt:SigningKey`, set `App:ClientUrl` to the app's public address, configure SMTP before people register, and set `Accounts:AdminEmails`.
* &#x20;ASP.NET Core Data Protection keys (which protect the tokens in emails, link tickets and passkey state) are stored in PostgreSQL so they work across restarts and instances. Like the rest of your data they're unencrypted at rest: protect database access and backups.
* Keep dependencies current: `.github/dependabot.yml` opens weekly update pull requests. Check
  for known vulnerabilities in CI too: `dotnet list package --vulnerable --include-transitive`
  and `npm audit` (in `src/Client`).
* Send the logs somewhere other than the server ([observability](./observability.md)), so they
  survive if the server doesn't.
* Tell people how to report a vulnerability to you: a `SECURITY.md` in your repository, and a
  [`security.txt`](https://securitytxt.org/) at `/.well-known/security.txt` (add it to
  `src/Client/public/.well-known/`).

## Security events in the logs

`src/ApiHost/Security/SecurityEvents.cs` logs what you'd look for after an attack, with the
user and the client's address (each entry also has the time, and the request's trace ID and
path):

* &#x20;**Signed in** (Information, event 1001): the user, the new session, and the path that signed them in (password, two-factor, passkey, Google or GitHub, an invitation).
* &#x20;**A replaced refresh token was used again** (Warning, 1003): it may have been stolen, so all the user's sessions were ended.

::: info With accounts

* **Refused** (Warning, 1002): a failed sign-in or other refusal from `/api/auth` (401, 403), any
  request refused for lack of permission (403), and rate limits (429). A password sign-in that
  goes on to ask for a two-factor code answers 403 too, so it's logged here, followed by "Signed
  in" once the code is right.

ASP.NET Core Identity adds its own, such as lockouts. Passwords, tokens and codes are never
logged.
:::

::: info Without accounts

* **Refused** (Warning, 1002): any request refused for lack of permission (403), or by a rate
  limit you add (429).

Once you add sign-in, log its successes and failures here too.
:::
