new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

OWASP Cheat Sheets · all subjects

authentication

408 notes in this subject, read out of this brain and free to use. This is page 5 of 7.

Authentication requirement for legacy applications

Ensure that only authenticated users can access the legacy application. Authentication could be enforced by the application itself, or by use of an IdP (Identity Provider) service. If the application is hosted in a restricted network environment, authentication should also be required to access this network environment, such as requiring users to authenticate to a VPN server before accessing the application.

Laravel app key must be generated for encryption and hashing

Laravel applications require an app key generated via the php artisan key:generate command. The app key is used for symmetric encryption and SHA256 hashes including cookie encryption, signed URLs, password reset tokens, and session data encryption.

Laravel file and directory permissions: directories 775, non-executable files 664

All Laravel directories should be configured with a maximum permission level of 775. Non-executable files should have a maximum permission level of 664. Executable files such as Artisan or deployment scripts should have a maximum permission level of 775.

Enable EncryptCookies middleware in web middleware group

The EncryptCookies middleware must be added to the web middleware group in App\Http\Kernel class to enable cookie encryption, particularly when using the cookie session store or storing sensitive data. This middleware is added to the 'web' key in the $middlewareGroups array.

APP_DEBUG environment variable must be false in production

To disable debug mode in production Laravel applications, set the APP_DEBUG environment variable to false. This prevents sensitive information exposure in error messages and stack traces.

Session cookie HttpOnly attribute configuration in config/session.php

Set 'http_only' => true in config/session.php to enable the HttpOnly attribute on session cookies. This prevents session cookies from being accessible from JavaScript, protecting against XSS-based cookie theft.

Session cookie domain attribute should be null unless using subdomains

Unless the Laravel application uses sub-domain route registrations, set the cookie 'domain' attribute to null in config/session.php. This ensures only the same origin (excluding subdomains) can set the cookie.

Session SameSite cookie attribute: set to lax or strict

Configure the 'same_site' attribute to 'lax' or 'strict' in config/session.php to restrict session cookies to first-party or same-site context, mitigating CSRF attacks.

HTTPS-only applications: set secure cookie attribute to true

For HTTPS-only Laravel applications, set the 'secure' configuration option to true in config/session.php to protect against man-in-the-middle attacks. For applications with mixed HTTP/HTTPS, set this value to null so the secure attribute is set automatically when serving HTTPS requests.

Session idle timeout: 2-5 minutes for high-value, 15-30 minutes for low-risk

Configure session lifetime in config/session.php using the 'lifetime' setting. OWASP recommends a 2-5 minute idle timeout for high-value applications and 15-30 minutes for low-risk applications. This is configured by setting the 'lifetime' value in minutes.

Laravel authentication guards: session and token types

Laravel authentication facilities consist of guards and providers. Guards define how users are authenticated per request. Providers define how users are retrieved from persistent storage. Laravel ships with a session guard (maintains state using session storage and cookies) and a token guard (for API tokens).

Laravel authentication providers: eloquent and database types

Laravel provides two default providers for user retrieval: eloquent provider (retrieves users using Eloquent ORM) and database provider (retrieves users using database query builder). Both are configured in config/auth.php and custom providers can be built.

Laravel Breeze starter kit authentication features

Laravel Breeze is a simple, minimal implementation of Laravel authentication features including login, registration, password reset, email verification, and password confirmation. It is recommended to use starter kits for robust and secure authentication.

Laravel Fortify: headless authentication with two-factor authentication

Laravel Fortify is a headless authentication backend that includes login, registration, password reset, email verification, password confirmation, and two-factor authentication features. It is recommended to use as a starter kit for secure authentication.

Laravel Jetstream: UI starter kit with Fortify authentication

Laravel Jetstream is an application starter kit providing a UI on top of Laravel Fortify's authentication features. It is recommended to use for robust and secure authentication implementations.

Laravel API authentication: Passport and Sanctum packages

Laravel offers two API authentication packages. Passport is an OAuth2 authentication provider. Sanctum is an API token authentication provider. Starter kits such as Fortify and Jetstream have built-in support for Sanctum.

Kubelet API requires authentication and authorization in production

Kubelets expose HTTPS endpoints granting powerful control over nodes and containers. By default, Kubelets allow unauthenticated access to this API. Production clusters should enable Kubelet authentication and authorization. Refer to Kubelet authentication/authorization documentation for implementation details.

Enable RBAC on kube-apiserver with --authorization-mode flag

To enable Role-Based Access Control, start the API server with the --authorization-mode flag set to a comma-separated list that includes RBAC, for example: kube-apiserver --authorization-mode=Example,RBAC --other-options --more-options

