【问题标题】:MSAL with Express and React: Authentication for root URL使用 Express 和 React 的 MSAL:根 URL 的身份验证
【发布时间】:2021-08-31 04:12:09
【问题描述】:

我有一个 React 前端和一个 express 后端。

目标是仅在用户通过使用 MSAL(Microsoft 身份验证库)的快速后端成功身份验证后才允许访问前端。

最初,我按照this 微软官方指南实现了身份验证流程。但是,本指南只是关于在没有真正前端的情况下使用纯 express。所以我不得不将本指南的信息与我的 React 前端结合起来。

第 1 步是在同一端口 (localhost:3000) 上运行它们,方法是将前端构建到“构建”文件夹中,并告诉 express 使用此文件夹中的静态文件。这很好用。

但现在我遇到了以下问题:我希望在访问 localhost:3000 时进行身份验证。但目前,此 URL 无需身份验证即可访问。在app.use() 之后,不会调用app.get()。只有当app.get() 使用某种扩展的URL(例如/login)调用时才有效。然后用户将通过身份验证,然后重定向到localhost:3000

请看快递代码:

//server.js
const path = require('path');

const express = require("express");
const msal = require('@azure/msal-node');

const SERVER_PORT = process.env.PORT || 3000; // use static build
const REDIRECT_URI = "http://localhost:3000"; 

// msal config
const config = {
    auth: {
        clientId: "xyz",
        authority: xyz",
        clientSecret: "xyz"
    },
    system: {
        loggerOptions: {
            loggerCallback(loglevel, message, containsPii) {
                console.log(message);
            },
            piiLoggingEnabled: false,
            logLevel: msal.LogLevel.Verbose,
        }
    }
};

// Create msal application object
const pca = new msal.ConfidentialClientApplication(config);

// Create Express App and Routes
const app = express();

// production mode: Build frontend using npm run build --> creates build folder. Use "build"-folder to serve static files with express

// use build folder
app.use(express.static(path.join(__dirname, './build')));

app.get('/', (req, res) => { // "/": app.get() is not invoked. "/login": works fine
    const authCodeUrlParameters = {
        scopes: ["user.read"],
        redirectUri: REDIRECT_URI,
    };

    // get url to sign user in and consent to scopes needed for application
    pca.getAuthCodeUrl(authCodeUrlParameters).then((response) => {
        res.redirect(response);
    }).catch((error) => console.log(JSON.stringify(error)));
});

// currently not being invoked
app.get('/redirect', (req, res) => {
    const tokenRequest = {
        code: req.query.code,
        scopes: ["user.read"],
        redirectUri: REDIRECT_URI,
    };

    pca.acquireTokenByCode(tokenRequest).then((response) => {
        console.log("\nResponse: \n:", response);
        res.sendStatus(200);
    }).catch((error) => {
        console.log(error);
        res.status(500).send(error);
    });
});


app.listen(SERVER_PORT, () => console.log(`Msal Node Auth Code Sample app listening on port ${SERVER_PORT}!`))

为什么在使用"/" 时没有调用app.get()(= 身份验证流程)? "*" 也不起作用。是否有可能实现在localhost:3000 而不是localhost:3000/login 上进行身份验证的目标?

如果不可能,我怎样才能通过输入localhost:3000来阻止用户访问前端?

我也为此搜索了 StackOverflow,但没有成功。例如,This question 对我来说并不适用,因为它使用了额外的私有路由。但我想避免额外的路线。因为我找到了很多可以做到这一点的例子,我开始怀疑这是否是唯一可能的方法。

我们将不胜感激。

【问题讨论】:

    标签: node.js express authentication msal


    【解决方案1】:

    要在用户通过 express 后端成功验证身份后允许访问前端,您可以使用 react-router-guards。

    在此处了解更多信息:https://www.npmjs.com/package/react-router-guards

    【讨论】:

      猜你喜欢
      • 2020-12-04
      • 2021-11-15
      • 2021-11-22
      • 2020-01-01
      • 2019-05-26
      • 2022-11-02
      • 1970-01-01
      • 2023-01-22
      • 1970-01-01
      相关资源
      最近更新 更多