Skip to content

C.A. Common Security Configuration

Jimmy Bourque edited this page Nov 30, 2026 · 1 revision

Français

API Security Configuration

This document explains the Security section of the JbtiEvolution.OraklLearn.API/appsettings.json and JbtiEvolution.OraklLearn.AdminAPI/appsettings.json files. It is intended for people who administer or deploy the applications without being security specialists.


Important notice: All configuration examples in this document are intended to run services in Visual Studio. For Docker deployments, refer to docker-compose.yml and the env and secret.env environment files generated by the OL CLI.

This document does not confirm or guarantee that any security setting is suitable for production. You are responsible for engaging qualified security specialists to validate your security settings, deployed workload, and any other configuration before using the system in production.


Security is divided into several complementary mechanisms:

  • retaining the keys that protect cookies and authentication tokens;
  • HTTP headers sent to browsers;
  • CORS policies that limit which sites may call the API from a browser;
  • the Entra ID application role required to access the application;
  • limiting the number of requests;
  • protecting remote image downloads.

Configuration and secrets

Sensitive values that must replace the examples below are stored separately:

  • appsettings.secrets.json files contain sensitive values used locally by each application;
  • the OL CLI artifacts directory, including .secrets.env, contains the secret files loaded by Docker Compose;
  • these files replace their corresponding generic values, including connection strings, Azure Storage keys, Entra ID secrets, Service Bus keys, and so on.

Secret files must never be added to a source-code repository, a publicly distributed archive, or a Docker image. They must remain in a protected location, with access limited to authorized personnel or deployment processes. Where possible, using a secrets vault (Azure Key Vault) is preferred.

The __override__value__ values in configuration files are placeholders indicating that a value must be provided in the secret file.

Overview

Subsection Main purpose Risk reduced
Security.
AuthenticationStorage
Keep cookie keys and the token cache Accidental sign-outs, inability to decrypt cookies, unnecessary token renewals
Security.Headers Add protections understood by browsers HTTP interception, clickjacking, URL leakage, loading of unplanned scripts
Security.Cors Allow only certain websites to call the API Reading responses from a malicious website
Security.Roles Require a role in the Entra ID token Access by an authenticated but unauthorized user
Security.ApiRateLimit Limit the request rate Abuse, overload and excessive resource consumption
Security.ImageDownloader Control images downloaded from the Internet SSRF, unlimited downloads and content disguised as an image

API and AdminAPI Differences (For Visual Studio projects)

The Security section is shared by both services, but some values must remain different because the API and AdminAPI are separate applications with different responsibilities.

Setting JbtiEvolution.OraklLearn.API JbtiEvolution.OraklLearn.AdminAPI
Authentication cookie directory data/portal/data-protection-keys data/admin/data-protection-keys
MSAL token cache directory data/portal/msal-token-cache data/admin/msal-token-cache
Authentication cookie name OraklLearn.API OraklLearn.Admin
Data Protection application name JbtiEvolution.OraklLearn.api JbtiEvolution.OraklLearn.adminapi
Required Entra ID role user.all admin.all
Default authorization policy Applies to endpoints using the default authorization policy Also applies as the fallback policy, so endpoints without an explicit authorization policy are protected by the required admin role
Local CORS origin https://localhost:44363 https://localhost:51314
CSP connect-src 'self' data: blob: plus configured server and Blob origins 'self' plus configured server and Blob origins

The remaining Headers settings, ApiRateLimit settings and ImageDownloader limit are currently the same in both appsettings.json files. Production values must still be supplied through the appropriate secret or deployment configuration for each service.

AuthenticationStorage

This subsection indicates where the API stores the data required for authentication after a restart. It also serves to share authentication information between multiple instances of the same web application, for example several replicas behind a load balancer. It does not store passwords.

All instances of the same application must therefore use the same persistent locations that are accessible for reading and writing. This allows one instance to create or protect a cookie and another instance to read and decrypt it afterward. Without this sharing, the user may be signed out every time a request is routed to a different instance.

Data protection keys are used in particular to encrypt and sign the API or AdminAPI session cookie. They therefore allow the application to recognize an existing session after each request and after a restart, provided that the same keys are accessible.

