Xss Cross Site Scripting in Flask with Bearer Tokens
Xss Cross Site Scripting in Flask with Bearer Tokens — how this specific combination creates or exposes the vulnerability
Cross-site scripting (XSS) in a Flask API that uses Bearer tokens can occur when an API response embeds untrusted data into HTML, XML, or JSON that is later rendered by a client-side application. Even though Bearer tokens are typically transmitted in HTTP headers and not directly reflected in responses, the token’s associated user context (e.g., username, role, or profile data) may be included in API output. If this output is used in a downstream web client without proper escaping, stored or reflected XSS can be triggered. For example, an endpoint returning user-controlled data alongside a token reference might produce JSON like {"message": "Hello, "} which, when parsed and rendered unsafely in the browser, executes script in the context of the authenticated user’s session.
Flask itself does not automatically escape content, so developers must explicitly encode data inserted into HTML, JavaScript, or attribute contexts. When Bearer token usage is paired with session-based or JWT-based authentication, XSS becomes more impactful because a successful script can capture or misuse the token from browser storage or cookies. Attackers often chain XSS with insecure token handling (e.g., storing tokens in localStorage without adequate protections) to achieve account takeover or further privilege escalation.
The combination also highlights the importance of separating concerns: API endpoints should focus on data and integrity, while rendering and output encoding should be handled by the client framework with strict Content Security Policy (CSP). middleBrick’s LLM/AI Security checks can detect scenarios where API responses might inadvertently expose token-related metadata or unsafe patterns, while its parallel checks such as Input Validation and Data Exposure help identify injection points and sensitive data paths that contribute to XSS risk.
Bearer Tokens-Specific Remediation in Flask — concrete code fixes
Remediation focuses on preventing untrusted data from being interpreted as executable code and on protecting tokens from exposure in browser contexts. Use Flask’s built-in escaping utilities and response headers to ensure data is safely encoded. Below are concrete code examples demonstrating secure handling of Bearer tokens and user data in Flask.
Example 1: Safe JSON response with escaped content and secure token handling.
from flask import Flask, request, jsonify, make_response
import html
app = Flask(__name__)
@app.route('/api/hello', methods=['GET'])
def hello():
user_input = request.args.get('name', '')
# Escape user input to prevent injection into JSON that may be rendered in HTML
safe_name = html.escape(user_input)
# Do not include tokens in the response body
response = make_response(jsonify({
'message': f'Hello, {safe_name}',
'status': 'ok'
}))
# Secure token in Authorization header only; avoid setting tokens in cookies without HttpOnly
response.headers['Cache-Control'] = 'no-store'
response.headers['X-Content-Type-Options'] = 'nosniff'
return response
if __name__ == '__main__':
app.run(debug=False)
Example 2: Using JSON with proper MIME type and CSP headers to reduce XSS impact.
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/api/data', methods=['POST'])
def data():
token = request.headers.get('Authorization', '').replace('Bearer ', '')
if not token:
return jsonify({'error': 'Unauthorized'}), 401
# Validate and sanitize input before using it
user_data = request.json.get('data', '')
safe_data = user_data.strip()
# Return safe JSON with correct content type
resp = jsonify({'data': safe_data})
resp.headers['X-Frame-Options'] = 'DENY'
resp.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
return resp
Additional recommendations: store tokens in HttpOnly, Secure cookies when possible; enforce strict CSP headers; validate and sanitize all user-supplied input; and use frameworks that auto-escape in templates. middleBrick’s scans can surface missing escape calls, unsafe cookie attributes, and endpoints that return data alongside token metadata, enabling targeted fixes before deployment.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |