C# 为Microsoft Graph SDK实现自定义身份验证处理程序
我的理解是,我可能错了,使用Microsoft Graph SDK,您可以获得一个GraphClientFactory,通过使用它,您可以从Graph客户端插入或删除中间件组件 因为它们提供了一种删除和添加中间件的方法,所以我假设我们可以提供身份验证处理程序的自定义实现,因为它基本上是一个委托处理程序 我编写了这段代码,它与Microsoft Graph提供的原始代码非常相似,只是为了看看我们是否可以实际使用自定义组件/处理程序:C# 为Microsoft Graph SDK实现自定义身份验证处理程序,c#,.net,microsoft-graph-api,microsoft-graph-sdks,C#,.net,Microsoft Graph Api,Microsoft Graph Sdks,我的理解是,我可能错了,使用Microsoft Graph SDK,您可以获得一个GraphClientFactory,通过使用它,您可以从Graph客户端插入或删除中间件组件 因为它们提供了一种删除和添加中间件的方法,所以我假设我们可以提供身份验证处理程序的自定义实现,因为它基本上是一个委托处理程序 我编写了这段代码,它与Microsoft Graph提供的原始代码非常相似,只是为了看看我们是否可以实际使用自定义组件/处理程序: public class CustomAuthenticati
public class CustomAuthenticationHandler: DelegatingHandler
{
internal AuthenticationHandlerOption AuthOption { get; set; }
public IAuthenticationProvider AuthenticationProvider { get; set; }
public CustomAuthenticationHandler(IAuthenticationProvider authenticationProvider)
{
AuthenticationProvider = authenticationProvider;
AuthOption = new AuthenticationHandlerOption();
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage httpRequestMessage, CancellationToken cancellationToken)
{
var authProvider = AuthenticationProvider;
if (authProvider != null)
{
await authProvider.AuthenticateRequestAsync(httpRequestMessage);
HttpResponseMessage response = await base.SendAsync(httpRequestMessage, cancellationToken);
//do something
return response;
}
else
{
return await base.SendAsync(httpRequestMessage, cancellationToken);
}
}
}
这是我在实际发送请求时收到的错误消息:
“代码:invalidRequest\r\n消息:发送请求前需要身份验证提供程序。\r\n”
到目前为止我还不能工作。我的问题是这是否可能?Microsoft Graph SDK是打算提供此功能,还是我完全理解错了?如果可以添加自定义处理程序,那么我做错了什么?您能提供相关id和时间戳吗?您是否仍在寻找有关此问题的帮助
var handlers = new DelegatingHandler[]
{
new CustomAuthenticationHandler(
new DelegateAuthenticationProvider(async (requestMessage) =>
{
var scopes = new string[] { "https://graph.microsoft.com/.default" };
var authResult = await confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync();
requestMessage
.Headers
.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
})
),
new CompressionHandler(),
new RetryHandler(),
new RedirectHandler()
};
var client = GraphClientFactory.Create(handlers);
GraphClient = new GraphServiceClient(client);