The MSAL cache contains the access tokens obtained by the API or AdminAPI to call protected downstream services, especially the Catalog service when it requires Entra ID authentication. The cache allows an access token that is still valid to be reused instead of requesting a new one for every call. This improves continuity for calls between services, reduces requests sent to Entra ID and allows different instances of the same application to share these tokens when they use shared storage.

Key Type Description
Security.AuthenticationStorage.
AuthenticationCookiesDirectory
string Directory containing the ASP.NET Core Data Protection keys used to encrypt and sign authentication cookies. If these keys are lost, users will have to sign in again.
Security.AuthenticationStorage.
MSALTokenCacheDirectory
string Directory containing the local cache of MSAL tokens used to call downstream APIs. Losing it requires new tokens to be obtained, but it does not replace the cookie keys.

Example for the API

"AuthenticationStorage": {
  "AuthenticationCookiesDirectory": "data/portal/data-protection-keys",
  "MSALTokenCacheDirectory": "data/portal/msal-token-cache"
}

Example for the AdminAPI

"AuthenticationStorage": {
  "AuthenticationCookiesDirectory": "data/admin/data-protection-keys",
  "MSALTokenCacheDirectory": "data/admin/msal-token-cache"
}

In production with multiple API instances, both directories must be persistent and accessible by all instances of the same application. A different Docker volume for each replica is not sufficient: one replica could create cookies that the others cannot decrypt. Shared storage ensures session continuity and also allows instances to reuse the same MSAL token cache.

The API and AdminAPI intentionally use different Data Protection application names. They therefore do not share their cookies, even if they use the same Entra ID provider.

HTTP Headers

This subsection configures the response headers intended for browsers. It is applied to the API, static files and fallback pages.

Key Type Description
Security.Headers.Enabled bool Enables the middleware that adds security headers to HTTP responses. If the value is false, the protections in this subsection are no longer added.
Security.Headers.EnforceHttps bool Prevents normal HTTP operation by redirecting every non-HTTPS request to its HTTPS equivalent. This protects cookies and data in transit. Use true when the application itself terminates TLS or when the reverse proxy headers are correctly processed.
Security.Headers.EnableHsts bool Adds Strict-Transport-Security to HTTPS responses. The browser then remembers that it must use HTTPS for future visits, reducing downgrade attacks to HTTP. HSTS is added only when the request is considered HTTPS.
Security.Headers.
HstsMaxAgeSeconds
int Indicates for how many seconds the browser must apply HSTS. With 31536000, an HTTPS visit forces subsequent visits to use HTTPS for one year. A long duration makes a configuration error more difficult to correct quickly.
Security.Headers.
HstsIncludeSubDomains
bool Adds includeSubDomains to HSTS. All subdomains will then automatically be required to use HTTPS. Do not enable it if a legitimate subdomain still works only over HTTP.
Security.Headers.HstsPreload` bool Adds preload to the HSTS header. This directive indicates that the domain may be eligible for the browser preload list, but it does not add it automatically. Enable it only when the domain and all its subdomains are permanently available over HTTPS.
Security.Headers.
ContentSecurityPolicy`
string Defines the sources allowed for scripts, styles, images, fonts, media, connections and frames. The browser blocks resources that do not match this policy, which notably limits the execution of injected scripts. The value must be tested with the web interface because a missing source may prevent a feature from working.
Security.Headers.
AllowedServerOrigins
string[] List of additional servers to which the application JavaScript can connect through fetch or XMLHttpRequest. These values are added to connect-src. Each origin must correspond to a server that is actually used; an origin that is too broad would allow connections to unplanned services.
Security.Headers.
AllowedBlobOrigins
string[] List of Azure Blob domains allowed for connections and for loading images or media. The code adds these values to connect-src, img-src and media-src, so that files stored in Blob Storage can be displayed or played by the interface.
Security.Headers.
ReferrerPolicy
string Controls the information about the current page that the browser may transmit when it opens another page or loads a resource. With no-referrer, no page address is transmitted, protecting potentially sensitive paths and parameters.
Security.Headers.
PermissionsPolicy
string Limits the sensitive features that pages and embedded frames can use. For example, camera=() blocks the camera, microphone=() blocks the microphone and geolocation=() blocks geolocation. This rule does not replace HTTPS or the browser’s permission request.

Example for the API

