当通过p5 loadImage()请求图片时,Safari不发送cookie给Express。

问题描述 投票:1回答:2

背景资料

我建立了一个 代理后的Express.js应用 让用户在被引导到网络应用之前先登录。这个 应用程序在Safari (macOSiOS)中无法提供一些图片,因为Safari没有将图片请求的cookie发送回来。 源于 loadImage() 方法,而在我的p5.js代码中。这在Chrome(macOS)上不会发生。

当我加载页面时,浏览器请求的资源很好。但来自我的应用程序的请求会返回一个不同的会话,它没有登录,并被Express捕获。

// Request for the main page by the browser
Session {
  cookie:
   { path: '/',
     _expires: 2020-05-04T16:26:00.291Z,
     originalMaxAge: 259199998,
     httpOnly: true,
     secure: true },
  loggedin: true }

// Request for image assets by a script in my application
Session {
  cookie:
   { path: '/',
     _expires: 2020-05-04T16:26:00.618Z,
     originalMaxAge: 259200000,
     httpOnly: true,
     secure: true } }

来自Safari的HTTP请求

GET https://mydomain/app/img/svg/Water.svg HTTP/1.1
Host: mydomain
Origin: https://mydomain
Connection: keep-alive
If-None-Match: W/"5e6-171c689d240"
Accept: image/png,image/svg+xml,image/*;q=0.8,video/*;q=0.8,*/*;q=0.5
If-Modified-Since: Wed, 29 Apr 2020 15:24:13 GMT
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Safari/605.1.15
Referer: https://mydomain/app/
Accept-Language: en-us
Accept-Encoding: gzip, deflate, br

HTTP/1.1 302 Found
Date: Fri, 01 May 2020 06:50:07 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.3.17
X-Powered-By: Express
Location: /
Vary: Accept
Content-Type: text/plain; charset=utf-8
Content-Length: 23
Access-Control-Allow-Origin: *
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive

Found. Redirecting to /

快速应用

应用程序设置在HTTPS代理后面,所以我将Express Session对象设置为信任代理,并将安全设置为自动(设置为false并不能解决问题)。

app.set('trust proxy', 1)
app.use(session({
    secret: 'my-secret',
    resave: true,
    saveUninitialized: true,
    cookie: {
        secure: 'auto',
        maxAge: 259200000
    }
}));

当用户登录时,它被发送到了 /auth 以检查数据库

app.post('/auth', function (request, response) {
    var user = request.body.user;
    var password = request.body.password;

    if (user && password) {
        connection.query('SELECT * FROM accounts WHERE user = ? AND password = ?', [user, password], function (error, results, fields) {
            if (results.length > 0) {

                request.session.loggedin = true;

                // If the user logs in successfully, then register the subdirectory
                app.use("/app", express.static(__dirname + '/private/'));

                // Then redirect
                response.redirect('/app');
            } else {
                response.send('Incorrect password!');
            }
            response.end();

            if (error) {
                console.log(error);
            }
        });
    } else {
        response.send('Please enter Username and Password!');
        response.end();
    }
});

他们被转到了 /app 登录时。

app.all('/app/*', function (request, response, next) {

    if (request.session.loggedin) {    
        next(); // allow the next route to run
    } else {
        // The request for images from my p5 script fails and these request redirect to "/"
        response.redirect("/");
    }
})

问题

我怎样才能确保Safari在请求时传递会话cookie,以便Express能够返回正确的资产?


编辑

包括调用 loadImage(). 这被嵌入到一个ES6类中,该类为化学模拟中的粒子加载图像资产。这个类必须成功地解析承诺,这样其他高阶类才能设置正确的属性。

loadParticleImage() {

    return new Promise((resolve, reject) => {

        loadImage(this.imageUrl, (result) => {

            // Resolves the Promise with the result
            resolve(result);

        }, (reason) => {

            console.log(reason);
        });
    })
}

编辑#2

将请求成功的头信息直接包含在图片资产的URL中。

GET https://mydomain/app/img/svg/Water.svg HTTP/1.1
Host: mydomain
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Cookie: connect.sid=s%3A2frOCv41gcVRf1J4t5LlTcWkdZTdc8NT.8pD5eEHo6JBCHcpgqOgszKraD7AakvPsMK7w2bIHlr4
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Safari/605.1.15
Accept-Language: en-us
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
express safari p5.js express-session
2个回答
2
投票

我建议使用 快递的静态中间件 来提供静态文件。有了它,你就不需要任何会话来获取图片、js、css等。此外,它还能加速你的应用程序。你需要将

app.use(express.static( ... )) 

在...之前 app.use(session( ... )) 语句,因为如果你想要一些额外的性能,因为如果你这样做,express将不会尝试为静态文件创建会话。


2
投票

语句,因为如果你这样做,express将不会为静态文件建立会话。fetch() 召见 源码 为此 loadImage() 功能没有设置 credentials 选择权 控制是否在请求中包含cookie,因此cookie不会随请求发送。

你真的需要在服务图像之前进行认证吗? 如果不需要,您可以重新安排您的服务器中的图像服务方式,这样就可以在不需要验证的情况下使用 express.static() 指向一个只包含无需认证即可提供服务的资源的目录。 如果这些资源确实需要认证,您可能需要对 loadImage() 代码,以使用 credentials: include 选项或以不同的方式加载你的图像。

© www.soinside.com 2019 - 2024. All rights reserved.