我正在尝试将我的 NodeJs Express 应用连接到 Microsoft Graph API,以便我可以发送自动电子邮件。到目前为止,我一直在关注this guide将我的应用程序连接到 microsoft-identify-express打包,希望它能让我在我的 Azure 应用程序中验证自己的身份,并允许我访问 API。
这是我的 msIdSettings:
const msIdAuthSettings = {
appCredentials: {
clientId: "...",
tenantId: "...",
clientSecret: "..."
},
authRoutes: {
redirect: "/redirect",
unauthorized: "/unauthorized",
error: "/error"
},
protectedResources: {
graphAPI: {
endpoint: "https://graph.microsoft.com/v1.0/me",
scopes: ["user.read", "mail.send"]
},
armAPI: {
endpoint: "https://management.azure.com/tenants?api-version=2020-01-01",
scopes: ["https://management.azure.com/user_impersonation"]
}
}
}
这是我的应用程序设置:
const express = require('express');
const session = require('express-session');
const cors = require('cors');
const MsIdExpress = require('microsoft-identity-express');
const msIdAuthSettings = require('./msIdAuthSettings');
const emailRouter = require('./routes/email');
require('dotenv').config();
const server = express();
server.use(cors());
server.use(express.json());
server.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // set this to true on production
}
}));
// instantiate the wrapper
const msid = new MsIdExpress.WebAppAuthClientBuilder(msIdAuthSettings).build();
// initialize the wrapper
server.use(msid.initialize());
// setup the routers
server.use('/email', emailRouter(msid));
module.exports = server;
这是我的电子邮件路由器:
const router = require('express').Router();
const msIdAuthSettings = require('../msIdAuthSettings');
module.exports = (msid) => {
// auth routes
router.get('/signin',
msid.signIn({
postLoginRedirect: "/",
}),
);
router.get('/signout',
msid.signOut({
postLogoutRedirect: "/",
}),
);
// unauthorized
router.get('/unauthorized', (req, res) => res.redirect('/401.html'));
router.get('*', (req, res) => res.redirect('/404.html'));
return router;
}
当我点击 /signin
端点时,它成功地将我带到授权步骤并让我登录到我的 Microsoft 帐户,但登录后,它会重定向到 中配置的端点msIdAuthSettings.authRoutes.unauthorized
:
Inspect Element -> Network Tab
我查看了source code ,我认为它一定在 this step 处失败。 ,但我不知道为什么。
我真的很感激任何有关这方面的帮助或建议,因为我已经花了两天时间在这上面,我想继续我的生活!
最佳答案
404 错误表示请求的资源不可用
。
因此,请确保应用程序身份验证请求中的重定向 url/回复 url 与 azure 广告门户中的重定向 url/回复 url 匹配,即;请仔细检查您的重定向 URI 是否是有效的端点,并且具有除本地主机之外的 https
协议(protocol),并确保用户被授予权限。
#To catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
How to handle 404 error in express? Example program (techeplanet.com)
- 请确保您为客户端 key 提供了正确的值。 必须是 clientsecret 值,而不是客户端 key ID。
- 此外,请确保针对您所选择的范围授予管理员同意 在 azure 门户中具有或请与管理员检查相同
引用:
Tutorial: Sign in users in a Node.js & Express web app - Microsoft Entra | Microsoft Docs
关于node.js - microsoft-identity-express - 为什么我无法成功登录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73186833/