ASP.NET Core 6 Web API集成Azure AD获取用户角色及用户列表实现求助
解决方案
一、从Azure Active Directory获取用户角色/声明
1. 配置Azure AD认证
在Program.cs中添加Azure AD认证与授权配置,让API能验证并解析AAD颁发的令牌:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd")); builder.Services.AddAuthorization(options => { // 可自定义角色授权策略,按需调整 options.AddPolicy("AdminAccess", policy => policy.RequireRole("Admin")); });
在appsettings.json中补充Azure AD配置项:
"AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "your-domain.onmicrosoft.com", "TenantId": "你的租户ID", "ClientId": "你的API客户端ID", "Audience": "api://你的API客户端ID" }
2. 在UserLogIn端点提取角色/声明
修改UserLogIn接口,从当前请求上下文的User对象中获取AAD用户的声明和角色:
[HttpPost("UserLogIn")] [Authorize] public IActionResult UserLogIn([FromBody] UserDTO userDto) { // 提取用户角色(AAD默认角色声明类型为ClaimTypes.Role) var userRoles = User.Claims .Where(c => c.Type == ClaimTypes.Role) .Select(c => c.Value) .ToList(); // 提取显示名称等其他声明 var displayName = User.FindFirst(ClaimTypes.Name)?.Value; // 填充UserDTO对应字段 userDto.Roles = userRoles; userDto.DisplayName = displayName; // 后续登录业务逻辑(如验证账号密码、返回令牌等) return Ok(userDto); }
二、实现AzureActiveDirectoryRepository.GetUsers()
1. 引入Microsoft Graph SDK依赖
安装必要的NuGet包,用于调用Azure AD的Graph API获取用户数据:
Install-Package Microsoft.Graph Install-Package Microsoft.Identity.Client
2. 编写Repository实现类
创建AzureActiveDirectoryRepository,通过Graph API查询AAD用户列表并转换为UserDTO:
public class AzureActiveDirectoryRepository : IAzureActiveDirectoryRepository { private readonly GraphServiceClient _graphClient; public AzureActiveDirectoryRepository(IConfiguration config) { // 使用客户端凭据模式获取Graph API访问权限 var clientId = config["AzureAd:ClientId"]; var tenantId = config["AzureAd:TenantId"]; var clientSecret = config["AzureAd:ClientSecret"]; var confidentialClient = ConfidentialClientApplicationBuilder .Create(clientId) .WithTenantId(tenantId) .WithClientSecret(clientSecret) .Build(); var authProvider = new ClientCredentialProvider(confidentialClient); _graphClient = new GraphServiceClient(authProvider); } public async Task<List<UserDTO>> GetUsers() { try { // 调用Graph API获取用户,按需选择返回字段 var aadUsers = await _graphClient.Users .Request() .Select(u => new { u.Id, u.UserPrincipalName, u.DisplayName, u.MemberOf }) .GetAsync(); // 转换为自定义UserDTO集合 return aadUsers.Select(u => new UserDTO { Id = u.Id, Username = u.UserPrincipalName, DisplayName = u.DisplayName, Roles = u.MemberOf.OfType<DirectoryRole>() .Select(r => r.DisplayName) .ToList() }).ToList(); } catch (ServiceException ex) { // 异常处理(如日志记录) throw new Exception("获取AAD用户列表失败", ex); } } }
3. 注册Repository到依赖注入容器
在Program.cs中添加:
builder.Services.AddScoped<IAzureActiveDirectoryRepository, AzureActiveDirectoryRepository>();
4. 在UserController中调用实现
修改GetUsers方法完成业务逻辑:
[HttpGet] [Authorize(Policy = "AdminAccess")] public async Task<IActionResult> GetUsers() { var users = await _azureActiveDirectoryRepository.GetUsers(); return Ok(users); }
三、Swagger适配AAD认证(调试用)
为了在Swagger UI中直接测试带AAD令牌的请求,添加Swagger OAuth配置:
builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "你的API名称", Version = "v1" }); var securityScheme = new OpenApiSecurityScheme { Name = "Azure AD Bearer", Type = SecuritySchemeType.OAuth2, Flows = new OpenApiOAuthFlows { Implicit = new OpenApiOAuthFlow { AuthorizationUrl = new Uri($"https://login.microsoftonline.com/{builder.Configuration["AzureAd:TenantId"]}/oauth2/v2.0/authorize"), Scopes = new Dictionary<string, string> { { builder.Configuration["AzureAd:Audience"], "API访问权限" } } } }, In = ParameterLocation.Header }; c.AddSecurityDefinition("oauth2", securityScheme); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { securityScheme, new[] { builder.Configuration["AzureAd:Audience"] } } }); });
在中间件配置中启用Swagger UI的OAuth支持:
app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "你的API V1"); c.OAuthClientId(builder.Configuration["AzureAd:ClientId"]); c.OAuthUseBasicAuthenticationWithAccessCodeGrant(); });
内容的提问来源于stack exchange,提问作者Macdroopy
相关产品推荐
相关产品推荐