Kubernetes Dashboard security risks and mitigations

The Kubernetes Dashboard is a powerful web management tool that must be secured carefully. Risks include exposure without authentication leading to cluster compromise. Mitigations include: do not expose the dashboard to the public; turn on Role-Based Access Control to limit service account privileges; grant permissions per user; use network policies to block requests from internal pods; check that no role binding for cluster-admin exists (pre-1.8); deploy with an authenticating reverse proxy using multi-factor authentication with OIDC id_tokens or Kubernetes Impersonation to use user credentials instead of privileged ServiceAccount.

Kubernetes API authorization denies by default; all parts of request must be allowed

In Kubernetes, authentication (logged in) must occur before authorization (granted permission). When the API server authorizes requests, permissions are denied by default. The server evaluates all request attributes against all policies and allows or denies the request. All parts of an API request must be allowed by some policy in order to proceed.

Recommended external API authentication methods for Kubernetes

Due to weaknesses in Kubernetes' internal authentication mechanisms, production and larger clusters should use external authentication. Recommended methods include: OpenID Connect (OIDC) for externalizing authentication with short-lived tokens and centralized groups for authorization; managed Kubernetes distributions (GKE, EKS, AKS) using respective IAM provider credentials; Kubernetes Impersonation for both managed and on-prem clusters to externalize authentication without API server configuration changes. Additionally, API access should use Multi-Factor Authentication (MFA) for all user access.

Kubernetes built-in API authentication methods not recommended for production

Kubernetes provides internal authentication mechanisms unsuitable for production: Static Token File stores clear text tokens in CSV on API server nodes and cannot be modified until server restart; X509 Client Certs lack certificate revocation support, making credentials impossible to revoke or modify without rotating the root CA and re-issuing all certificates; Service Accounts Tokens are primarily for workload-to-API authentication, not user authentication.

Always log authentication successes and failures

Failed authentication attempts provide critical early indicators of credential-based attacks such as brute-force, credential-stuffing, and password-spraying. Monitoring repeated failures for the same account, failures from multiple IP addresses, or rapid bursts of login attempts helps detect account takeover attempts before they succeed. Authentication successes and failures must always be logged as these events are essential for identifying security incidents and supporting incident investigation. This aligns with OWASP ASVS 7.1.1 for authentication failure logging requirements.

Always log session management failures

Session management failures must always be logged. Examples include cookie session identification value modification or suspicious JWT validation failures.

Tenant identification from authenticated session, not client headers

Establish tenant context early in the request lifecycle via middleware/interceptor. Extract tenant ID from verified JWT claims in the authenticated session, never from client-supplied headers or request parameters. Validate the extracted tenant exists and is active before proceeding.

Bind tenant context using ContextVar for thread-safe propagation

Use contextvars.ContextVar to maintain thread-safe tenant context throughout the request lifecycle. Create a TenantContext object containing tenant_id, user_id, roles, and is_validated flag. Propagate this context through all application layers and reset it after request processing.

Validate tenant context in middleware before processing requests

Implement TenantMiddleware that extracts tenant_id from verified JWT claims, validates that the tenant exists and is active in the database, creates a TenantContext object with validation flag set to true, and sets the context using current_tenant.set(). Return 401 Unauthorized if tenant context is missing; return 403 Forbidden if tenant is invalid or inactive.

Use @require_tenant decorator to enforce tenant context on sensitive operations

Create a @require_tenant decorator that validates current_tenant.get() returns a context with is_validated=True before allowing function execution. Raise SecurityException if tenant context is missing or validation flag is false.

Do not derive tenant context from client-supplied headers or parameters

Never extract or trust tenant IDs from request headers, query parameters, or body. Always derive tenant context from verified JWT claims in authenticated session.

Do not skip tenant validation for 'internal' services or background jobs

All database queries, cache operations, and storage access must include tenant validation, even for internal/backend services. Background jobs must explicitly set tenant context before processing.

Do not share API keys or credentials across tenants

Generate unique API keys for each tenant. Never reuse or share credentials across tenant boundaries.

Bearer tokens and audience restriction requirement

Bearer tokens (RFC 6750) are the most common access token type, requiring only the token value for API access. Since anyone possessing a bearer token can use it, bearer tokens must be restricted to a single audience (Resource Server) to limit the impact of token leakage.

Refresh tokens require sender-constraining or rotation

Refresh tokens are credentials used to obtain new access tokens. They must be protected using sender-constraining mechanisms (DPoP or mTLS) or refresh token rotation. Refresh token rotation involves issuing new refresh tokens and invalidating old ones immediately to detect replay attempts. Combining PoP-constrained refresh tokens with rotation provides defense-in-depth.

