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

如何在Microsoft Graph v5 SDK中通过AccessToken初始化GraphServiceClient

解决Microsoft Graph v5 SDK中替换DelegateAuthenticationProvider初始化GraphServiceClient的问题

在Microsoft Graph v5 SDK中,DelegateAuthenticationProvider已被移除,替代方案是实现IAuthenticationProvider接口,或使用BaseBearerTokenAuthenticationProvider简化开发。以下是适配.NET 8 ASP.NET Core Web API的完整实现:

步骤1:自定义身份验证提供器

直接继承BaseBearerTokenAuthenticationProvider,它已封装基础逻辑,只需传入请求中的accessToken即可:

using Microsoft.Graph;
using Microsoft.Graph.Authentication;

public class CustomBearerTokenAuthProvider : BaseBearerTokenAuthenticationProvider
{
    private readonly string _accessToken;

    public CustomBearerTokenAuthProvider(string accessToken)
    {
        _accessToken = accessToken;
    }

    protected override Task<string> GetAuthorizationTokenAsync(
        HttpRequestMessage requestMessage,
        CancellationToken cancellationToken)
    {
        return Task.FromResult(_accessToken);
    }
}

步骤2:初始化GraphServiceClient并调用邀请接口

注意v5的API调用语法已调整,不再需要.Request()方法,直接使用fluent API调用:

var authorizationHeader = HttpContext.Request.Headers["Authorization"].FirstOrDefault();
if (string.IsNullOrEmpty(authorizationHeader) || !authorizationHeader.StartsWith("Bearer "))
{
    return BadRequest("无效的授权头");
}

var accessToken = authorizationHeader.Substring("Bearer ".Length);

// 使用自定义身份验证提供器初始化GraphServiceClient
var authProvider = new CustomBearerTokenAuthProvider(accessToken);
var _graphServiceClient = new GraphServiceClient(authProvider);

var invitation = new Invitation
{
    InvitedUserEmailAddress = userEmail,
    SendInvitationMessage = true,
    InviteRedirectUrl = "https://loremipsum.app",
    InvitedUserType = "guest" // 默认值为guest,可选member
};

// v5中直接调用PostAsync提交请求
var invite = await _graphServiceClient.Invitations.PostAsync(invitation);

return Ok(invite);

关键变化说明

  • 身份验证提供器替换:DelegateAuthenticationProvider被移除,改用实现IAuthenticationProvider或继承BaseBearerTokenAuthenticationProvider
  • API调用语法:v5简化了请求构建逻辑,不再需要.Request()方法,直接对实体调用对应HTTP方法(如PostAsync)
  • 错误处理增强:建议添加对Authorization头的有效性检查,避免空引用或格式错误导致的异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 12:42:41