express-session/cors/Axios 返回 401(未经授权)

发布于 2025-01-18 12:13:35 字数 2194 浏览 4 评论 0原文

更新:它在Firefox上显然可以使用,我正在使用Brave。我想它正在用会话阻止cookie?我不知道该怎么办。


我正在构建一个带有VUE的应用程序,并通过Axios连接到用Express制造的API。

我正在尝试使用明确的课程来管理登录会议和auth。在我的Local主机上,它效果很好,但是当我尝试从Heroku上托管的网站使用它时,它会破裂。检查会话是否具有usuario属性的中间件会阻止呼叫。

我很确定这与HTTP而不是HTTP有关。我用一些生成的凭据在Localhost HTTPS上测试了它,并以相同的方式破裂。

登录的终点很长,但是基本上检查您给出的密码是否正确,如果是正确的,则将其设置为req.session.usuario带有一些用户数据的对象。之后,当我再次检查会话时,未设置usuario

CORS中间件:

const cors = require("cors");

const whitelist = ["https://localhost:8080", "https://hosted-client.herokuapp.com"];
const corsOptions = {
    credentials: true,
    origin: (origin, callback) => {
        if (whitelist.includes(origin))
            return callback(null, true);

        //callback(new Error("CORS error"));
        callback(null, true);
    },
};

module.exports = cors(corsOptions);

会话中间件:

const Redis        = require("ioredis");
const connectRedis = require("connect-redis");
const session      = require("express-session");

const RedisStore = connectRedis(session);
const redisClient = new Redis(
    process.env.REDIS_PORT,
    process.env.REDIS_HOST,
    {password: process.env.REDIS_PASSWORD}
);

module.exports = session({
    store: new RedisStore({ client: redisClient }),
    secret: process.env.SECRET,
    saveUninitialized: false,
    resave: process.env.STATE_ENV === "production",
    proxy: true,
    cookie: {
        secure: process.env.STATE_ENV === "production",
        httpOnly: true,
        sameSite: "none",
        // maxAge: 1000 * 60 * 30, // 30 minutos
    },
});

简单的测试验证中间件:

module.exports = function (req, _, next) {
    if (!req.session || !req.session.usuario) {
        const err = new Error("No se encontró una sesión");
        err.statusCode = 401;

        next(err);
    }
    next();
}

客户端上的Axios实例:

require("dotenv").config();
import axios from "axios";

export default axios.create({
    baseURL: process.env.VUE_APP_API,
    headers: {
        "Content-type": "application/json",
    },
    withCredentials: true,
});

我不确定这是否足够信息,如果不是让我知道。

UPDATE: it aparently works on firefox, I was using brave. I guess it's blocking the cookie with the session?? I don't know what to do about that.


I'm building an app with Vue, connecting through Axios to an API made with express.

I'm trying to use express-session to manage login sessions and auth. On my localhost it works great, but when I tried to use it from the site hosted on heroku, it breaks. The middleware that checks whether the session has an usuario property blocks the call.

I'm pretty sure it has to do with https instead of http. I tested it on localhost https with some generated credentials and it broke the same way.

The endpoint for login is quite long, but basically checks if the password you gave it is correct, and if it is, it sets req.session.usuario to an object with some user data. After that, when I check again for the session, usuario is not set.

The CORS middleware:

const cors = require("cors");

const whitelist = ["https://localhost:8080", "https://hosted-client.herokuapp.com"];
const corsOptions = {
    credentials: true,
    origin: (origin, callback) => {
        if (whitelist.includes(origin))
            return callback(null, true);

        //callback(new Error("CORS error"));
        callback(null, true);
    },
};

module.exports = cors(corsOptions);

The session middleware:

const Redis        = require("ioredis");
const connectRedis = require("connect-redis");
const session      = require("express-session");

const RedisStore = connectRedis(session);
const redisClient = new Redis(
    process.env.REDIS_PORT,
    process.env.REDIS_HOST,
    {password: process.env.REDIS_PASSWORD}
);

module.exports = session({
    store: new RedisStore({ client: redisClient }),
    secret: process.env.SECRET,
    saveUninitialized: false,
    resave: process.env.STATE_ENV === "production",
    proxy: true,
    cookie: {
        secure: process.env.STATE_ENV === "production",
        httpOnly: true,
        sameSite: "none",
        // maxAge: 1000 * 60 * 30, // 30 minutos
    },
});

A simple test auth middleware:

module.exports = function (req, _, next) {
    if (!req.session || !req.session.usuario) {
        const err = new Error("No se encontró una sesión");
        err.statusCode = 401;

        next(err);
    }
    next();
}

The Axios instance on the client:

require("dotenv").config();
import axios from "axios";

export default axios.create({
    baseURL: process.env.VUE_APP_API,
    headers: {
        "Content-type": "application/json",
    },
    withCredentials: true,
});

I'm not sure if that's enough info, if not let me know.

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文