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

基于Nest.js(Node.js)实现Azure AD用户CRUD与认证的可行性及文档咨询

可以通过Nest.js实现Azure AD用户的CRUD与认证管理

完全可以用Nest.js(基于Node.js)对接Azure AD完成用户的认证及CRUD操作,核心是通过Microsoft Graph API与Azure AD交互,你找到的资料正是官方核心参考依据。

核心实现思路

  • 认证管理:借助Nest.js的@nestjs/passport结合Azure AD的OAuth2/OpenID Connect策略,实现用户登录、令牌验证等认证流程;
  • 用户CRUD操作:通过Microsoft Graph SDK for Node.js调用Graph API,完成用户的创建、查询、更新、删除,支持用户自助注册与管理员后台操作两种场景。

关键步骤与代码示例

1. 配置Azure AD应用

在Azure门户中注册应用,获取以下信息并配置环境变量:

  • 租户ID(Tenant ID)
  • 客户端ID(Client ID)
  • 客户端密钥(Client Secret)
  • 配置API权限(需添加User.ReadWrite.All、Directory.ReadWrite.All等权限,根据操作范围选择)

2. 安装依赖

npm install @microsoft/microsoft-graph-client @nestjs/passport passport-azure-ad @nestjs/jwt @azure/identity

3. 封装Azure AD用户操作服务

创建azure-ad.service.ts封装Graph API调用:

import { Injectable } from '@nestjs/common';
import { Client } from '@microsoft/microsoft-graph-client';
import { TokenCredentialAuthenticationProvider } from '@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials';
import { ClientSecretCredential } from '@azure/identity';

@Injectable()
export class AzureAdService {
  private graphClient: Client;

  constructor() {
    const credential = new ClientSecretCredential(
      process.env.AZURE_TENANT_ID,
      process.env.AZURE_CLIENT_ID,
      process.env.AZURE_CLIENT_SECRET,
    );
    const authProvider = new TokenCredentialAuthenticationProvider(credential, {
      scopes: ['https://graph.microsoft.com/.default'],
    });
    this.graphClient = Client.initWithMiddleware({ authProvider });
  }

  // 创建用户
  async createUser(userData: {
    accountEnabled: boolean;
    displayName: string;
    mailNickname: string;
    userPrincipalName: string;
    passwordProfile: { password: string; forceChangePasswordNextSignIn: boolean };
  }) {
    return this.graphClient.api('/users').post(userData);
  }

  // 获取单个用户
  async getUser(userId: string) {
    return this.graphClient.api(`/users/${userId}`).get();
  }

  // 更新用户信息
  async updateUser(userId: string, updateData: Partial<{ displayName: string; mailNickname: string }>) {
    return this.graphClient.api(`/users/${userId}`).patch(updateData);
  }

  // 删除用户
  async deleteUser(userId: string) {
    return this.graphClient.api(`/users/${userId}`).delete();
  }
}

4. 实现Azure AD认证策略

创建azure-ad.strategy.ts配置Passport认证策略:

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { BearerStrategy } from 'passport-azure-ad';

@Injectable()
export class AzureAdStrategy extends PassportStrategy(BearerStrategy) {
  constructor() {
    super({
      identityMetadata: `https://login.microsoftonline.com/${process.env.AZURE_TENANT_ID}/v2.0/.well-known/openid-configuration`,
      clientID: process.env.AZURE_CLIENT_ID,
      validateIssuer: true,
      issuer: `https://login.microsoftonline.com/${process.env.AZURE_TENANT_ID}/v2.0`,
      audience: process.env.AZURE_CLIENT_ID,
      loggingLevel: 'info',
      passReqToCallback: false,
    });
  }

  async validate(payload: any) {
    return { userId: payload.oid, username: payload.name, email: payload.email };
  }
}

在auth.module.ts中导入并配置模块:

import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { AzureAdStrategy } from './azure-ad.strategy';

@Module({
  imports: [PassportModule],
  providers: [AzureAdStrategy],
  exports: [PassportModule],
})
export class AuthModule {}

官方参考核心内容

你找到的两份文档是核心参考:

  • Graph API总览:涵盖API调用的基础规范、认证方式、请求响应格式等核心信息;
  • 用户资源文档:详细定义了用户对象的结构、CRUD操作的参数要求、返回值说明等细节。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:02:50