Skip to main content
Version: 2.0

Security Guide

This guide covers security best practices for deploying and operating Milvaion in production environments. All security configurations are managed through appsettings.json, environment variables, and infrastructure settings.


Authentication Configuration​

JWT Token Settings​

Configure token security in appsettings.json:

{
"Milvasoft": {
"Identity": {
"Token": {
"UseUtcForDateTimes": true,
"ExpirationMinute": 90,
"TokenValidationParameters": {
"ValidateIssuer": true,
"ValidateAudience": true,
"ValidIssuer": "https://your-domain.com",
"ValidAudience": "milvaion-clients"
},
"SecurityKeyType": 0,
"SymmetricPublicKey": "your-256-bit-secret-key-here"
}
}
}
}
SettingDevelopmentProduction
ExpirationMinute9015-30
ValidateIssuerfalsetrue
ValidateAudiencefalsetrue
SymmetricPublicKeyAnyRandom 256-bit key

Generate a Secure Key​

# PowerShell
[Convert]::ToBase64String((1..32 | ForEach-Object { Get-Random -Maximum 256 }))

# Linux/macOS
openssl rand -hex 32

⚠️ Important: Never commit your production JWT key to version control. Use environment variables instead.

Token Expiration Behavior​

Milvaion handles token states with specific HTTP status codes:

Status CodeMeaningClient Action
401Invalid or missing tokenRedirect to login
419Token expiredRefresh token or re-login
403Insufficient permissionsShow access denied

Required Configuration​

No secret is shipped in appsettings.json. Set these through the environment (or a secret store) on every deployment:

VariablePurpose
ConnectionStrings__DefaultConnectionStringDatabase connection, including its password.
Milvasoft__Identity__Token__SymmetricPublicKeySigning key for login tokens.
MilvaionConfig__ApiKey__SecretSigning secret for api keys.
MilvaionConfig__RabbitMQ__Username / MilvaionConfig__RabbitMQ__PasswordBroker credentials (default guest).

If a signing key is not set the API still starts, but generates a random one for that process and logs a warning: sessions and api keys stop working at every restart, and replicas reject each other's tokens.

For the local docker-compose stack, copy .env.example to .env.

These are off unless you turn them on:

VariableEffect
MilvaionConfig__Developer__EndpointsEnabledRegisters the developer endpoints (database reset, seed, export). Everything but database/init requires super admin.
MilvaionConfig__Developer__ApiDocsEnabledServes the OpenAPI document and Scalar reference.

Client addresses are only taken from X-Forwarded-For when the sending proxy is listed under MilvaionConfig__ForwardedHeaders__KnownProxies__0 or MilvaionConfig__ForwardedHeaders__KnownNetworks__0. Login and token refresh are limited per client address by MilvaionConfig__RateLimiting__LoginPermitPerMinute (default 60, 0 disables); behind a proxy that is not listed, every client shares one limit. The first-run setup has its own limit, MilvaionConfig__RateLimiting__SetupPermitPerMinute (default 10).


External Identity Providers (SSO)​

In addition to local username/password login, Milvaion can federate authentication to external identity providers. Two types are supported and both are off by default, so the application keeps its local login behavior until one is enabled:

  • OIDC (OpenID Connect) — browser redirect single sign-on (for example Keycloak, Entra ID, Auth0).
  • LDAP / Active Directory — the normal username/password form, with the password verified by a directory bind instead of the local hash.

Regardless of the provider, identity is owned by the provider while permissions stay owned by Milvaion. On each sign-in Milvaion keeps a shadow user record and mirrors the provider's groups as roles; an administrator then assigns the permission set of those roles inside Milvaion. A group can only map to a role that provider owns: a group named after a local role, such as SuperAdmin, is ignored. Local roles are granted only through explicit role mappings.

There are two ways to configure providers:

In the panelIn configuration files
WhereSettings → Single sign-onMilvaionConfig:Authentication
Takes effectImmediately, on every instanceAfter a restart
How manyAny number of OIDC providers, one enabled LDAP directoryOne OIDC provider and one LDAP directory
SecretsEncrypted in the database, never shown againIn the configuration