"Headers": {
  "Enabled": true,
  "EnforceHttps": true,
  "EnableHsts": true,
  "HstsMaxAgeSeconds": 31536000,
  "HstsIncludeSubDomains": true,
  "HstsPreload": true,
  "ContentSecurityPolicy": "connect-src 'self' data: blob:; default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com/ajax/libs/font-awesome/ https://maxcdn.bootstrapcdn.com/font-awesome/; img-src 'self' data: blob:; media-src 'self' data: blob:; font-src 'self' https://cdnjs.cloudflare.com/ajax/libs/font-awesome/ https://maxcdn.bootstrapcdn.com/font-awesome/; frame-ancestors 'none';",
  "AllowedServerOrigins": [
    "http://localhost:*",
    "https://localhost:*"
  ],
  "AllowedBlobOrigins": [
    "https://orakllearn.blob.core.windows.net"
  ],
  "ReferrerPolicy": "no-referrer",
  "PermissionsPolicy": "camera=(), microphone=(), geolocation=()"
}

The AdminAPI uses the same header settings except that its configured CSP starts with connect-src 'self'; instead of connect-src 'self' data: blob:;. Its local CORS origin is also different: https://localhost:51314 instead of https://localhost:44363.

Example for the AdminAPI

"Headers": {
  "Enabled": true,
  "EnforceHttps": true,
  "EnableHsts": true,
  "HstsMaxAgeSeconds": 31536000,
  "HstsIncludeSubDomains": true,
  "HstsPreload": true,
  "ContentSecurityPolicy": "connect-src 'self'; default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com/ajax/libs/font-awesome/ https://maxcdn.bootstrapcdn.com/font-awesome/; img-src 'self' data: blob:; media-src 'self' data: blob:; font-src 'self' https://cdnjs.cloudflare.com/ajax/libs/font-awesome/ https://maxcdn.bootstrapcdn.com/font-awesome/; frame-ancestors 'none';",
  "AllowedServerOrigins": [
    "http://localhost:*",
    "https://localhost:*"
  ],
  "AllowedBlobOrigins": [
    "https://orakllearn.blob.core.windows.net"
  ],
  "ReferrerPolicy": "no-referrer",
  "PermissionsPolicy": "camera=(), microphone=(), geolocation=()"
}

Simplified explanation of the current CSP:

  • default-src 'self' allows by default only the application’s own domain;
  • script-src 'self' blocks JavaScript from other domains;
  • style-src ... 'unsafe-inline' allows local styles, existing inline styles and Font Awesome;
  • img-src 'self' data: blob: allows local images and previews generated by the application;
  • frame-ancestors 'none' prevents another site from displaying the application in an iframe;
  • the origins configured in AllowedBlobOrigins are automatically added to the image and media rules.

EnforceHttps means: “if someone arrives over HTTP, redirect them to HTTPS.” It should normally remain true to protect exchanges between the browser and the application.

There are, however, two common ways to install the application:

  • Without a reverse proxy, the API receives the HTTPS connection directly. It can therefore check itself that the request is secure.
  • With a reverse proxy, such as Azure Application Gateway, Nginx or a Kubernetes ingress, the reverse proxy receives the HTTPS connection and sometimes forwards it to the API over HTTP on the internal network. For the API, the internal connection then appears to be HTTP, even though the browser is correctly using HTTPS.

In the second case, the reverse proxy must forward the original protocol information with the X-Forwarded-Proto: https header, and the API must trust this header before running this middleware. The project processes forwarded headers before the security headers. If this configuration is missing or incorrect, the API may believe that all requests are HTTP and continuously redirect them to the same HTTPS URL. This creates a redirect loop and makes the site inaccessible.

HSTS headers are sent only in HTTPS responses; they are not included in HTTP responses. Setting HstsPreload=true does not automatically add the domain to a browser’s HSTS preload list. Before submitting a domain for inclusion, verify that the domain and all of its subdomains are ready to use HTTPS.

Cors

CORS is a rule applied by browsers. It determines which websites can call the API from JavaScript and read the response.

CORS does not replace authentication. It mainly prevents an unauthorized website from reading responses in the browser.

CSRF definition

CSRF means “Cross-Site Request Forgery.” It is an attack in which a malicious website tries to make a request to the application on behalf of a user who is already signed in. For example, a malicious page could try to modify a profile or delete data by automatically using the browser’s session cookie.

