1

我正在尝试使用身份验证检查创建动态子域。子域按预期工作,但由于我添加了身份验证,它只是被忽略了,至少在大多数情况下。isAuthenticated 总是返回 false,所以理论上它应该总是重定向到登录。但事实并非如此。日志也非常随机地打印(在我看来是什么)。

有人可以帮我弄这个吗?

subdomains.forEach(subdomain => {
    const subDir = `${subdomainDir}/${subdomain}/`;

    let subExpress = express();

    subExpress.use(express.static(__dirname + subDir));

    subExpress.get('*', async (req, res) => {
        let isAuthenticated = false;

        try {
            isAuthenticated = await login.isAuthenticated(req.get('authorization'))
        } catch (error) {
            console.log(error);
        }

        console.log("subdomain", subdomain)
        console.log("isAuthenticated", isAuthenticated, "subdomain === login", subdomain === "login");

        if (isAuthenticated || subdomain === "login") {
            res.sendFile(`/${subDir}index.html`, {
                root: '.'
            });
        } else {
            res.redirect(301, `https://login.${domain}/`);
        }
    });

    app.use(vhost(`${subdomain}.${domain}`, subExpress));
});

let unusedSub = express();

unusedSub.get('*', (req, res) => {
    console.log("unusedSub");
    res.redirect(`https://dashboard.${domain}/`);
});

app.use(vhost(`*.${domain}`, unusedSub));

app.listen(port, () => console.log(`Listening on port ${port}.`));
4

1 回答 1

1

我已经想通了。基本上“使用”的顺序是错误的。静态部分必须在身份验证检查之后,您必须调用“下一步”。也许这会对某人有所帮助。

subdomains.forEach(subdomain => {
    const subDir = `${subdomainDir}/${subdomain}/`;

    let subExpress = express();

    subExpress.use(async (req, res, next) => {
        let isAuthenticated = false;

        try {
            isAuthenticated = await login.isAuthenticated(req.get('authorization'))
        } catch (error) {
            console.log(error);
        }

        if (isAuthenticated || subdomain === "login") {
            next();
        } else {
            res.redirect(301, `https://login.${domain}/`);
        }
    });

    subExpress.use(express.static(__dirname + subDir));

    app.use(vhost(`${subdomain}.${domain}`, subExpress));
});
于 2019-12-21T18:37:09.557 回答