Both can be used together. A configured provider is listed in the panel as read-only under the name Oidc or Ldap. A panel provider with the same name replaces it, even while the panel provider is disabled.

Password login for local users, including the root user, always works, whatever state the providers are in.

Managing Providers in the Panel​

  • The server needs the same encryption key as database secrets: MilvaionConfig__Secrets__Database__EncryptionKey. If a key is removed, providers encrypted with it show as unreadable and cannot be used until they are saved again.
  • Only a super admin (App.SuperAdmin) can add, change or delete a provider, because a provider decides who can sign in and with which roles. The IdentityProviderManagement.List permission allows viewing them. Api keys are refused.
  • Client secrets and bind passwords are write-only. Leave the field empty to keep the stored value. The bind password has to be entered again when the LDAP host, port or SSL setting changes.
  • Tokens are routed to a provider by their issuer, so an issuer can belong to one enabled provider only, and not to Milvaion's own tokens.
  • Test checks a saved provider before you enable it: for OIDC the discovery document, the issuer and the signing keys; for LDAP the connection, the service account and the search base. Only a super admin can run it. It times out after 10 seconds, does not follow redirects and reports a fixed outcome, never what the other side answered.
  • Register <dashboard address>/auth/callback as the redirect URI and <dashboard address>/login as the post-logout redirect URI at the OIDC provider.
  • Signing out of Milvaion also ends the session at the provider, which then returns to the login page. Turn off Sign out at the provider too (EndProviderSession: false in the configuration) to keep users signed in there.
  • The audience is required, so tokens the provider issued to other applications are refused. It stays optional for a provider in the configuration files; the panel shows a warning when it is empty there.
  • Disabling or deleting an OIDC provider rejects its tokens at once. Users of an LDAP directory keep their current access token until it expires (Milvasoft:Identity:Token:ExpirationMinute, 90 minutes by default), but cannot renew it. Shorten that lifetime if disabling a directory has to take effect sooner. Open dashboard connections of the provider's users are closed within seconds. Instances that miss the change notification catch up within 30 seconds.
  • A role mirrored from a group belongs to the provider it came from. A group of the same name at another provider does not get its permissions.
  • The name a request runs under is the name of the Milvaion account, never the one claimed in the token.
  • Role mappings name existing local roles. A mapping to SuperAdmin makes every holder of that provider role a super admin.
  • Directory users are tied to the LDAP host name they signed in through. Changing the host stops existing directory users from signing in until it is changed back.

OIDC Configuration​

{
"MilvaionConfig": {
"Authentication": {
"Oidc": {
"Enabled": true,
"Authority": "https://keycloak.example.com/realms/milvaion",
"MetadataAddress": "",
"ValidIssuers": "",
"Audience": "milvaion-spa",
"ClientId": "milvaion-spa",
"ClientSecret": "",
"RequireHttpsMetadata": true,
"NameClaim": "preferred_username",
"SubjectClaim": "sub",
"RolesClaim": "roles",
"RolePrefix": ""
}
}
}
}
SettingDescription
EnabledTurns OIDC on. When true the login page shows a sign-in button for it.
AuthorityRealm/issuer URL as the browser addresses it. Handed to the SPA and, unless MetadataAddress overrides it, used by the API for discovery.
MetadataAddressOptional discovery document URL for when the API reaches the provider on a different host than the browser (e.g. a containerized API using host.docker.internal).
ValidIssuersOptional comma-separated list of issuer values to accept when browser and API reach the provider on different hosts.
AudienceExpected token audience (usually the client id). Required in the panel. Empty in the configuration disables audience validation, so tokens issued to other applications are accepted.
ClientIdPublic client id the SPA uses for the redirect (PKCE) flow.
ClientSecretOptional secret for a confidential client. Not required to validate tokens.
RequireHttpsMetadataRejects non-HTTPS metadata/authority. Keep true outside local development.
NameClaim / SubjectClaim / RolesClaimClaims used for the display name, the stable per-user identifier, and the user's roles/groups.
RolePrefixOptional prefix filter: only roles starting with this value are provisioned. Empty takes them all.
RoleMappingsExplicit grants from a provider role to existing local roles, comma-separated, for example RoleMappings__owner=SuperAdmin. Only listed roles reach local roles. Unlisted provider roles are mirrored with an empty permission set.

The SPA requests the openid profile email offline_access scopes and renews expired access tokens with the refresh token, so the client must be allowed offline_access. Milvaion reads the user's identity from the access token, so it must carry the NameClaim, SubjectClaim, RolesClaim and email claims.

⚠️ Important: Never commit ClientSecret to version control. Use environment variables or a secret store.

LDAP / Active Directory Configuration​

{
"MilvaionConfig": {
"Authentication": {
"Ldap": {
"Enabled": true,
"Host": "ldap.example.com",
"Port": 636,
"UseSsl": true,
"BaseDn": "dc=corp,dc=example,dc=com",
"BindDn": "[email protected]",
"BindPassword": "",
"UserDnFormat": "{0}@corp.example.com",
"UserSearchFilter": "(sAMAccountName={0})",
"GroupMemberAttribute": "memberOf",
"RolePrefix": "milvaion"
}
}
}
}
SettingDescription
EnabledTurns directory login on. LDAP users sign in through the normal username/password form.
Host / PortDirectory server address.
UseSslUse LDAPS (typically port 636). Credentials must never cross an unencrypted connection in production.
BaseDnSearch base for user and group lookups.
BindDn / BindPasswordOptional service account used to look up the user entry and groups. Leave empty to bind directly as the user.
UserDnFormatTemplate forming the bind DN from the username, e.g. {0}@corp.example.com. {0} is the submitted username.
UserSearchFilterFilter to locate the user entry for group resolution.
GroupMemberAttributeAttribute listing group memberships.
RolePrefixOptional prefix filter for groups mapped into Milvaion roles.
RoleMappingsExplicit grants from a directory group to existing local roles, as for OIDC.

⚠️ Important: Always enable UseSsl in production so credentials are never sent over an unencrypted connection. Store BindPassword in an environment variable, never in source control.

Inactive External User Cleanup​

Externally provisioned users who have not signed in for InactiveUserRetentionDays (default 90) are pruned automatically; local users are never touched. Set the value to 0 to disable pruning.

{
"MilvaionConfig": {
"Authentication": {
"InactiveUserRetentionDays": 90
}
}
}

Managing External Users and Roles​

Because identity is owned by the provider, some fields are read-only in Milvaion for external records:

  • External users — name, email, username, password and role membership are owned by the provider. Only Milvaion-owned fields (notification preferences and the lock) are editable; changes to the provider-owned fields are ignored.
  • External roles — the name mirrors the provider group and cannot be renamed here, but the permission set is assigned in Milvaion.
  • Change password is rejected for external users: their password lives with the identity provider.

Deleting an external user does not block them. The provider still vouches for them, so the next sign-in creates the account again, also when the deleted account was locked. To keep somebody out, disable them at the provider, or lock the user in Milvaion (User Management, edit the user; lockout in the API):

  • The lock of an external user lasts until it is removed. (For local users, lockout is temporary, see the lockout settings below.)
  • An OIDC user's requests are refused within about 10 seconds.
  • An LDAP user cannot sign in or renew the session. Their current access token works until it expires, as when the directory is disabled.
  • Their open dashboard connections are closed within seconds.
  • The removal of inactive users (InactiveUserRetentionDays) skips locked users.

The stored roles of external users are updated when they sign in, so leaving a group takes its permissions away at the next sign-in.

Changing what a role grants (its permission set) or deleting a role takes effect for external users immediately, without waiting for their session to expire.


Approval messages can carry links that open an approval.

  • Answering needs a sign-in. A link only opens the approval. The user has to sign in and hold one of the approval's approver roles, for the whole installation or in the project of the approval. Super admins are no exception, and with no approver roles nobody can answer through a link. Approving and rejecting follow the same rule, and the answer is recorded with the user. Before the sign-in the page shows nothing about the approval.
  • An approval can opt in to answers without a sign-in. It is off by default. Then whoever holds a link can answer, so send links only to channels whose members may do so. The answer is recorded as link, with the channel and the address the message was sent to, and not with a person.
  • The client address is recorded in both cases.
  • A link is signed, works once, and expires with the approval. Only an answer uses it up: opening it, signing in, or a user without the role does not.
  • Nothing is answered until Approve or Reject is pressed, so link previews and mail scanners that fetch the address change nothing.
  • An approval that needs a form is approved in Milvaion. It can be rejected through a link.
  • Links are signed with a key derived from MilvaionConfig__ApiKey__Secret. Changing that secret invalidates links that were already sent.
  • MilvaionConfig__Alerting__MilvaionAppUrl must be set, otherwise no links are created.
  • The confirmation page shares the rate limit of the login page.

Password Security​

Password Policy Configuration​

Configure password requirements in appsettings.json:

{
"Milvasoft": {
"Identity": {
"Password": {
"RequiredLength": 8,
"RequiredUniqueChars": 2,
"RequireNonAlphanumeric": true,
"RequireLowercase": true,
"RequireUppercase": true,
"RequireDigit": true
}
}
}
}
SettingMinimumHigh Security
RequiredLength812+
RequiredUniqueChars24

Passwords are hashed with PBKDF2-SHA512 and 210,000 iterations (the Milvasoft library default). Leave Hasher:IterationCount unset so this default applies; hashes created with older, weaker settings still verify and are upgraded on the user's next successful login.

Account Lockout Protection​

Protect against brute-force attacks:

{
"Milvasoft": {
"Identity": {
"Lockout": {
"AllowedForNewUsers": true,
"MaxFailedAccessAttempts": 5,
"DefaultLockoutTimeSpan": 15
}
}
}
}

Behavior:

  • After 5 failed attempts → Account locked for 15 minutes
  • Lockout duration shown to user
  • Successful login resets the counter

Infrastructure Security​

PostgreSQL​

Secure Connection String​

{
"ConnectionStrings": {
"DefaultConnectionString": "Host=postgres;Port=5432;Database=MilvaionDb;Username=milvaion_app;Password=SECURE_PASSWORD;SSL Mode=Require;Trust Server Certificate=false;Pooling=true;Maximum Pool Size=100"
}
}

Best Practices​

PracticeImplementation
Dedicated userCreate milvaion_app with minimum required permissions
SSL/TLSEnable SSL Mode=Require
Network isolationUse private network, no public IP
Connection limitsSet Maximum Pool Size appropriately

Database User Permissions​

-- Create application user with minimal permissions
CREATE USER milvaion_app WITH PASSWORD 'secure_password';

-- Grant only necessary permissions
GRANT CONNECT ON DATABASE MilvaionDb TO milvaion_app;
GRANT USAGE ON SCHEMA public TO milvaion_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO milvaion_app;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO milvaion_app;

-- For migrations (use a separate admin user)
CREATE USER milvaion_admin WITH PASSWORD 'admin_password';
GRANT CREATE ON SCHEMA public TO milvaion_admin;

Redis​

API Configuration​

{
"MilvaionConfig": {
"Redis": {
"ConnectionString": "redis:6379,ssl=true",
"Password": "STRONG_REDIS_PASSWORD",
"Database": 0,
"ConnectTimeout": 5000,
"SyncTimeout": 5000
}
}
}

Worker Configuration​

{
"Worker": {
"Redis": {
"ConnectionString": "redis:6379",
"Password": "SAME_REDIS_PASSWORD",
"Database": 0,
"CancellationChannel": "Milvaion:JobScheduler:cancellation_channel"
}
}
}

A Separate Redis User for Workers​

Workers use Redis for one thing: they subscribe to the cancellation channel. They never read or write keys. The API's password, on the other hand, can read everything under the key prefix, including the job schedule and the api key cache. Do not give workers that password. Give them their own Redis user (Redis 6 or later) that can only ping and subscribe:

# redis.conf, or ACL SETUSER at runtime
user milvaion-api on >API_PASSWORD ~Milvaion:JobScheduler:* &Milvaion:JobScheduler:* +@all
user milvaion-worker on >WORKER_PASSWORD resetkeys resetchannels &Milvaion:JobScheduler:*cancellation_channel -@all +ping +subscribe +psubscribe +unsubscribe +punsubscribe +hello +auth +client|setname +client|setinfo

Replace Milvaion:JobScheduler: with your KeyPrefix, and point the workers at the new user, for example "ConnectionString": "redis:6379,user=milvaion-worker,password=WORKER_PASSWORD".

A worker that holds only this user cannot read schedules or api keys, even if the worker host is compromised. This does not need any change in Milvaion or in the worker SDKs.

Redis Server Hardening​

# redis.conf
requirepass YOUR_STRONG_PASSWORD
bind 127.0.0.1 # Or private network IP only
protected-mode yes
rename-command FLUSHALL ""
rename-command FLUSHDB ""
rename-command DEBUG ""

RabbitMQ​

API Configuration​

{
"MilvaionConfig": {
"RabbitMQ": {
"Host": "rabbitmq",
"Port": 5672,
"Username": "milvaion_producer",
"Password": "SECURE_RABBITMQ_PASSWORD",
"VirtualHost": "/milvaion"
}
}
}

Worker Configuration​

{
"Worker": {
"RabbitMQ": {
"Host": "rabbitmq",
"Port": 5672,
"Username": "milvaion_consumer",
"Password": "SECURE_RABBITMQ_PASSWORD",
"VirtualHost": "/milvaion"
}
}
}

Virtual Host Isolation​

Create a dedicated virtual host for Milvaion:

# Create virtual host
rabbitmqctl add_vhost /milvaion

# Create users with specific permissions
rabbitmqctl add_user milvaion_producer SECURE_PASSWORD
rabbitmqctl set_permissions -p /milvaion milvaion_producer ".*" ".*" ".*"

rabbitmqctl add_user milvaion_consumer SECURE_PASSWORD
rabbitmqctl set_permissions -p /milvaion milvaion_consumer ".*" ".*" ".*"

# Remove default guest user
rabbitmqctl delete_user guest

Disable Management UI in Production​

# Disable management plugin entirely
rabbitmq-plugins disable rabbitmq_management

# Or restrict via environment variable
RABBITMQ_MANAGEMENT_LISTENER_IP=127.0.0.1

Secrets Management​

This section covers Milvaion's own settings. For credentials that jobs need (SMTP passwords, API tokens), do not write them into job data: use secret references such as {{secret:smtp-password}}, which are resolved from environment variables, configuration, HashiCorp Vault or Azure Key Vault only when the job is sent to a worker.

Environment Variables​

Override sensitive configuration with environment variables:

# docker-compose.yml
services:
milvaion-api:
environment:
- ConnectionStrings__DefaultConnectionString=Host=postgres;...;Password=${DB_PASSWORD}
- Milvasoft__Identity__Token__SymmetricPublicKey=${JWT_SECRET}
- MilvaionConfig__Redis__Password=${REDIS_PASSWORD}
- MilvaionConfig__RabbitMQ__Password=${RABBITMQ_PASSWORD}
- MILVAION_ROOT_PASSWORD=${ROOT_PASSWORD}

worker:
environment:
- Worker__Redis__Password=${REDIS_PASSWORD}
- Worker__RabbitMQ__Password=${RABBITMQ_PASSWORD}

Docker Secrets​

For Docker Swarm deployments:

services:
milvaion-api:
secrets:
- db_password
- jwt_secret
- redis_password
- rabbitmq_password

