HIGH api key exposureaspnetsession cookies

Api Key Exposure in Aspnet with Session Cookies

Api Key Exposure in Aspnet with Session Cookies — how this specific combination creates or exposes the vulnerability

In ASP.NET applications, storing or transmitting API keys within session cookies can inadvertently expose sensitive credentials. Session cookies are typically designed to maintain user state, not to carry highly sensitive values such as API keys. When an API key is placed into a session cookie, it may be exposed through multiple vectors inherent to cookie handling and session management.

Cookies can be exposed if the HttpOnly flag is not set, making them accessible to client-side scripts via cross-site scripting (XSS) attacks. If the cookie lacks the Secure flag, it may be transmitted over unencrypted HTTP connections, risking interception. Additionally, if the session identifier or cookie value is logged inadvertently (for example, in server logs, browser history, or error messages), the embedded API key may be persisted in locations not intended for sensitive data.

ASP.NET session cookies often use identifiers that map to server-side session stores, but embedding an API key directly into the cookie value means the credential travels with every request. This behavior violates the principle of separation between authentication/session management and secrets management. Attackers who gain access to cookie data through XSS, insecure transmission, or log exposure can leverage the exposed API key to impersonate services or access external systems.

Consider an endpoint that relies on an API key stored in a session cookie to authorize requests to a third-party service. A scanner performing unauthenticated checks might detect the presence of the cookie and attempt to extract or replay it. In parallel security checks such as those for BOLA/IDOR or Data Exposure, the scan may surface that sensitive data is being stored in a cookie without adequate protections. The LLM/AI Security checks may further flag system prompt leakage patterns if cookie values are reflected in error messages or debug output, indicating information disclosure.

Compliance frameworks such as OWASP API Top 10 highlight the risks of storing sensitive data in cookies, and frameworks like PCI-DSS and SOC2 emphasize protecting credentials in transit and at rest. When API keys reside in session cookies, the application may fail to meet these standards due to insufficient protections like missing encryption at rest for session state, lack of strict transport policies, or inadequate input validation that allows injection into cookie values.

An example of insecure cookie usage in ASP.NET Core might involve setting a cookie with an API key value without applying essential security flags:

// Insecure cookie handling in ASP.NET Core
var apiKeyValue = "sk-proj-abc123...";
var cookieOptions = new CookieOptions
{
    // Missing Secure and HttpOnly flags
    Expires = DateTime.Now.AddMinutes(30)
};
Response.Cookies.Append("SessionApiKey", apiKeyValue, cookieOptions);

Without Secure and HttpOnly, the API key can leak through insecure channels and client-side scripts. Even if transmitted over HTTPS, embedding long-term secrets in cookies increases the attack surface. Regular scans using middleBrick can identify such patterns by correlating cookie usage with API key exposure findings across Authentication, Data Exposure, and LLM/AI Security checks, providing prioritized remediation guidance to move secrets out of session state and into secure storage.

Session Cookies-Specific Remediation in Aspnet — concrete code fixes

To mitigate API key exposure when using session cookies in ASP.NET, developers should avoid storing secrets directly in cookies and instead rely on server-side session storage with minimal identifiers in cookies. When cookies must be used, they must be hardened with security flags and treated as session handles rather than secret containers.

First, store the API key securely on the server (for example, in memory cache, distributed cache, or a secure vault) and keep only a non-sensitive session identifier in the cookie. If you must pass a reference, ensure the cookie is marked as Secure, HttpOnly, and scoped with SameSite to reduce exposure paths.

Here is an example of secure cookie configuration in ASP.NET Core that avoids placing sensitive values in the cookie itself:

// Secure cookie handling in ASP.NET Core
// Store the API key server-side, not in the cookie
HttpContext.Session.SetString("ApiKeyGuid", Guid.NewGuid().ToString());

var cookieOptions = new CookieOptions
{
    Secure = true,      // Transmit only over HTTPS
    HttpOnly = true,    // Prevent client-side script access
    SameSite = SameSiteMode.Strict, // Mitigate CSRF
    Expires = DateTime.Now.AddMinutes(30)
};
Response.Cookies.Append("SessionId", HttpContext.Session.Id, cookieOptions);

In this approach, the cookie only contains a session ID, while the API key remains in server-managed session storage. This aligns with separation of duties and reduces the risk of credential leakage through cookie theft or logging.

For applications that integrate with external services requiring API keys, retrieve the key from a secure server-side store at runtime rather than baking it into cookies. If the API key must be presented to a downstream service, do so from server memory or a secure client-side environment (such as a backend-for-frontend pattern), never from a cookie that could be accessed by browsers or intermediaries.

Additionally, enforce strict input validation for any data used to construct session cookies to prevent injection or tampering. Validate and sanitize all user-supplied values before they influence cookie contents. Combine these practices with transport security (HTTPS), short session lifetimes, and regular rotation of session identifiers to further limit exposure windows.

Using middleBrick scans, you can validate that cookies carry no sensitive values and that security flags are correctly applied. The tool’s checks for Data Exposure, Authentication, and LLM/AI Security help surface risky cookie usage patterns, while the CLI and Web Dashboard enable tracking these issues over time and integrating fixes into CI/CD workflows.

Frequently Asked Questions

Why is storing an API key in a session cookie considered risky in ASP.NET?
Storing an API key in a session cookie increases the risk of exposure through XSS, insecure transmission, or logging. Cookies may be accessed by scripts if HttpOnly is missing, transmitted in cleartext if Secure is missing, and inadvertently persisted in logs. This violates separation between session identifiers and secrets and expands the attack surface.
What are the essential cookie flags to protect session handling in ASP.NET Core?
Use Secure (HTTPS only), HttpOnly (block client-side script access), and SameSite (mitigate CSRF) flags. Avoid storing sensitive values in cookies; keep only non-sensitive identifiers and store secrets server-side in session or secure cache.