【发布时间】:2022-01-20 21:46:45
【问题描述】:
我在使用 Firebase 函数时遇到了 CORS 政策问题,即使我认为我在后端做的事情是正确的,我会向您展示代码。
const cors = require("cors");
const express = require("express");
const cookieParser = require('cookie-parser');
const app = express();
app.use(
cors({
origin: true,
credentials: true
}),
cookieParser(),
);
这是我试图从前端调用的函数:
app.post("/auth/login", (req, res) => login(req, res));
有了这个身体:
const login = async (req, res) => {
try {
const user = {
id: req.body.id,
password: req.body.password,
};
const auth = getAuth();
const { valid, errors } = validateLoginData(user);
if (!valid)
throw { code: "validation-failed", message: errors, status: 400 };
let data = await signInWithEmailAndPassword(auth, user.id, user.password);
let token = await data.user.getIdToken();
console.log("TOKEN: " + token);
res.cookie("_token", token, { httpOnly: true, maxAge: 3600000 });
return res.status(202).json({ message: "OK" });
} catch (err) {
switch (err.code) {
case "validation-failed":
return res.status(err.status).json({ message: err.message });
case "auth/user-not-found":
case "auth/wrong-password":
return res
.status(401)
.json({ message: "Wrong credentials, please try again" });
default:
return res.status(500).json({ message: err.message });
}
}
};
所以问题来了:当我从邮递员调用它时它可以工作,当我从我的浏览器调用它时(勇敢)它不起作用并且它在控制台中告诉我这个:
Access to XMLHttpRequest at 'https://europe-west1-stormtestfordota.cloudfunctions.net/api/auth/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'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
我已经尝试了许多我在网上找到的修复方法,但没有一个有效,请您帮帮我吗?
【问题讨论】:
-
不管您遇到什么问题,您是否了解像在此处那样允许任何具有凭据的来源的严重安全隐患?
-
是的!但是我们设置了安全规则来防止任何恶意行为
-
如何保护用户免受跨域请求伪造?
-
我们只使用 http cookie 以确保一切正常
-
HttpOnlycookie 属性对 CSRF 攻击没有任何作用...请重新考虑您的 CORS 配置并了解您在做什么。
标签: node.js firebase google-cloud-functions cors