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

如何在Azure AD B2C认证的Blazor WASM中调用Graph API?

实现方案:通过后端中转调用MS Graph API(Azure AD B2C场景)

一、后端配置与准备

  • 在Azure AD B2C中注册后端应用
    • 生成并保存客户端密钥(Client Secret)
    • 为后端应用添加MS Graph API的应用权限(如User.Read.All,根据业务需求选择),并完成管理员权限授予
  • 后端项目(以ASP.NET Core为例)配置
    • 安装NuGet包:Microsoft.Identity.Web、Microsoft.Identity.Web.MicrosoftGraph
    • 在appsettings.json中添加配置项:
      "AzureAdB2C": {
        "Instance": "https://你的B2C租户域名.b2clogin.com/",
        "Domain": "你的B2C租户域名.onmicrosoft.com",
        "TenantId": "你的租户ID",
        "ClientId": "后端应用的Client ID",
        "ClientSecret": "后端应用的Client Secret",
        "Scopes": "https://graph.microsoft.com/.default"
      },
      "MicrosoftGraph": {
        "BaseUrl": "https://graph.microsoft.com/v1.0",
        "Scopes": "https://graph.microsoft.com/.default"
      }
      

二、后端控制器实现

创建受保护的API控制器,封装Graph API调用逻辑:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Graph;

[ApiController]
[Route("api/[controller]")]
[Authorize] // 仅允许已认证的Blazor WASM客户端访问
public class GraphProxyController : ControllerBase
{
    private readonly GraphServiceClient _graphServiceClient;

    public GraphProxyController(GraphServiceClient graphServiceClient)
    {
        _graphServiceClient = graphServiceClient;
    }

    // 示例:获取当前登录用户的信息
    [HttpGet("me")]
    public async Task<IActionResult> GetCurrentUser()
    {
        var userId = User.FindFirst("sub")?.Value;
        if (string.IsNullOrEmpty(userId))
        {
            return BadRequest("无法获取用户ID");
        }

        try
        {
            var user = await _graphServiceClient.Users[userId]
                .Request()
                .Select(u => new { u.DisplayName, u.Email, u.Id })
                .GetAsync();

            return Ok(user);
        }
        catch (ServiceException ex)
        {
            return StatusCode((int)ex.StatusCode, ex.Message);
        }
    }

    // 示例:获取所有用户列表(需对应Graph API权限)
    [HttpGet("users")]
    public async Task<IActionResult> GetAllUsers()
    {
        try
        {
            var users = await _graphServiceClient.Users
                .Request()
                .Select(u => new { u.DisplayName, u.Email })
                .GetAsync();

            return Ok(users);
        }
        catch (ServiceException ex)
        {
            return StatusCode((int)ex.StatusCode, ex.Message);
        }
    }
}

三、后端服务注册

在Program.cs中完成身份验证与Graph服务的注册:

var builder = WebApplication.CreateBuilder(args);

// 注册Azure AD B2C身份验证
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAdB2C"));

// 注册MS Graph服务
builder.Services.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"));

builder.Services.AddControllers();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

四、Blazor WASM客户端调用

通过HttpClient调用后端代理接口:

@inject HttpClient Http
@code {
    private UserInfo? CurrentUser { get; set; }

    protected override async Task OnInitializedAsync()
    {
        try
        {
            CurrentUser = await Http.GetFromJsonAsync<UserInfo>("api/graphproxy/me");
        }
        catch (Exception ex)
        {
            // 自定义错误处理逻辑
        }
    }

    public class UserInfo
    {
        public string? DisplayName { get; set; }
        public string? Email { get; set; }
        public string? Id { get; set; }
    }
}

关键说明

  • 后端采用应用权限调用Graph API,规避了Azure AD B2C不支持前端直接调用Graph的限制
  • 控制器的[Authorize]特性确保接口仅对已认证的客户端开放,保障数据安全
  • 可根据业务需求扩展更多Graph API代理方法,比如用户组管理、邮件操作等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 17:07:37