Proof of Possession tokens protect against token replay and interception

Proof of Possession (PoP) tokens are cryptographically bound to clients through mechanisms like DPoP (RFC 9449) or mTLS-bound access tokens (RFC 8705). These tokens are bound to a private key owned by the client and the client must demonstrate possession of this private key to use the token. This approach provides additional protection when token interception is a concern.

Prevent open redirectors to avoid authorization code and access token exfiltration

Clients and Authorization Servers must not expose URLs that forward the user's browser to arbitrary URIs obtained from a query parameter, as open redirectors enable exfiltration of authorization codes and access tokens.

PKCE provides CSRF protection for OAuth clients with PKCE support

Clients that have ensured the Authorization Server supports PKCE may rely on the CSRF protection provided by PKCE. In OpenID Connect flows, the nonce parameter provides CSRF protection. Otherwise, one-time user CSRF tokens carried in the state parameter that are securely bound to the user agent must be used for CSRF protection.

Use issuer parameter for clients interacting with multiple Authorization Servers

When an OAuth Client can interact with more than one Authorization Server, clients should use the issuer iss parameter as a countermeasure, or rely on an iss value in the authorization response, such as the iss Claim in the ID Token in OpenID Connect. When these countermeasure options are absent, clients may instead use distinct redirect URIs to identify authorization endpoints and token endpoints.

Avoid forwarding requests containing user credentials

An Authorization Server must avoid forwarding or redirecting a request potentially containing user credentials accidentally.

PKCE mitigates authorization code interception and injection attacks

Proof Key for Code Exchange (PKCE, pronounced pixy) is used to mitigate authorization code interception attacks. It protects authorization codes created for public clients because PKCE ensures that an attacker cannot redeem a stolen authorization code at the token endpoint without knowledge of the code_verifier. PKCE also protects against authorization code injection attacks.

Use PKCE for all client types including SPAs and native applications

Clients must use the Authorization Code Grant with PKCE (response_type=code) for all client types, including single-page applications and native applications. Existing applications using the Implicit Grant must migrate. The hybrid code id_token response type may be used only when an OpenID Connect ID Token is required at the authorization endpoint; access tokens must still be obtained via the token endpoint and never via the front channel.

PKCE code challenge must not expose the verifier in authorization request

When using PKCE, clients should use PKCE code challenge methods that do not expose the PKCE verifier in the authorization request, because attackers who can read the authorization request can break the security provided by PKCE. Authorization servers must support PKCE.

Authorization Server must enforce PKCE code_verifier at token endpoint

If a client sends a valid PKCE code_challenge parameter in the authorization request, the authorization server must enforce the correct usage of code_verifier at the token endpoint.

Mitigate PKCE Downgrade Attacks by requiring code_challenge presence

Authorization Servers must mitigate PKCE Downgrade Attacks by ensuring a token request containing a code_verifier parameter is accepted only if a code_challenge parameter was present in the authorization request.

Implicit Grant is deprecated and must not be used

The Implicit Grant (response_type=token) is deprecated by RFC 9700 §2.1.2 and removed from OAuth 2.1. It exposes access tokens in the URL fragment, which leaks via browser history, referrer headers, and proxy/server logs, and access tokens obtained this way cannot be sender-constrained. Major identity providers have either disabled it or marked it for removal.

DPoP Proof of Possession mechanism (RFC 9449)

DPoP (Demonstration of Proof of Possession - RFC 9449) works as follows: The client generates a public-private key pair. The Authorization Server can sender-constrain the access token to the client's public key by including a cnf (confirmation) claim with a JWK thumbprint (jkt), although this is optional and implementation-dependent. For each API request, the client includes a proof-of-possession of its private key as a JWT signed with this private key that includes a hash of the access token. The Resource Server validates both the access token and the DPoP proof (including the token hash) to ensure the request originates from the legitimate token holder. DPoP does not require mutual TLS authentication; proof is provided via DPoP HTTP headers; is suitable for various client types including browsers and mobile applications; but requires additional cryptographic operations per request.

Mutual TLS Certificate-Bound Access Tokens mechanism (RFC 8705)

Mutual TLS Certificate-Bound Access Tokens (RFC 8705) work as follows: The client authenticates using a TLS client certificate during the TLS handshake (mutual TLS authentication, mTLS). The Authorization Server binds the access token to the client certificate's thumbprint via the cnf claim. The Resource Server validates that the certificate presented during the TLS handshake matches the certificate bound to the access token. This mechanism operates at the transport layer; leverages existing TLS infrastructure; can use PKI or self-signed certificates for certificate management; authentication occurs during connection establishment; and requires no per-request proof generation.

