C# 在.net完整框架中构造具有委托访问权限的Microsoft Graph
我正在尝试在.NET4.5框架中成功构建具有委托权限的图形客户端。我已经尝试了我在互联网上找到的所有方法,但都不起作用。 我已在azure ad中注册了我的应用程序,并具有委托权限,但构建它时没有任何运气。以下是我尝试过的最新版本:C# 在.net完整框架中构造具有委托访问权限的Microsoft Graph,c#,.net,graph,delegates,C#,.net,Graph,Delegates,我正在尝试在.NET4.5框架中成功构建具有委托权限的图形客户端。我已经尝试了我在互联网上找到的所有方法,但都不起作用。 我已在azure ad中注册了我的应用程序,并具有委托权限,但构建它时没有任何运气。以下是我尝试过的最新版本: //private string[] _scopes = new string[] { "https://graph.microsoft.com/.default" }; //private string[] _scopes =
//private string[] _scopes = new string[] { "https://graph.microsoft.com/.default" };
//private string[] _scopes = new string[] { "https://graph.microsoft.com/User.ReadWrite.All" };
//private readonly string[] _scopes = new string[] { "User.Read" };
private readonly string[] _scopes = new string[] { "User.Read.All" };
public GraphServiceClient GetAuthenticatedGraphClient(ClaimsIdentity userIdentity) =>
new GraphServiceClient(new DelegateAuthenticationProvider(
async requestMessage =>
{
// Passing tenant ID to the sample auth provider to use as a cache key
var accessToken = await _authProvider.GetUserAccessTokenAsync();
// Append the access token to the request
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}));
}
public async Task<string> GetUserAccessTokenAsync()
{
try
{
var result = await _app.AcquireTokenForClient(_scopes)
.ExecuteAsync();
return result.AccessToken;
}
// Unable to retrieve the access token silently.
catch (Exception ex)
{
throw new ServiceException(new Error
{
Code = GraphErrorCode.AuthenticationFailure.ToString(),
Message = "Caller needs to authenticate. Unable to retrieve the access token silently."
});
}
}
//私有字符串[]\u作用域=新字符串[]{”https://graph.microsoft.com/.default" };
//私有字符串[]_scopes=新字符串[]{”https://graph.microsoft.com/User.ReadWrite.All" };
//私有只读字符串[]_scopes=新字符串[]{“User.Read”};
私有只读字符串[]_scopes=新字符串[]{“User.Read.All”};
公共GraphServiceClient GetAuthenticatedGraphClient(ClaimsEntity用户标识)=>
新GraphServiceClient(新的DelegateAuthenticationProvider(
异步请求消息=>
{
//将租户ID传递给示例身份验证提供程序以用作缓存密钥
var accessToken=wait_authProvider.GetUserAccessTokenAsync();
//将访问令牌附加到请求
requestMessage.Headers.Authorization=新的AuthenticationHeaderValue(“承载者”,accessToken);
}));
}
公共异步任务GetUserAccessTokenAsync()
{
尝试
{
var result=await\u app.AcquireTokenForClient(\u作用域)
.ExecuteAsync();
返回result.AccessToken;
}
//无法以静默方式检索访问令牌。
捕获(例外情况除外)
{
抛出新ServiceException(新错误
{
Code=GraphErrorCode.AuthenticationFailure.ToString(),
Message=“呼叫方需要进行身份验证。无法以静默方式检索访问令牌。”
});
}
}
我是否可以获得完整的代码片段来正确构造Microsoft graph客户端以获得完整框架web应用程序的代理权限?我最终找到了一个有效的示例,该示例具有正确的Microsoft graph代理权限设置: