You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS如何使用passport-azure-ad将未认证用户重定向到微软登录页

基于passport-azure-ad实现微软登录重定向的操作步骤

你当前用到的oauth-bearer策略是用于接口Bearer令牌校验的场景,无法实现跳转到微软登录页的功能,需要改用passport-azure-ad提供的OIDCStrategy(OpenID Connect策略)来实现网页端登录重定向逻辑。

1. 前置配置初始化

先在Azure门户完成应用注册,获取clientID、clientSecret、tenantId,并配置和代码一致的登录回调地址,然后完成策略初始化:

const passport = require('passport');
const OIDCStrategy = require('passport-azure-ad').OIDCStrategy;

passport.use(new OIDCStrategy({
    identityMetadata: `https://login.microsoftonline.com/${你的租户ID}/v2.0/.well-known/openid-configuration`,
    clientID: 你注册的应用客户端ID,
    responseType: 'code id_token',
    responseMode: 'form_post',
    redirectUrl: 'http://localhost:3000/auth/callback', // 必须和Azure后台配置的回调地址完全一致
    allowHttpForRedirectUrl: true, // 本地开发用,生产环境请关闭
    clientSecret: 你注册的应用客户端密钥,
    scope: ['openid', 'profile', 'email']
  },
  function(iss, sub, profile, accessToken, refreshToken, done) {
    // 此处自定义用户信息校验、存储逻辑
    return done(null, profile);
  }
));

// 配合express session实现登录态持久化(需要提前配置express-session中间件)
passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(user, done) {
  done(null, user);
});

2. 编写登录重定向路由

你需要的/login路由逻辑如下,调用authenticate时指定策略为azuread-openidconnect即可自动触发微软登录页重定向:

app.get('/login', passport.authenticate('azuread-openidconnect', {
  failureRedirect: '/login-fail' // 自定义登录失败跳转地址
}), function(req, res) {
  res.redirect('/'); // 该逻辑实际不会触发,请求会直接跳转到微软登录页
});

3. 补充登录回调路由

微软登录完成后会回调你配置的redirectUrl,需要对应路由处理认证结果:

app.post('/auth/callback', passport.authenticate('azuread-openidconnect', {
  failureRedirect: '/login-fail',
  successRedirect: '/dashboard' // 认证成功后跳转到业务页面
}));

注意:使用前需要在express初始化阶段注册passport中间件:

app.use(passport.initialize());
app.use(passport.session()); // 不需要持久化登录态可以省略该行

内容的提问来源于stack exchange,提问作者Hassan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 09:06:10