Api Key Exposure in Strapi with Bearer Tokens
Api Key Exposure in Strapi with Bearer Tokens — how this specific combination creates or exposes the vulnerability
Strapi is an open-source headless CMS that often exposes REST and GraphQL endpoints under a predictable path such as /api/*. When APIs rely on bearer tokens for authentication, any leak of those tokens effectively grants access to the protected resources. In Strapi, developers sometimes configure routes as unauthenticated for convenience during development or due to incomplete policy configuration. If a route that should require a bearer token is left open, an unauthenticated scan by middleBrick can discover the endpoint and observe whether it returns sensitive data without credentials.
Bearer tokens are typically sent in the Authorization header as Bearer <token>. The risk arises when clients (mobile apps, SPAs, or third-party services) embed tokens in JavaScript bundles, environment variables checked into source control, or logs that are publicly accessible. Because Strapi can be deployed behind CDNs or reverse proxies, misconfigured CORS or missing route-level policies may allow any origin to invoke the endpoint with a valid-looking token. middleBrick tests unauthenticated attack surfaces; if a bearer-protected endpoint inadvertently allows requests without a token or with a weak token validation scheme, the scan flags it as a potential exposure.
During a scan, middleBrick checks whether sensitive endpoints return data without requiring proper authorization. For Strapi, this includes content types such as api::article.article or user-related endpoints like /api/users. If a developer uses a bearer token pattern but fails to enforce it consistently across controllers or services, the scan’s authentication checks may reveal endpoints that return PII, media URLs, or internal identifiers without validating the Authorization: Bearer header. This becomes a finding in the Authentication and Data Exposure categories, with remediation guidance to tighten route policies and verify token validation at the controller or plugin level.
Another vector specific to the combination of Strapi and bearer tokens is the use of the same token across environments. For example, a token generated from a local Strapi admin session might be accidentally embedded in a frontend config file. When that token is static or long-lived, it increases the window for misuse. middleBrick’s LLM/AI Security checks do not evaluate bearer tokens directly, but the scanner’s unauthenticated tests can surface endpoints that should have been restricted. Cross-referencing OpenAPI specs with runtime findings helps identify mismatches where the spec declares a bearer requirement but the implementation does not enforce it.
To illustrate a correct bearer token usage pattern in Strapi, consider a properly configured route that requires an authenticated request with a valid bearer token. The following example shows a cURL request that includes the header and expects a 200 response only when the token is valid. Note that Strapi’s actual enforcement happens via its policies and role-based access controls; this snippet demonstrates the client-side expectation.
curl -X GET "https://example.com/api/articles" \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0NSIsImlhdCI6MTcxODAwMDAwMH0.SignatureHere" \
-H "Accept: application/json"
Conversely, an incorrect setup might omit the header or use an invalid token, resulting in a 401 or 403 response. Developers should ensure that Strapi policies validate the token scope and that tokens are rotated regularly. middleBrick’s findings will highlight endpoints that do not enforce authentication, enabling teams to align implementation with the intended bearer token strategy and reduce the risk of unauthorized data exposure.
Bearer Tokens-Specific Remediation in Strapi — concrete code fixes
Remediation focuses on ensuring Strapi consistently validates bearer tokens for protected routes and that tokens are handled securely by clients and pipelines. On the server side, verify that content-type and route-specific policies require authentication. In Strapi, policies are defined under src/policies and can be attached to controllers. A policy that checks for a valid bearer token can validate the token format and, if using JWTs, confirm the signature and claims before allowing access.
Below is an example of a Strapi policy that checks for a bearer token in the Authorization header and performs basic validation. This policy should be assigned to routes that must be protected.
// src/policies/bearer-auth.js
module.exports = async (ctx, next) => {
const authHeader = ctx.request.header.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
ctx.throw(401, 'Unauthorized: Bearer token missing');
}
const token = authHeader.split(' ')[1];
if (!token) {
ctx.throw(401, 'Unauthorized: Malformed Authorization header');
}
// Optionally verify JWT or validate against a database of valid tokens
try {
// Example for JWT verification (use a library like jsonwebtoken)
// const payload = jwt.verify(token, process.env.JWT_SECRET);
// ctx.state.user = payload;
await next();
} catch (err) {
ctx.throw(401, 'Unauthorized: Invalid token');
}
};
Register this policy in src/policies/policy.json and attach it to the relevant API controllers via the Strapi admin panel or configuration files. This ensures that requests without a properly formatted Authorization: Bearer header are rejected before reaching the business logic.
On the client side, avoid embedding bearer tokens in JavaScript that can be extracted from the browser. Instead, use short-lived tokens and secure storage mechanisms. The following example shows a secure way to include a bearer token in API calls from a Node.js environment, reducing the risk of accidental exposure in logs or version control.
const fetch = require('node-fetch');
async function fetchArticles() {
const token = process.env.STRAPI_BEARER_TOKEN; // injected at runtime
const response = await fetch('https://example.com/api/articles', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Accept': 'application/json',
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
fetchArticles().then(data => console.log(data)).catch(err => console.error(err));
For teams using the middleBrick CLI, run middlebrick scan <url> to validate that your Strapi endpoints enforce bearer requirements and to detect any unauthenticated data exposure. Pro plan users can enable continuous monitoring to receive alerts if authentication configurations drift. In CI/CD, the GitHub Action can enforce a minimum security score and fail builds when bearer-related misconfigurations are detected. These integrations complement manual policy reviews and help maintain consistent authorization across deployments.
Finally, rotate bearer tokens regularly and restrict their scope to the minimum required permissions. If using JWTs, set short expiration times and implement refresh token strategies with strict validation. By combining server-side policy enforcement, secure client-side handling, and automated scans, teams can mitigate the risk of api key exposure through bearer tokens in Strapi.
Frequently Asked Questions
How can I test if my Strapi bearer token enforcement is working correctly?
middlebrick scan https://example.com/api/articles. Ensure the endpoint returns 401 when called without a token and 200 only when a valid Authorization: Bearer header is provided.