React 的访问控制允许凭据问题

发布于 2025-01-15 18:08:07 字数 2894 浏览 3 评论 0原文

这是一个使用 React 创建登录系统的项目。但是当连接后端flask检查登录是否有效时,却出现了如下错误信息。希望有人能帮助我。我花了很多天试图解决这个问题并搜索每个相关的帖子,但仍然无法解决它:(

我正在使用 chrome 浏览器。 另外,我在 chrome 上安装了 Access-Control-Allow-Origin 插件。

错误消息

Access to fetch at 'http://localhost:5000/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.

前端代码(react)

fetch(domain+"/login", {
    body: JSON.stringify(mydata),
    credentials: "include",
    headers: new Headers({
       'Content-Type': 'application/json',
       'Access-Control-Allow-Credentials': true
    }),
            
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, cors, *same-origin
    redirect: 'follow', // manual, *follow, error
    referrer: 'no-referrer', // *client, no-referrer
    })
    .then(response=>{
      
       if(response.ok){
            
         return response.json()
       }
     }
        

后端(flask)包含以下代码以允许跨源

app = Flask(__name__)
CORS(app, supports_credentials=True)
@app.route('/login', methods=['GET', 'POST'])
def login():
    
    data = request.json       
    print(data)
    result = {}

    login_info = {
        "code": -1,
        "message": ""
    }
    
    if data:
        
        username = data['username']
        password = data['password']
        cur = database.cursor(dictionary=True)
        cur.execute(
            "SELECT username, password, role FROM user WHERE username = %s AND password = %s AND disabled = 0;", (username, password))
        # cur.execute("SELECT uid, displayname, rank, disabled FROM user WHERE username = %s AND password = %s;", (username, password,))
        # cur.execute("SELECT uid, displayname, rank, disabled FROM user WHERE username = %s AND password = AES_ENCRYPT(%s, UNHEX(SHA2('encryption_key', )));", (username, password,))
        account = cur.fetchone()
        if account:
            # modify_info(1, "Login successfully!")
            login_info["code"] = 1
            login_info["message"] = "Login successfully!"
            account_str = json.dumps(account, cls=MyEncoder)
            account_json = json.loads(account_str)
            session["username"] = account_json["username"]
            result["username"] = username
            result["role"] = account_json["role"]
            result["isLogin"] = 1

        else:
            # modify_info(0, "Login not successful")
            login_info["code"] = 0
            login_info["message"] = "Login not successful"

        cur.close()
    return jsonify({"code": login_info["code"], "data": result, "message": login_info["message"]})

Here is a project to create a login system using react. However when it connects to the back-end flask to check whether the login is valid or not, it shows the error message below. Hope someone can help me. I spent so many days trying to fix this and search every related post but still couldn't fix it :(

I'm using the chrome browser.
Also, I have installed the Access-Control-Allow-Origin plugin on chrome.

error message

Access to fetch at 'http://localhost:5000/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.

front-end code (react)

fetch(domain+"/login", {
    body: JSON.stringify(mydata),
    credentials: "include",
    headers: new Headers({
       'Content-Type': 'application/json',
       'Access-Control-Allow-Credentials': true
    }),
            
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, cors, *same-origin
    redirect: 'follow', // manual, *follow, error
    referrer: 'no-referrer', // *client, no-referrer
    })
    .then(response=>{
      
       if(response.ok){
            
         return response.json()
       }
     }
        

back-end(flask) include below code to allow cross origin

app = Flask(__name__)
CORS(app, supports_credentials=True)
@app.route('/login', methods=['GET', 'POST'])
def login():
    
    data = request.json       
    print(data)
    result = {}

    login_info = {
        "code": -1,
        "message": ""
    }
    
    if data:
        
        username = data['username']
        password = data['password']
        cur = database.cursor(dictionary=True)
        cur.execute(
            "SELECT username, password, role FROM user WHERE username = %s AND password = %s AND disabled = 0;", (username, password))
        # cur.execute("SELECT uid, displayname, rank, disabled FROM user WHERE username = %s AND password = %s;", (username, password,))
        # cur.execute("SELECT uid, displayname, rank, disabled FROM user WHERE username = %s AND password = AES_ENCRYPT(%s, UNHEX(SHA2('encryption_key', )));", (username, password,))
        account = cur.fetchone()
        if account:
            # modify_info(1, "Login successfully!")
            login_info["code"] = 1
            login_info["message"] = "Login successfully!"
            account_str = json.dumps(account, cls=MyEncoder)
            account_json = json.loads(account_str)
            session["username"] = account_json["username"]
            result["username"] = username
            result["role"] = account_json["role"]
            result["isLogin"] = 1

        else:
            # modify_info(0, "Login not successful")
            login_info["code"] = 0
            login_info["message"] = "Login not successful"

        cur.close()
    return jsonify({"code": login_info["code"], "data": result, "message": login_info["message"]})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

趴在窗边数星星i 2025-01-22 18:08:07

在规范中,Access-Control-Allow-Credentials: true 标头不允许与
Access-Control-Allow-Origin: * 标头。

但是, * 是 Fl​​ask cors 中原始标头的默认值,您应该将其设置为特定值,例如:

app = Flask(__name__)
CORS(app, origins=['http://localhost:3000'], supports_credentials=True)

另外,这里是有关它的文档的链接: https://flask-cors.readthedocs.io/en/latest/api.html

<一href="https://i.sstatic.net/uosPx.jpg" rel="nofollow noreferrer">在此处输入图像描述

更新

这似乎是cookie问题的samesite,这里是设置它的代码:

from flask import Flask, make_response
from flask_cors import CORS

app = Flask(__name__)
CORS(app, supports_credentials=True)

@app.route("/", methods=['POST'])
def index():
    res = make_response()
    res.set_cookie("name", value="I am cookie", samesite='Lax')
    return res, 500

app.run(debug=True)

In the specification, the Access-Control-Allow-Credentials: true header is not allowed to use with
the Access-Control-Allow-Origin: * header.

However, * is the default value for the origin header in flask cors, you should set it to a specific value, for example:

app = Flask(__name__)
CORS(app, origins=['http://localhost:3000'], supports_credentials=True)

Also, here is link to the document about it: https://flask-cors.readthedocs.io/en/latest/api.html

enter image description here

Update

It seems like the samesite of the cookie problem, here's the code to set it:

from flask import Flask, make_response
from flask_cors import CORS

app = Flask(__name__)
CORS(app, supports_credentials=True)

@app.route("/", methods=['POST'])
def index():
    res = make_response()
    res.set_cookie("name", value="I am cookie", samesite='Lax')
    return res, 500

app.run(debug=True)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文