secrets:
db_password:
file: ./secrets/db_password.txt
jwt_secret:
file: ./secrets/jwt_secret.txt
redis_password:
file: ./secrets/redis_password.txt
rabbitmq_password:
file: ./secrets/rabbitmq_password.txt

Kubernetes Secrets​

apiVersion: v1
kind: Secret
metadata:
name: milvaion-secrets
namespace: milvaion
type: Opaque
stringData:
db-password: "your-secure-db-password"
jwt-secret: "your-256-bit-jwt-secret"
redis-password: "your-redis-password"
rabbitmq-password: "your-rabbitmq-password"

Reference in deployment:

env:
- name: MilvaionConfig__Redis__Password
valueFrom:
secretKeyRef:
name: milvaion-secrets
key: redis-password

Logging Security​

Log Level Configuration​

Reduce sensitive information in logs for production:

{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft.AspNetCore.Authentication": "Warning",
"Microsoft.AspNetCore.Authorization": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
}
}
}
}

Seq Log Server Security​

# docker-compose.yml
seq:
environment:
- SEQ_FIRSTRUN_ADMINPASSWORD=${SEQ_ADMIN_PASSWORD}
- ACCEPT_EULA=Y

⚠️ Important: Change the Seq admin password immediately after first deployment.


Worker Security​

Resource Limits​

Prevent resource exhaustion attacks:

# docker-compose.yml
worker:
deploy:
resources:
limits:
cpus: '2'
memory: 2048M
reservations:
cpus: '0.5'
memory: 512M

Worker Configuration​

{
"Worker": {
"WorkerId": "worker-01",
"MaxParallelJobs": 32,
"ExecutionTimeoutSeconds": 300
}
}
SettingDescriptionSecurity Impact
MaxParallelJobsLimit concurrent executionsPrevents resource exhaustion
ExecutionTimeoutSecondsKill long-running jobsPrevents hung processes

Network Security​

Reverse Proxy Configuration (nginx)​

server {
listen 443 ssl http2;
server_name milvaion.your-domain.com;

ssl_certificate /etc/ssl/certs/milvaion.crt;
ssl_certificate_key /etc/ssl/private/milvaion.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers off;

# Security headers
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

location / {
proxy_pass http://milvaion-api:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

Firewall Rules​

Only expose necessary ports:

ServicePortExposure
Milvaion API5000Via reverse proxy only
PostgreSQL5432Private network only
Redis6379Private network only
RabbitMQ5672Private network only
RabbitMQ Management15672Disabled or internal only
Seq5341Internal only

Security Checklist​

Pre-Production​

  • Change all default passwords (PostgreSQL, Redis, RabbitMQ, Seq)
  • Generate new JWT signing key (256-bit random)
  • Enable SSL/TLS for database connections
  • Set strong password policies
  • Configure account lockout
  • Set MILVA_ENV=prod environment variable

Infrastructure​

  • Place databases on private networks
  • Configure reverse proxy with TLS termination
  • Set up firewall rules
  • Disable RabbitMQ management UI or restrict access
  • Enable Redis protected mode
  • Remove default guest user from RabbitMQ

Monitoring​

  • Set up alerts for failed login attempts
  • Monitor worker health anomalies
  • Configure log retention policies
  • Enable database backup monitoring

Regular Maintenance​

  • Rotate secrets quarterly
  • Update container images for security patches
  • Review activity logs regularly
  • Audit user permissions
  • Test backup restoration procedures

Incident Response​

Signs of Compromise​

IndicatorAction
Multiple failed logins from same IPReview logs, consider IP blocking
Unexpected admin user creationDisable account, investigate
Unusual job execution patternsReview job logs and payloads
Database connection spikesCheck for injection attempts
Worker heartbeat anomaliesInvestigate worker health

Response Steps​

  1. Contain - Isolate affected systems
  2. Identify - Review logs in Seq/Grafana
  3. Eradicate - Remove threat, rotate all credentials
  4. Recover - Restore from known-good backups
  5. Document - Record incident details and lessons learned