CORS and CSRF are two different protections: CORS controls which sites can read API responses, while CSRF protection verifies that a request which modifies data was actually initiated by the expected application. If authentication uses cookies and cross-origin requests are allowed, a specific CSRF protection must be provided in addition to AllowCredentials.

Key Type Description
Security.Cors.
AllowedOrigins
string[] Exact list of allowed origins. An origin contains the protocol, domain and possibly the port, but never a path, query string or trailing /.
Security.Cors.
AllowedMethods
string[] HTTP methods allowed for these origins. OPTIONS is required for CORS preflight requests.
Security.Cors.
AllowedHeaders
string[] Headers that the browser is allowed to send, especially during a preflight request.
Security.Cors.
AllowCredentials
bool Indicates whether the browser may send cookies, certificates or other credentials during a call between two different domains. When this value is true, the API can recognize the session cookie sent by the client application. It should remain false if the API uses only Bearer tokens in the Authorization header, because cross-origin cookies are then unnecessary.

Example for the API

"Cors": {
  "AllowedOrigins": [
    "https://localhost:44363"
  ],
  "AllowedMethods": [ "GET", "POST", "PUT", "DELETE", "OPTIONS" ],
  "AllowedHeaders": [ "Authorization", "Content-Type", "If-Match", "Language" ],
  "AllowCredentials": false
}

Example for the AdminAPI

"Cors": {
  "AllowedOrigins": [
    "https://localhost:51314"
  ],
  "AllowedMethods": [ "GET", "POST", "PUT", "DELETE", "OPTIONS" ],
  "AllowedHeaders": [ "Authorization", "Content-Type", "If-Match", "Language" ],
  "AllowCredentials": false
}

Correct value: https://portal.example.com.

Incorrect values: https://portal.example.com/, https://portal.example.com/app, * or a URL containing credentials.

AllowCredentials should remain false when clients use the Authorization: Bearer ... header. Enable it only if cross-origin cookies are truly required and CSRF protection is provided. OrakLearn does not require it to be enabled.

Roles

This subsection indicates the Entra ID application role required by the default authorization policy. A user may be correctly authenticated and still be denied if they do not have this role in the roles claim of their token.

Key Type Description
Security.<br>Roles.<br>DefaultRole string Name of the Entra ID role required for endpoints protected by the default policy. For the API, the expected value is generally user.all; for the AdminAPI, admin.all.

Example for the API

"Roles": {
  "DefaultRole": "user.all"
}

Example for the AdminAPI

"Roles": {
  "DefaultRole": "admin.all"
}

The role must exist in the Entra ID application registration and be assigned to the relevant users or groups. Simply signing in with Entra ID is not enough if the required role is missing.

To create an application role in Microsoft Entra ID, open Entra ID > App registrations, select the application that represents the API, then go to Manage > App roles > Create app role. Define a display name, a stable technical value such as user.all or admin.all, then assign the role to the authorized users or groups in the enterprise application. The technical value created in Entra ID must be identical to Security:Roles:DefaultRole.

See the official Microsoft documentation for adding application roles and getting them from a token for detailed steps and Azure portal examples. Additionally, the OL CLI automatically performs these configuration tasks.

The code accepts both claim names used by token handlers: roles and http://schemas.microsoft.com/ws/2008/06/identity/claims/role.

ApiRateLimit

Rate limiting protects the API against too many calls made close together. Each user or tenant has a separate budget for reads and mutations.

GET requests are considered reads. POST, PUT, PATCH and DELETE requests are considered mutations.

Key Type Description
Security.ApiRateLimit.
ReadRequestsPerMinute
int Maximum number of read tokens available during a period. Validation allows values from 1 to 5120.
Security.ApiRateLimit.
MutationRequestsPerMinute
int Maximum number of mutation requests during a period. Validation allows values from 1 to 1024.
Security.ApiRateLimit.
QueueLimit
int Maximum number of requests that may wait for a token when the budget is exhausted. 0 means immediate rejection. Validation allows values from 0 to 32.
Security.ApiRateLimit.
ReplenishmentPeriodSeconds
int Duration, in seconds, before the budget is replenished.
Security.ApiRateLimit.
RetryAfterSeconds
int Value sent in the Retry-After header with the HTTP 429 Too Many Requests response.
Security.ApiRateLimit.
SharedStorageDirectory
string When running in containers, use a shared mount so user rate‑limit calculation data is accessible to every instance.

