Header Issue: Flask Server Not Receiving Custom Headers in Request (SECRET_KEY Issue) #5658
Unanswered
ansdnwls45
asked this question in
Q&A
Replies: 1 comment
-
You aren't configuring your CORS Setting properly. You are only allowing headers for "/" Try Basically, need to have the wildcards so that your cors settings aren't too restrictive. May not completely be the issue, I will try to reproducer later and get back with you. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Title:
Header Issue: Flask Server Not Receiving Custom Headers in Request (SECRET_KEY Issue)
Description:
Hello, I am experiencing an issue where my Flask server does not properly receive the SECRET_KEY header sent from the client (Postman, PowerShell, etc.). Despite configuring the Flask application with Flask-CORS and ensuring headers are sent from the client, the server consistently logs the received SECRET_KEY as None, resulting in a 403 Invalid SECRET_KEY response.
I have tried multiple debugging approaches, but the issue persists. Below is the detailed information about the setup, code, and error logs.
Environment:
Operating System: Windows 10
Python Version: 3.11
Flask Version: 2.2.5
Flask-CORS Version: 3.0.10
dotenv Version: 1.0.0
Reproduction Steps:
Set up the .env file in the project root directory with the following content:
API_SECRET_KEY=mflow1546
Run the following Flask application:
import os
from flask import Flask, request, jsonify
from flask_cors import CORS
import logging
from dotenv import load_dotenv
Load .env file
load_dotenv()
Get SECRET_KEY from environment variables
SECRET_KEY = os.getenv('API_SECRET_KEY', 'default_key')
if not SECRET_KEY or SECRET_KEY == 'default_key':
print(f"Loaded SECRET_KEY from environment: {SECRET_KEY}")
raise ValueError("SECRET_KEY is not properly set.")
Initialize Flask app
app = Flask(name)
CORS(app, resources={r"/": {"origins": ""}}, supports_credentials=True, allow_headers=["Content-Type", "SECRET_KEY"])
Configure logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s: %(message)s')
@app.route('/api/save', methods=['POST'])
def save_data():
try:
# Log all headers for debugging
headers = dict(request.headers)
logging.debug(f"All Headers: {headers}")
if name == 'main':
print(f"Loaded SECRET_KEY from .env: {SECRET_KEY}")
app.run(debug=True)
Use the following Postman setup to send a POST request:
URL: http://127.0.0.1:5000/api/save
Method: POST
Headers:
SECRET_KEY: mflow1546
Content-Type: application/json
Body (raw, JSON):
{
"key": "your_key_value",
"content": "This is a valid request",
"title": "Sample Title"
}
Alternatively, use the following PowerShell script to send the request:
$headers = @{
"SECRET_KEY" = "mflow1546"
"Content-Type" = "application/json"
}
$body = @"
{
"key": "your_key_value",
"content": "This is a valid request",
"title": "Sample Title"
}
"@
Invoke-RestMethod -Uri "http://127.0.0.1:5000/api/save" -Method POST -Headers $headers -Body $body
Expected Behavior:
The Flask server should receive the SECRET_KEY header correctly.
The request should pass validation and return a 200 OK response with the message "Data received successfully!".
Actual Behavior:
The SECRET_KEY received by the server is always None (as logged by the Received SECRET_KEY log).
The server consistently responds with a 403 Invalid SECRET_KEY error.
Debugging Steps Tried:
Verified the .env file is correctly loaded (the correct SECRET_KEY is printed at startup).
Ensured the headers in Postman and PowerShell are set properly.
Logged all headers received by the Flask server (custom headers like SECRET_KEY are not present).
Used Flask-CORS with allow_headers=["Content-Type", "SECRET_KEY"].
Tested with different HTTP clients (Postman, PowerShell, Python requests).
Logs:
Flask Server Logs:
Loaded SECRET_KEY from .env: mflow1546
Loaded SECRET_KEY: mflow1546
2024-12-22 08:21:18,527 WARNING: * Debugger is active!
2024-12-22 08:21:18,530 INFO: * Debugger PIN: 181-191-701
2024-12-22 08:12:30,764 DEBUG: All Headers: {'Content-Type': 'application/json', 'User-Agent': 'PostmanRuntime/7.43.0', 'Accept': '/', 'Cache-Control': 'no-cache', 'Postman-Token': 'ff45eb20-073b-43d5-8d99-4c474bbe7ff0', 'Host': '127.0.0.1:5000', 'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive', 'Content-Length': '110'}
2024-12-22 08:12:30,765 DEBUG: Received SECRET_KEY: None
2024-12-22 08:12:30,766 ERROR: Invalid SECRET_KEY in request.
Questions:
Why is the SECRET_KEY header missing from the received headers?
Is there an issue with Flask-CORS or how Flask processes custom headers?
Are there additional configurations required to properly receive custom headers in Flask?
Thank you for your time and assistance!
Beta Was this translation helpful? Give feedback.
All reactions