SHADOW AI
Authentication is the process of establishing the identity of a user, service, or other security principal.
For a secure AI platform, authentication is not simply a login form. It is a complete security subsystem covering:
Account registration
Password protection
Email verification
Multi-factor authentication
Session management
Access tokens
Refresh tokens
Device/session tracking
Account recovery
Credential changes
Login protection
Suspicious authentication detection
Logout and revocation
Administrative authentication
Service-to-service identity
A compromised authentication system can undermine almost every other security control in the platform.
Therefore, authentication should be designed as a dedicated security boundary rather than scattered across individual API endpoints.
A typical architecture is:
Client
↓
Authentication Endpoint
↓
Input Validation
↓
Credential Verification
↓
MFA / Additional Verification
↓
Session Creation
↓
Session Store
↓
Authenticated Request
↓
Session Validation
↓
Identity Context
↓
Authorization
The key distinction is:
Authentication
↓
Who are you?
Authorization
↓
What are you allowed to do?
Authentication should never be treated as authorization.
The platform may contain multiple identity types.
Examples:
Regular users
Organization members
Administrators
Support personnel
Examples:
Background workers
AI orchestration services
Media-processing workers
Notification services
Examples:
OAuth/OIDC providers
Enterprise identity providers
Social login providers
Examples:
Internal service credentials
Short-lived workload identities
Deployment identities
Each identity category should have an appropriate authentication mechanism.
A secure registration flow can be:
Registration Request
↓
Input Validation
↓
Rate Limit
↓
Password Policy Validation
↓
Create Account
↓
Store Password Hash
↓
Create Verification Challenge
↓
Send Verification Message
↓
User Verifies Account
↓
Account Activated
The application should avoid activating sensitive capabilities before the required verification steps are completed.
Passwords must never be stored as plaintext.
Do not store:
password = "MyPassword123"
Instead, use a password hashing algorithm designed specifically for password storage.
Modern options include:
Argon2id
bcrypt
scrypt
For new systems, Argon2id is commonly a strong choice when supported and appropriately configured.
The password hash should be stored rather than the original password.
Conceptually:
Password
↓
Password Hashing Algorithm
↓
Password Hash
↓
Database
During login:
Submitted Password
↓
Password Verification
↓
Stored Hash
↓
Match / Reject
The server should never need to recover the original password.
Password hashing systems should use unique salts.
Conceptually:
Password + Unique Salt
↓
Password Hash
Modern password-hashing libraries generally manage salts automatically.
Developers should avoid inventing custom password hashing schemes.
Password policies should balance security and usability.
Controls can include:
minimum length
maximum supported length
breached-password detection
rejection of extremely common passwords
rate limiting
secure password reset
Avoid unnecessarily complicated composition rules that encourage predictable patterns.
For example, forcing users to repeatedly add:
Password1!
Password2!
Password3!
does not necessarily create stronger long-term security.
Longer passwords or passphrases are generally preferable.
The application should support reasonably long passwords.
It should also protect against abusive inputs such as extremely large request bodies.
Therefore:
Password policy
+
Request-size limits
should both exist.
The system should not silently truncate passwords because truncation can create confusing security behavior.
A secure login flow can be:
POST /auth/login
↓
Validate request
↓
Rate-limit request
↓
Locate account
↓
Verify password
↓
Check account state
↓
Check MFA requirement
↓
Create authenticated session
↓
Record security event
↓
Return appropriate response
The response should avoid unnecessarily revealing whether a particular account exists.
For example, instead of:
Email does not exist.
the system can use a generic authentication failure message.
Failed authentication attempts should be monitored.
Relevant events include:
login.failed
login.success
mfa.failed
password.reset.requested
password.reset.completed
session.revoked
account.locked
These events support detection and incident response.
However, logging must avoid storing:
plaintext passwords
authentication tokens
MFA secrets
password-reset tokens
unnecessary sensitive information
Authentication endpoints are common targets for:
credential stuffing
brute-force attempts
automated abuse
Rate limiting can be applied at multiple levels:
IP
Account
Device/session
Network
Tenant
Global authentication service
A single IP-based limit may be insufficient because attackers can distribute requests across many addresses.
Likewise, an account-only limit can be abused to deny legitimate users.
A layered approach is generally more resilient.
Account lockout must be designed carefully.
A permanent or aggressive lockout can allow attackers to intentionally lock other users out.
Alternatives include:
progressive delays
temporary restrictions
adaptive verification
MFA challenges
risk-based controls
notification of suspicious activity
The objective is to slow abusive authentication without creating an easy denial-of-service mechanism.
Multi-factor authentication adds another security layer.
Common factors include:
Something the user knows:
Password
PIN
Something the user has:
Authenticator device
Security key
Verified device
Something the user is:
Biometric factor
A secure platform should support appropriate MFA methods based on its threat model.
Time-based one-time passwords are commonly implemented using authenticator applications.
The flow is:
Server generates MFA secret
↓
User enrolls authenticator
↓
Authenticator generates code
↓
User submits code
↓
Server verifies code
The secret must be protected carefully.
It should not be returned through ordinary API responses after enrollment.
A secure enrollment process should require authentication before enabling MFA.
A stronger flow can include:
Authenticated session
↓
Request MFA enrollment
↓
Additional verification
↓
Display enrollment information
↓
User submits valid MFA code
↓
Activate MFA
↓
Generate recovery codes
MFA should not become active until enrollment has been successfully verified.
Users can lose access to their authenticator.
Recovery codes provide a backup mechanism.
They should be:
generated securely
high entropy
shown only when appropriate
stored securely
individually invalidated after use
protected against replay
Example conceptual state:
Recovery Code
↓
Unused
↓
Consumed
A consumed recovery code should never work again.
For higher-security accounts, phishing-resistant authentication mechanisms such as WebAuthn/passkeys can provide stronger protection than passwords alone.
Conceptually:
User
↓
Authenticator
↓
Cryptographic challenge
↓
Signed response
↓
Server verification
The server stores public credential information rather than the user's private authenticator key.
Private keys remain protected by the authenticator.
Passkeys can provide passwordless or password-reduced authentication.
The architecture generally relies on public-key cryptography.
The server stores:
credential ID
public key
user association
metadata
The private key remains protected by the user's device/authenticator.
This can reduce exposure to password phishing and credential reuse.
After successful authentication, the application needs an authenticated session.
A secure session architecture can be:
Login
↓
Session Creation
↓
Session Identifier
↓
Secure Cookie
↓
Browser
↓
Authenticated Request
↓
Session Validation
For browser applications, secure HTTP-only cookies are often preferable to exposing long-lived authentication credentials directly to JavaScript.
Important cookie attributes include:
HttpOnly
Secure
SameSite
Prevents ordinary JavaScript from reading the cookie.
This reduces some token-theft opportunities during XSS attacks.
Ensures the cookie is transmitted only over HTTPS.
Controls cross-site cookie transmission and contributes to CSRF defense.
The exact SameSite policy should match the application's architecture.
Session identifiers must be unpredictable.
Do not use:
userId
email
timestamp
incrementing number
as session identifiers.
Instead, generate cryptographically secure random values.
A session ID should not contain meaningful user information.
A session database can contain:
sessionId
userId
tenantId
createdAt
expiresAt
lastSeenAt
revokedAt
device metadata
security metadata
The exact information should be minimized according to privacy requirements.
Sessions should have controlled lifetimes.
Possible controls include:
absolute expiration
idle expiration
refresh expiration
manual revocation
security-event revocation
For example:
User inactive
↓
Session expires
or:
Password changed
↓
Existing sessions revoked
The correct lifetime depends on risk and user experience requirements.
Important authentication events can trigger session rotation.
Examples:
Login
MFA completion
Privilege elevation
Password change
Email verification
Account recovery
Rotating the session identifier helps reduce session fixation risks.
Session fixation occurs when an attacker attempts to cause a victim to use a session identifier known to the attacker.
A secure implementation should:
Pre-authentication session
↓
Successful authentication
↓
New authenticated session identifier
Never simply upgrade an attacker-known anonymous session into an authenticated session without rotation.
Logout should invalidate the session server-side.
A robust logout flow:
Logout Request
↓
Authenticate session
↓
Revoke session
↓
Clear cookie
↓
Record security event
Clearing the browser cookie alone is not always sufficient if server-side sessions remain valid.
Users should ideally have an option such as:
Sign out of all devices
The server can revoke all active sessions associated with the account.
This is especially important after:
suspected account compromise
password change
device loss
security incident
A user security page can display:
Current device
Windows / Chrome
Last active: recent
Mobile device
Android
Last active: earlier
Other browser
Chrome
Last active: earlier
Users can revoke sessions individually.
Avoid exposing unnecessary device-identifying information.
Some architectures use short-lived access tokens with refresh tokens.
Conceptually:
Short-lived Access Token
↓
API access
Long-lived Refresh Token
↓
Obtain new access token
Refresh tokens require particularly strong protection because they can maintain long-term access.
A secure architecture can rotate refresh tokens.
Conceptually:
Refresh Token A
↓
Refresh
↓
Token B issued
↓
Token A invalidated
If an old refresh token is reused unexpectedly, the server can detect potential token theft and revoke the associated token family.
Access tokens should generally be short-lived when practical.
Long-lived credentials increase the period during which a stolen credential can be abused.
The exact lifetime should be determined by:
threat model
application type
usability requirements
revocation architecture
JSON Web Tokens can be useful but are frequently misused.
Common problems include:
excessive lifetime
weak signing configuration
missing audience validation
missing issuer validation
accepting unintended algorithms
storing tokens insecurely
inability to revoke compromised tokens
A JWT should not automatically be treated as safer than a server-side session.
The authentication architecture should choose tokens based on actual requirements rather than popularity.
When JWTs are used, validation should include appropriate checks such as:
signature
issuer
audience
expiration
not-before
algorithm
key identity
token type
The server should not trust claims simply because they are syntactically valid.
Authentication tokens may contain claims such as:
userId
tenantId
roles
scopes
However, highly dynamic authorization information should not necessarily live indefinitely inside long-lived tokens.
For example:
User promoted to admin
↓
Old token still says member
or:
Admin privileges removed
↓
Old token still says admin
Short-lived credentials and server-side authorization checks can reduce this problem.
Account recovery is effectively another authentication pathway.
Therefore:
The security of account recovery should be comparable to the security of login.
A weak recovery flow can bypass a strong password and MFA system.
A secure password-reset flow can be:
User requests reset
↓
Generic response
↓
Generate random reset token
↓
Store protected token representation
↓
Send reset message
↓
User submits token
↓
Validate token
↓
Set new password
↓
Invalidate reset token
↓
Revoke appropriate sessions
Reset tokens should be:
unpredictable
short-lived
single-use
securely stored
invalidated after use
The request:
POST /auth/password-reset
should generally not reveal whether the supplied account exists.
For example, a generic response can indicate that if the account is eligible, recovery instructions will be sent.
This reduces account enumeration.
Email verification can establish control of an email address.
The process:
Registration
↓
Verification token
↓
Email
↓
User clicks verification link
↓
Server validates token
↓
Email marked verified
Verification tokens should have:
expiration
cryptographic randomness
single-use semantics
revocation after successful use
Changing a user's email address should be treated as a sensitive operation.
A stronger workflow is:
Authenticated user
↓
Re-authentication / MFA
↓
Request new email
↓
Verify new address
↓
Update account
↓
Notify old address where appropriate
↓
Invalidate relevant sessions if required
This reduces account takeover through unauthorized email changes.
Some operations deserve stronger verification even when the user already has an active session.
Examples:
change password
disable MFA
change primary email
delete account
access sensitive financial data
create privileged API credentials
The application can require:
current password
+
MFA
or another appropriate strong-authentication method.
Administrative accounts should receive stronger controls.
Recommended principles include:
mandatory MFA
stronger session policies
restricted administrative interfaces
privileged-action auditing
least privilege
separate administrative roles
reauthentication for dangerous operations
session monitoring
Administrative privileges should not automatically be inherited by ordinary user sessions.
When a user temporarily performs a privileged operation:
Normal session
↓
Additional authentication
↓
Temporary privilege
↓
Sensitive operation
↓
Privilege expires
This reduces the exposure associated with permanently elevated sessions.
AI platforms frequently contain:
API server
Worker
AI router
Media processor
Notification service
Storage service
These services must authenticate to each other.
Avoid shared permanent credentials whenever possible.
Preferred approaches include:
workload identity
short-lived credentials
service identity
mTLS where appropriate
scoped service tokens
Each service should have only the permissions it requires.
Conceptually:
API Service
↓
Authenticated Service Identity
↓
Worker
The receiving service should verify:
Who is calling?
Is the credential valid?
Is it intended for this service?
Is this operation permitted?
Important events should generate security telemetry.
Examples:
authentication.success
authentication.failure
mfa.enabled
mfa.disabled
password.changed
password.reset
email.changed
session.created
session.revoked
credential.created
credential.revoked
Security monitoring can then identify suspicious patterns.
Signals can include:
unusually high login failures
impossible or unusual access patterns
repeated password-reset requests
rapid session creation
unexpected geographic changes
abnormal device patterns
repeated MFA failures
privileged login from unusual contexts
Detection should be risk-based rather than relying on a single signal.
AI platforms introduce additional authentication concerns.
An attacker who compromises an AI account may gain access to:
private prompts
uploaded documents
conversation history
generated media
stored memories
API keys
payment information
agent capabilities
connected tools
Therefore, authentication security directly protects the AI platform's broader data and action surface.
AI agents should not automatically inherit a user's full identity and permissions.
A safer architecture is:
User
↓
Agent Session
↓
Explicit Capability
↓
Specific Tool
↓
Authorized Action
For example, permission to summarize a document should not automatically imply permission to delete the document.
The platform should carefully protect:
password hashes
session identifiers
refresh tokens
MFA secrets
recovery codes
API credentials
service credentials
OAuth tokens
These should never appear in:
application logs
analytics events
error messages
client-visible debug output
screenshots
telemetry payloads
Sensitive authentication secrets should be protected at rest using appropriate security controls.
Examples:
Database encryption
Secret-management systems
Key management systems
Access-controlled storage
Encryption alone does not solve authorization problems.
The application must also restrict who can retrieve authentication secrets.
Cookie-based authentication introduces CSRF considerations.
Important controls can include:
SameSite cookies
CSRF tokens where required
origin validation
strict request methods
appropriate CORS configuration
State-changing operations should not be casually exposed to cross-site requests.
CORS configuration should be explicit.
Avoid broad policies equivalent to:
Allow every origin
especially when credentials are involved.
Use an allowlist appropriate to the actual frontend architecture.
A clean API might include:
POST /auth/register
POST /auth/login
POST /auth/logout
POST /auth/refresh
POST /auth/verify-email
POST /auth/password-reset/request
POST /auth/password-reset/confirm
POST /auth/mfa/enroll
POST /auth/mfa/verify
POST /auth/mfa/disable
GET /auth/sessions
DELETE /auth/sessions/:id
POST /auth/sessions/revoke-all
The exact endpoints depend on the chosen authentication architecture.
A simplified conceptual model could include:
User
├── id
├── email
├── passwordHash
├── emailVerifiedAt
├── status
└── createdAt
Session
├── id
├── userId
├── createdAt
├── expiresAt
├── revokedAt
└── metadata
MFA
├── userId
├── type
├── secretReference
└── enabledAt
RecoveryCode
├── id
├── userId
├── codeHash
├── usedAt
└── createdAt
Sensitive values should be protected appropriately.
Account state can be modeled as:
REGISTERED
↓
EMAIL_PENDING
↓
VERIFIED
↓
ACTIVE
↓
SUSPENDED
↓
DISABLED
Recovery and security states may introduce additional transitions.
Explicit state modeling prevents scattered boolean flags from producing inconsistent behavior.
Account deletion should consider:
active sessions
refresh tokens
API credentials
MFA configuration
recovery codes
personal data
uploaded files
AI memories
generated media
payment information
audit requirements
Deleting the primary user record alone may leave sensitive credentials or data behind.
Testing should include:
valid registration
invalid input
duplicate account
verification
rate limiting
valid credentials
invalid credentials
expired account
suspended account
MFA-enabled account
brute-force protection
creation
expiration
rotation
revocation
logout
logout-all
reset request
expired token
reused token
invalid token
password change
session invalidation
enrollment
verification
incorrect code
recovery code
disable flow
| Scenario | Expected Result |
|---|---|
| Correct password | Authentication succeeds |
| Incorrect password | Authentication fails |
| Expired session | Request rejected |
| Revoked session | Request rejected |
| Invalid reset token | Reset rejected |
| Reused reset token | Reset rejected |
| Invalid MFA code | Verification rejected |
| Used recovery code | Rejected |
| Cross-user session ID | Rejected |
| Expired refresh token | Rejected |
| Revoked refresh token | Rejected |
| Unauthorized privilege change | Rejected |
Passwords are never stored plaintext.
Modern password hashing is used.
Password inputs are safely handled.
Common/breached passwords are considered.
Credential stuffing protections exist.
Session IDs are cryptographically random.
Cookies use appropriate security attributes.
Sessions expire.
Sessions can be revoked.
Sessions rotate after important authentication events.
Logout invalidates server-side sessions.
MFA is supported where appropriate.
Enrollment requires verification.
Recovery codes are protected.
MFA removal requires strong verification.
Reset tokens are random.
Reset tokens expire.
Tokens are single-use.
Recovery does not expose account existence.
Relevant sessions are revoked after recovery.
Admin accounts require strong authentication.
Privileged operations are audited.
Privilege elevation is controlled.
Administrative sessions are monitored.
Service identities exist.
Credentials are scoped.
Short-lived credentials are preferred.
Service permissions follow least privilege.
┌───────────────────┐
│ Client │
└─────────┬─────────┘
│
▼
┌───────────────────┐
│ Auth API Gateway │
└─────────┬─────────┘
│
┌───────────────┴───────────────┐
│ │
▼ ▼
┌─────────────────┐ ┌─────────────────┐
│ Credential │ │ MFA / Passkey │
│ Verification │ │ Verification │
└────────┬────────┘ └────────┬────────┘
│ │
└───────────────┬───────────────┘
▼
┌───────────────────┐
│ Session Manager │
└─────────┬─────────┘
│
┌───────────────┼──────────────┐
▼ ▼ ▼
Session DB Audit Detection
│ │ │
└───────────────┴──────────────┘
│
▼
┌───────────────────┐
│ Authorization │
│ / Policy Engine │
└───────────────────┘
The most important principles are:
Authentication establishes identity; authorization determines access.
Never store plaintext passwords.
Use established password-hashing algorithms rather than custom cryptography.
Treat account recovery as an authentication mechanism.
Protect sessions as carefully as passwords.
Use secure, unpredictable session identifiers.
Rotate sessions after important authentication transitions.
Provide session revocation.
Use MFA for appropriate risk levels, especially privileged accounts.
Protect MFA secrets and recovery codes.
Prefer phishing-resistant authentication where practical.
Keep access tokens short-lived when possible.
Treat refresh tokens as high-value credentials.
Do not expose authentication secrets in logs.
Use explicit service identities for internal services.
Monitor authentication events for suspicious behavior.
Require stronger verification for sensitive account changes.
Test authentication boundaries independently and continuously.
Authentication is the foundation upon which the rest of the AI platform's authorization model depends.
A production-grade implementation must protect the complete identity lifecycle—from registration and password storage through MFA, session management, recovery, privilege elevation, service authentication, and eventual account deletion.
The strongest design is not simply one that makes login difficult to attack. It is one that ensures that every credential, session, recovery mechanism, privileged action, and service identity has a clearly defined lifecycle and security boundary.
With authentication and sessions established, the next stage is to build the platform's external API security layer around these identities.
Next: Chapter 107 — Secure API Security Implementation: Authentication Middleware, Authorization Middleware, API Keys, OAuth/OIDC, Rate Limiting, Request Validation & API Abuse Protection
Comments
Post a Comment