admin管理员组文章数量:1125776
I'm making a small personal project to learn react and python flask as backend. I am using flask_cors and didn't have much of an issue until I wanted to use a custom middleware to check the JWT token.
The error doesn't occur in Postman, only in browser, and I could check in Postman that the middleware works fine.
This is my code:
app = Flask(__name__)
CORS(app, supports_credentials=True, resources={r"/*": {"origins": "*"}})
def jwt_required(f):
@wraps(f)
def decorated(*args, **kwargs):
json_data = request.json
token = json_data['token']
if not token:
return redirect('/Login')
try:
data = jwtOG.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
print("COMPROBAR TOKEN:", data)
except jwtOG.ExpiredSignatureError:
return redirect('/Login')
except jwtOG.InvalidTokenError:
return redirect('/Login')
return f(*args, **kwargs)
return decorated
@app.route("/getAlluser", methods=["GET"])
@jwt_required
def getAlluser():
if request.method == "GET":
try:
conn,cur = sqlOpen()
response= getSqlgetAlluser(conn,cur)
# Puedes devolver una respuesta JSON si es necesario
return jsonResponse("success", response, '', 0)
except Exception as e:
# Manejar posibles errores
return jsonify({"error": str(e)}), 400
else:
return jsonify({"error": "Método no permitido"}), 405
Missing CORS headers in the response
If I don't add the middleware the error doesn't happen and you can see the CORS headers in the response.
I have tried adding the cors headers manually, and the method "OPTIONS" in the route methods. I have also tried to do the middleware with the app.before_request to the same outcome (Works in postman but not in browser)
I'm making a small personal project to learn react and python flask as backend. I am using flask_cors and didn't have much of an issue until I wanted to use a custom middleware to check the JWT token.
The error doesn't occur in Postman, only in browser, and I could check in Postman that the middleware works fine.
This is my code:
app = Flask(__name__)
CORS(app, supports_credentials=True, resources={r"/*": {"origins": "*"}})
def jwt_required(f):
@wraps(f)
def decorated(*args, **kwargs):
json_data = request.json
token = json_data['token']
if not token:
return redirect('/Login')
try:
data = jwtOG.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
print("COMPROBAR TOKEN:", data)
except jwtOG.ExpiredSignatureError:
return redirect('/Login')
except jwtOG.InvalidTokenError:
return redirect('/Login')
return f(*args, **kwargs)
return decorated
@app.route("/getAlluser", methods=["GET"])
@jwt_required
def getAlluser():
if request.method == "GET":
try:
conn,cur = sqlOpen()
response= getSqlgetAlluser(conn,cur)
# Puedes devolver una respuesta JSON si es necesario
return jsonResponse("success", response, '', 0)
except Exception as e:
# Manejar posibles errores
return jsonify({"error": str(e)}), 400
else:
return jsonify({"error": "Método no permitido"}), 405
Missing CORS headers in the response
If I don't add the middleware the error doesn't happen and you can see the CORS headers in the response.
I have tried adding the cors headers manually, and the method "OPTIONS" in the route methods. I have also tried to do the middleware with the app.before_request to the same outcome (Works in postman but not in browser)
Share Improve this question edited yesterday VLAZ 28.8k9 gold badges62 silver badges82 bronze badges asked 2 days ago fglopezfglopez 11 bronze badge New contributor fglopez is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 3 |1 Answer
Reset to default 0Getting a CORS error when testing it with your browser but not when testing it with Postman is perfectly reasonable: CORS is only checked by browsers. Postman is an application and therefore doesn't validate anything regarding CORS.
If you did try setting it up using the app.before_request functionality, please check that CORS headers are present the response, therefore you should be adding them to the app.after_request method. (see this answer here and here)
Keep in mind that it is the browser that will not continue with the request if the response from the flask application does not provide these headers, it is not the server which is rejecting the request. Confusing, but that's just how CORS is.
本文标签:
版权声明:本文标题:python - Why am I getting blocked by CORS policy when I added a middleware to check the JWT token? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736656920a1946278.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
Authorization
as an allowed request header in your CORS configuration. – jub0bs Commented 2 days ago