Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CORS does not work with OpenAPI #47

Closed
GasperFunda opened this issue Nov 23, 2022 · 4 comments
Closed

CORS does not work with OpenAPI #47

GasperFunda opened this issue Nov 23, 2022 · 4 comments
Labels
bug Something isn't working Stale

Comments

@GasperFunda
Copy link

With using flask-cors I cannot reach my endpoints via my web app. If I change to normal Flask cors settings work.

Environment:

  • Python version: 3.9.1
  • Operating system: Windows 10
  • Flask version: 2.2.2
  • flask-openapi3 version: 2.2.0
@GasperFunda GasperFunda added the bug Something isn't working label Nov 23, 2022
@dvaerum
Copy link
Contributor

dvaerum commented Nov 23, 2022

Hey @GasperFunda, could you provide a code example?

@GasperFunda
Copy link
Author

GasperFunda commented Nov 24, 2022

import json
from flask import request
from pymongo import MongoClient
from bson import json_util, ObjectId
from flask_openapi3 import Info, Tag
from flask_openapi3 import OpenAPI
import bcrypt
from models.user import Token, UserLogin, UserRegister, UserUpdate, UserUpdatePassword,UserCreate, User
import jwt
from flask_cors import CORS, cross_origin
info = Info(title="Users Microservice for Bank system cr23", version="1.0.0")
app = OpenAPI(__name__, info=info)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

client = MongoClient(host='mongodb',
                        port=27017, 
                        username='dbUser', 
                        password='dbPass',
                    authSource="admin")
db = client["users"]

def parse_json(data):
    return json.loads(json_util.dumps(data))

login_tag = Tag(name="Login", description="Logs user into the bank system.")
@app.post('/login', responses={"200": Token} ,tags=[login_tag])
@cross_origin()
def login(body: UserLogin):
    user = db.users.find_one({"email": body.email})
    if user:
        if bcrypt.checkpw(body.password.encode('utf-8'), user['password']):
            user.pop('password')
            return parse_json({"token": jwt.encode(parse_json(user), 'JWT_SECRET', algorithm='HS256')})
        else:
            return {"message": "Invalid password"}, 401
    return {"message": "Invalid username"}, 401

Here for example I could not reach the login endpoint via my React app due to CORS. When I changed back to normal Flask, everything worked fine.

@luolingchun
Copy link
Owner

@GasperFunda I didn't repeat your bug.

server:

from flask_cors import CORS, cross_origin

from flask_openapi3 import Info, Tag
from flask_openapi3 import OpenAPI

info = Info(title="Users Microservice for Bank system cr23", version="1.0.0")
app = OpenAPI(__name__, info=info)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

login_tag = Tag(name="Login", description="Logs user into the bank system.")


@app.post('/login', tags=[login_tag])
@cross_origin()
def login():
    return {"message": "Invalid username"}, 200


if __name__ == "__main__":
    app.run("0.0.0.0", debug=True)

js in console:

var url = "http://localhost:5000/login";
var httpRequest = new XMLHttpRequest();
httpRequest.open('POST', url, true);
httpRequest.setRequestHeader("Content-type", "application/json");
var obj = {
    "username": "mkii",
    "password": "1234"
};

httpRequest.send(JSON.stringify(obj));

// 响应后的回调函数
httpRequest.onreadystatechange = function () {
    if (httpRequest.readyState == 4 && httpRequest.status == 200) {
        var json = httpRequest.responseText;
        console.log(json);
    }
};

output:
image

server without CORS:

from flask_cors import CORS, cross_origin

from flask_openapi3 import Info, Tag
from flask_openapi3 import OpenAPI

info = Info(title="Users Microservice for Bank system cr23", version="1.0.0")
app = OpenAPI(__name__, info=info)
# cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

login_tag = Tag(name="Login", description="Logs user into the bank system.")


@app.post('/login', tags=[login_tag])
# @cross_origin()
def login():
    return {"message": "Invalid username"}, 200


if __name__ == "__main__":
    app.run("0.0.0.0", debug=True)

output:
image

@github-actions github-actions bot added the Stale label Jun 1, 2023
Copy link

github-actions bot commented Jun 1, 2024

This issue has been automatically closed because we haven't heard back for more than 365 days, please reopen this issue if necessary.

@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Jun 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working Stale
Projects
None yet
Development

No branches or pull requests

3 participants