Example for the API

"ApiRateLimit": {
  "ReadRequestsPerMinute": 120,
  "MutationRequestsPerMinute": 20,
  "QueueLimit": 0,
  "ReplenishmentPeriodSeconds": 60,
  "RetryAfterSeconds": 60,
  "SharedStorageDirectory": "C:\\app\\data\\portal\\rate-limit"
}

Example for the AdminAPI

"ApiRateLimit": {
  "ReadRequestsPerMinute": 120,
  "MutationRequestsPerMinute": 20,
  "QueueLimit": 0,
  "ReplenishmentPeriodSeconds": 60,
  "RetryAfterSeconds": 60,
  "SharedStorageDirectory": "C:\\app\\data\\admin\\rate-limit"
}

With this example, a user can make up to 120 reads and 20 mutations per 60-second period. An additional request is rejected with HTTP 429 and advice to retry after 60 seconds.

The key used for the budget normally combines the Entra ID tenant and the user identity. For an anonymous request or one without a usable claim, the code uses the identity name, IP address or unknown as a fallback.

ImageDownloader

This subsection limits raster images downloaded from remote URLs. It is important because a URL provided by a user could be used to try to reach an internal service or to send a very large file.

A raster format is an image made of colored points called pixels. PNG, JPEG, GIF, BMP and WebP are examples of raster formats. In contrast, SVG is a vector format: it describes the image with code and shapes. The module accepts raster formats recognized by their binary signature and rejects content that does not match a supported image.

ImageDownloader is used to download and validate remote raster images, especially during book generation or preparation. It is also used when the generator must reread a cached image from its URL. The module does not download audio files: it accepts only resources that pass the image-format checks.

Key Type Description
Security.<br>ImageDownloader.<br>MaxImageBytes long Maximum accepted size for a downloaded image, in bytes. Validation allows a value from 1 to 1073741824 bytes.

Example for the API

"ImageDownloader": {
  "MaxImageBytes": 10485760
}

Example for the AdminAPI

"ImageDownloader": {
  "MaxImageBytes": 10485760
}

10485760 bytes correspond to approximately 10 MiB.

The code performs more checks than size alone:

  • only absolute HTTPS URLs on port 443 are accepted;
  • private, local, loopback, link-local, multicast and reserved addresses are rejected;
  • DNS resolution is checked before the connection and again when the socket is opened to reduce DNS rebinding risk;
  • if provided, Content-Type must start with image/;
  • size is checked using Content-Length when it exists and while reading the stream when it does not exist or is not reliable;
  • the binary signature must correspond to a PNG, JPEG, GIF, BMP or WebP raster image;
  • SVG, HTML, XML or other arbitrary content is not accepted as a raster image.

Deployment Recommendations

  • Keep Security.Headers.Enabled, EnableHsts and EnforceHttps enabled in production when the HTTPS architecture is correctly configured.
  • Replace all __override__value__ values before starting the API.
  • Never publish AccountKey, ClientSecret, connection strings or other secrets in a Git repository or in this documentation.
  • Set AllowedOrigins to an explicit list of known domains. Do not use a generic origin or a wildcard.
  • Verify that AllowedBlobOrigins exactly matches the domains actually used by Blob Storage.
  • Share authentication directories between replicas of the same API, or use suitable distributed storage.
  • Test CSP changes in a staging environment: a policy that is too strict may prevent the interface from loading its scripts, styles, images or media.
  • Adjust rate limits according to actual load and monitor HTTP 429 responses.
  • Keep a reasonable image limit: increasing it also increases the memory that downloads and image decoders may consume.

Reference Files

  • Configuration registration: JbtiEvolution.OraklLearn.Security/Configuration/SecuritySettingsExtensions.cs
  • Header options: JbtiEvolution.OraklLearn.Security/Configuration/SecurityHeadersSettings.cs
  • CORS options: JbtiEvolution.OraklLearn.Security/Configuration/CorsSettings.cs
  • Rate-limit options: JbtiEvolution.OraklLearn.Security/Configuration/ApiRateLimitSettings.cs
  • Image-download options: JbtiEvolution.OraklLearn.Security/Configuration/ImageDownloaderSettings.cs
  • Authentication-storage options: JbtiEvolution.OraklLearn.Security/Configuration/AuthenticationStorageOptions.cs

Clone this wiki locally