HIGH cors wildcardgrapebearer tokens

Cors Wildcard in Grape with Bearer Tokens

Cors Wildcard in Grape with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Grape is a Ruby REST-like framework commonly used to build APIs, and it allows CORS configuration via the rack-cors middleware. When a CORS rule uses a wildcard origin (*) together with credentials-bearing requests such as Bearer Tokens in the Authorization header, the effective security boundary can be weakened in practice, even if the token itself is not transmitted to wildcard origins under strict browser behavior.

Many APIs rely on Bearer Tokens for authorization, where the token is passed as Authorization: Bearer <token>. A common but risky CORS setup in Grape looks like this:

# config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :delete, :options],
      expose: ['Authorization'],
      allow_credentials: true
  end
end

In this configuration, origins '*' means any origin is allowed, while allow_credentials: true tells browsers to include credentials (including cookies and HTTP authentication) in cross-origin requests. However, when credentials are included, browsers do not allow the wildcard origin (*) to be used. In many browser implementations, this combination is either ignored or treated as an insecure configuration, potentially allowing requests from unexpected origins if the server does not validate the Origin header properly.

An attacker can craft a malicious web page hosted on a different origin that sends authenticated requests using the victim’s Bearer Token. Even if the browser blocks direct credential leakage to a wildcard origin, misconfigured middleware or lack of strict origin validation may allow the request to proceed. This can lead to unauthorized API calls on behalf of the user, especially if the API relies solely on the Bearer Token for authorization without additional checks.

Moreover, CORS is a browser-enforced mechanism; non-browser clients (such as curl or Postman) do not respect CORS policies. If an API endpoint using wildcard CORS also accepts Bearer Tokens and does not validate the token scope or origin context server-side, an attacker who obtains a token can abuse it from any origin. This is why CORS rules must be as specific as possible, and sensitive endpoints should never rely on wildcard origins when credentials or tokens are involved.

Bearer Tokens-Specific Remediation in Grape — concrete code fixes

To secure Grape-based APIs that use Bearer Tokens, CORS configuration should explicitly define allowed origins and avoid using a wildcard when credentials are required. Below is a secure CORS setup that specifies origins and correctly handles Bearer Token authorization headers.

# config/initializers/cors.rb
allowed_origins = ['https://app.example.com', 'https://admin.example.com']

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins *allowed_origins
    resource '*',
      headers: ['Authorization', 'Content-Type'],
      methods: [:get, :post, :put, :delete, :options],
      expose: ['Authorization'],
      allow_credentials: true
  end
end

On the server side, ensure that token validation is performed for every request. Grape provides before hooks to verify the presence and correctness of the Bearer Token. Here is an example of a Grape API class that validates tokens before allowing access to protected resources:

class API > Grape::API
  format :json

  before do
    auth_header = env['HTTP_AUTHORIZATION']
    unless auth_header&.start_with?('Bearer ')
      error!('Unauthorized', 401)
    end

    token = auth_header.split(' ').last
    unless valid_token?(token)
      error!('Invalid token', 401)
    end
  end

  resource :secure do
    get do
      { message: 'Access granted with valid Bearer Token' }
    end
  end

  private

  def valid_token?(token)
    # Replace with actual token validation logic, e.g., JWT verification
    # Example: JWT.decode(token, Rails.application.secrets.secret_key_base)[0]
    token == 'expected_secure_token_value'
  end
end

Additionally, avoid exposing the Authorization header unnecessarily. Only include it in the expose list if client-side JavaScript needs to read it. For most APIs, it is safer to keep authorization headers restricted to server-to-server communication.

For teams using the middleBrick platform, the Pro plan includes continuous monitoring that can detect risky CORS configurations involving wildcard origins and credential usage, helping you identify insecure settings before they are exploited. The CLI tool allows you to scan your Grape endpoints from the terminal with a simple command:

$ middlebrick scan https://api.example.com

By combining strict origin policies, server-side token validation, and automated scanning, you can reduce the risk associated with CORS wildcard and Bearer Token misconfigurations.

Related CWEs: dataExposure

CWE IDNameSeverity
CWE-200Exposure of Sensitive Information HIGH
CWE-209Error Information Disclosure MEDIUM
CWE-213Exposure of Sensitive Information Due to Incompatible Policies HIGH
CWE-215Insertion of Sensitive Information Into Debugging Code MEDIUM
CWE-312Cleartext Storage of Sensitive Information HIGH
CWE-359Exposure of Private Personal Information (PII) HIGH
CWE-522Insufficiently Protected Credentials CRITICAL
CWE-532Insertion of Sensitive Information into Log File MEDIUM
CWE-538Insertion of Sensitive Information into Externally-Accessible File HIGH
CWE-540Inclusion of Sensitive Information in Source Code HIGH

Frequently Asked Questions

Is it safe to use 'Access-Control-Allow-Origin: *' with Bearer Tokens?
No. When credentials or Bearer Tokens are used, the browser requires specific origins. Using a wildcard origin with allow_credentials can lead to insecure behavior and should be avoided.
How can I validate Bearer Tokens in a Grape API?
Use a before hook to extract and validate the token from the Authorization header before allowing access to protected resources, as shown in the remediation code example.