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

升级MsGraph至最新版本遇阻:.NET8下MVC应用认证适配问题

问题:.NET8升级后MsGraph认证代码适配问题

我有一个使用MsGraph连接Active Directory的MVC应用,升级至.NET8并更新NuGet包后无法正常运行。目前只能注释掉发送邮件、上传图片相关代码,但这并非理想解决方案。

旧版本MsGraph中的认证代码如下:

public GraphServiceClient GetAuthenticatedGraphClient(ClaimsIdentity userIdentity) =>
new GraphServiceClient(new DelegateAuthenticationProvider(
async requestMessage =>
{
// Get user's id for token cache.  These links hard coded in sample application
var identifier = userIdentity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")?.Value + "." + userIdentity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid")?.Value;
//var identifier = userIdentity.FindFirst(Microsoft.AspNetCore.Identity.UserLoginInfo)?.Value + "." + userIdentity.FindFirst(ClaimTypes.NameIdentifier)?.Value;

              // Passing tenant ID to the sample auth provider to use as a cache key
              var accessToken = await _authProvider.GetUserAccessTokenAsync(identifier);



              // Append the access token to the request
              requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);



              // This header identifies the sample in the Microsoft Graph service. If extracting this code for your project please remove.
              //requestMessage.Headers.Add("SampleID", "aspnetcore-connect-sample");
              requestMessage.Headers.Add("MsGraphTest", "MsGraphTest");
          }));
}

适配MsGraph v5的认证代码替换方案

根据官方升级指引,原DelegateAuthenticationProvider需替换为基于Kiota抽象的IAccessTokenProvider实现,具体步骤如下:

1. 实现自定义IAccessTokenProvider

创建自定义Token提供类,复用原有token获取逻辑:

using Microsoft.Kiota.Abstractions.Authentication;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Claims;

public class CustomGraphTokenProvider : IAccessTokenProvider
{
    private readonly IAuthProvider _authProvider;
    private readonly ClaimsIdentity _userIdentity;

    public CustomGraphTokenProvider(IAuthProvider authProvider, ClaimsIdentity userIdentity)
    {
        _authProvider = authProvider;
        _userIdentity = userIdentity;
    }

    public async Task<string> GetAuthorizationTokenAsync(Uri uri, Dictionary<string, object> additionalAuthenticationContext = default, CancellationToken cancellationToken = default)
    {
        // 沿用原有缓存key生成逻辑
        var identifier = _userIdentity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")?.Value + "." + 
                         _userIdentity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid")?.Value;
        
        // 调用原有方法获取访问令牌
        return await _authProvider.GetUserAccessTokenAsync(identifier);
    }

    // 配置允许的Graph服务主机,默认允许graph.microsoft.com
    public AllowedHostsValidator AllowedHostsValidator { get; } = new AllowedHostsValidator(new[] { "graph.microsoft.com" });
}

2. 重构GetAuthenticatedGraphClient方法

替换原方法,使用新的认证体系初始化GraphServiceClient:

using Microsoft.Graph;
using Microsoft.Kiota.Abstractions.Authentication;
using System.Security.Claims;

public GraphServiceClient GetAuthenticatedGraphClient(ClaimsIdentity userIdentity)
{
    // 实例化自定义token提供器
    var tokenProvider = new CustomGraphTokenProvider(_authProvider, userIdentity);
    // 创建Bearer认证提供器
    var authProvider = new BaseBearerTokenAuthenticationProvider(tokenProvider);
    
    // 初始化GraphServiceClient
    var graphClient = new GraphServiceClient(authProvider);
    
    // 添加全局自定义请求头(对应原代码中的MsGraphTest)
    graphClient.HttpClient.DefaultRequestHeaders.Add("MsGraphTest", "MsGraphTest");
    
    return graphClient;
}

3. 关键注意事项

  • 确保已安装必要NuGet包:Microsoft.Graph(v5+)、Microsoft.Kiota.Abstractions
  • 原DelegateAuthenticationProvider已被弃用,必须使用基于Kiota的认证方式
  • 若需自定义HttpClient配置,可将自定义HttpClient实例传入GraphServiceClient构造函数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 18:43:24