4

I want to set up CORS within my flask application and adding flask-cors helped up to a certain point. While "CORS(app)" helped with all routes that don't require Authorization, I can't access routes that do.

One route in question looks like this.

@users_blueprint.route('/users/<user_id>', methods=['GET'])
@authenticate
def get_single_user(resp, user_id):
response_object = {
    'status': 'failure',
    'message': 'Invalid Payload'
}

if resp != user_id:
    response_object['message'] = 'You are not authorized to view this user'
    return jsonify(response_object), 400

try:
    user = User.query.filter_by(user_id=user_id).first()
    if user:
        response_object['status'] = 'success'
        response_object['data'] = user.to_json()
        return jsonify(response_object), 200
    else:
        response_object['message'] = 'The user does not exist'
        return jsonify(response_object), 400
except (exc.IntegrityError, ValueError, TypeError) as e:
    db.session().rollback()
    return jsonify(response_object), 400

I played around with the CORS settings and so far got this:

#enable CORS
CORS(app, allow_headers=["Content-Type", "Authorization", \
        "Access-Control-Allow-Credentials"], supports_credentials=True)

But when I try to access the route in question from within my React application via fetch I get this error:

Failed to load MYROUTE: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 502. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

What else could I do?

EDIT

When I send a OPTIONS request via CURL I can see that my route in question will respond with "access-control-allow"-headers. So I'm really clueless as to what is going on. Here's also my fetch request:

const url = `myurlendpoint/myuserid`
const token = my_id_token
const options = {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  }
};
fetch(url, options)
  .then(response => console.log(response.json()))
  .catch(error => console.log(error))

ALSO: When I call my route without the header 'Authorization' present I get the correct response saying "No auth provided" and NOT the cross-origin problem. If this route really had not cross-origin-allow set then it should state that in my request without Authorization, right? So it has something to do with the Authorization header...

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
kidman01
  • 835
  • 5
  • 17
  • 32
  • have you tried `CORS(app, expose_headers='Authorization')`? Also, if you solved your problem, feel free to answer the question yourself for documentation – blkpingu Jul 17 '20 at 17:54

0 Answers0