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

如何使用Node.js连接Azure AD并查找用户

用Node.js查询Azure AD用户的正确姿势

首先得澄清一个关键点:普通的Azure AD并不支持LDAP协议访问,如果你用的是纯Azure AD(没有部署Azure AD Domain Services),那node-activedirectory这个库是不适用的,应该用Microsoft Graph API来实现用户查询。如果是Azure AD Domain Services(AAD DS),那可以通过LDAP连接,下面分两种情况来说:

情况1:使用Azure AD Domain Services(支持LDAP)

你的现有代码有几个需要修正的地方:

  • Azure AD DS的LDAP连接必须用SSL,所以URL应该是ldaps://<你的AAD DS域名>:636,而不是ldap://
  • 开发环境下可能需要临时禁用证书验证(生产环境一定要配置正确的证书)
  • 完整的示例代码如下:
const ActiveDirectory = require('activedirectory');

// 修正后的配置参数
const config = {
  url: 'ldaps://myhotmail.onmicrosoft.com:636',
  baseDN: 'dc=myhotmail,dc=onmicrosoft,dc=com',
  username: 'roledene@myhotmail.onmicrosoft.com',
  password: 'myPassword',
  // 开发环境临时禁用证书检查,生产环境请移除该配置并配置合法证书
  tlsOptions: { rejectUnauthorized: false }
};

const ad = new ActiveDirectory(config);

// 测试连接并查询用户
ad.authenticate(config.username, config.password, (err, auth) => {
  if (err) {
    console.error('连接失败:', err);
    return;
  }

  if (auth) {
    console.log('连接成功!');
    // 按用户主体名称查找指定用户
    const query = `(userPrincipalName=roledene@myhotmail.onmicrosoft.com)`;
    ad.findUsers(query, (err, users) => {
      if (err) {
        console.error('查询用户失败:', err);
        return;
      }
      console.log('找到的用户:', users);
    });
  } else {
    console.log('用户名或密码错误');
  }
});

情况2:使用纯Azure AD(推荐用Microsoft Graph API)

因为纯Azure AD不提供LDAP接口,官方推荐用Microsoft Graph JavaScript SDK来查询用户,步骤如下:

  1. 先安装依赖包:
npm install @microsoft/microsoft-graph-client @azure/msal-node
  1. 编写查询代码(需要先在Azure AD门户注册应用,获取tenantId、clientId、clientSecret三个参数):
const { Client } = require('@microsoft/microsoft-graph-client');
const { ClientCredentialAuthenticationProvider } = require('@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials');
const { ClientSecretCredential } = require('@azure/msal-node');

// 替换为你从Azure AD注册应用获取的参数
const credentials = new ClientSecretCredential(
  '你的租户ID',
  '你的客户端ID',
  '你的客户端密钥'
);

const authProvider = new ClientCredentialAuthenticationProvider(credentials, {
  scopes: ['https://graph.microsoft.com/.default']
});

const client = Client.initWithMiddleware({ authProvider });

// 按邮箱查找用户的异步函数
async function findUserByEmail(email) {
  try {
    const user = await client.api(`/users/${email}`).get();
    console.log('找到的用户:', user);
    return user;
  } catch (err) {
    console.error('查询用户失败:', err);
  }
}

// 调用查询函数
findUserByEmail('roledene@myhotmail.onmicrosoft.com');

额外提醒

  • 纯Azure AD场景下,优先用Microsoft Graph API,这是官方支持的标准方式,功能更全面也更稳定
  • 使用Azure AD Domain Services时,要确保你的账号有足够的LDAP访问权限
  • 生产环境绝对不能禁用证书验证,一定要配置合法的SSL证书保障连接安全

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:55:49