Use Proof of Possession tokens for sensitive data and high-value transactions

Proof of Possession tokens are particularly valuable in scenarios requiring enhanced token security. Consider PoP tokens for: access tokens that need to be used for more than one audience (Resource Server); APIs handling sensitive data (financial, healthcare, personal information); high-value transactions (payments, critical operations); long-lived tokens where extended validity periods warrant additional protection; cross-organizational access (B2B integrations); mobile and native applications where the client environment may present additional security considerations; and distributed architectures where tokens traverse multiple network boundaries.

Implement sender-constrained access tokens using DPoP or mTLS

For advanced protection against token replay scenarios, Authorization and Resource Servers may implement mechanisms for sender-constraining access tokens, such as Mutual TLS for OAuth 2.0 (mTLS - RFC 8705) or Demonstration of Proof of Possession (DPoP - RFC 9449). These mechanisms cryptographically bind tokens to specific clients through proof-of-possession of the private key.

Restrict access token privileges to minimum required

The privileges associated with an access token should be restricted to the minimum required for the particular application or use case. This prevents clients from exceeding the privileges authorized by the Resource Owner, prevents users from exceeding their privileges, and reduces the impact of access token leakage. Combine with sender-constrained tokens for defense-in-depth.

Do not use Resource Owner Password Credentials Grant

The Resource Owner password credentials grant must not be used because it insecurely exposes the credentials of the Resource Owner to the client, increasing the attack surface of the application.

Use asymmetric methods for Authorization Server client authentication

Authorization Servers should use client authentication when possible. It is recommended to use asymmetric (public-key based) methods for client authentication such as mTLS or private_key_jwt (OpenID Connect). When asymmetric methods are used, Authorization Servers do not need to store sensitive symmetric keys, making these methods more robust against several attacks.

Prevent client influence over client_id, sub, and other claims

Authorization Servers must not allow clients to influence their client_id or sub value or any other Claim that can be confused with a genuine Resource Owner. It is recommended to use end-to-end TLS.

Authorization responses must use HTTPS, no HTTP except loopback

Authorization responses must not be transmitted over unencrypted network connections. Authorization Servers must not allow redirect URIs that use the http scheme except for native clients that use Loopback Interface Redirection.

PBKDF2 for password hashing in .NET

Use System.Security.Cryptography.Rfc2898DeriveBytes for PBKDF2 password hashing in .NET Framework 4.6 and earlier versions. For .NET Framework 4.6.1 and later or .NET Core, use Microsoft.AspNetCore.Cryptography.KeyDerivation.Pbkdf2, which has significant advantages over Rfc2898DeriveBytes.

Access token restriction to Resource Servers, resources, and actions

Access tokens must be restricted to certain Resource Servers, resources, and actions. The Authorization Server should associate the access token with: - Specific Resource Servers (audience restriction, preferably to a single Resource Server) - Specific resources and actions on those Resource Servers Every Resource Server is obliged to verify for every request whether the access token was meant to be used for that particular Resource Server, and for that particular action on that particular resource. If not, the Resource Server must refuse to serve the request. Clients and Authorization Servers may utilize the following parameters to determine Resource Servers, resources, and/or actions: - scope parameter - resource parameter - authorization_details parameter

Multifactor Authentication Cheat Sheet available

The Multifactor Authentication Cheat Sheet is available in the OWASP series covering MFA controls and methods.

OAuth2 Cheat Sheet available

The OAuth2 Cheat Sheet is available in the OWASP series covering OAuth 2.0 authorization flow and implementation.

Single question from bank should not change until answered correctly

If the user is asked a single question selected from a bank of possible questions, that question should not be changed until the user answers it correctly. Allowing attempts at different security questions greatly increases chance of attacker guessing or obtaining answer to one of them.

Indicating expected answer format for security questions

It is beneficial to give users indication of the format for entering answers through input validation or recommendation. For example, when asking for a date, indicating format should be 'DD/MM/YYYY' prevents users from having to guess what format they used when registering.

NIST prohibition on security questions as authentication factor

NIST SP 800-63 no longer recognizes security questions as an acceptable authentication factor. Account recovery is an alternate authentication method and must be as strong as regular authentication. NIST SP 800-63B section 5.1.1.2 paragraph 4 states: 'Verifiers SHALL NOT prompt subscribers to use specific types of information (e.g., "What was the name of your first pet?") when choosing memorized secrets.'

Give your agent this brain