[英]Calling Microsoft Graph APIs as authenticated user from an ASP.net Core WebApp that uses AzureAD authentication
I have a Asp.NET Core MVC 2.2 WebApp that uses Azure Active Directory to log-in users, configured like this: 我有一个使用Azure Active Directory登录用户的Asp.NET Core MVC 2.2 WebApp,配置如下:
public void ConfigureServices(IServiceCollection services){
//...
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => configuration.Bind("AzureAd", options));
//...
}
All the required info is configured in appsettings.json
(ClientID, TenantID, domain, etc.) and the login process works perfectly without issues. 所有必需的信息都在appsettings.json
配置(ClientID,TenantID,域等),并且登录过程可以完美地进行而不会出现问题。
Now, when the user calls a certain action in a certain controller, I would like to make a few calls to the Microsoft Graph API. 现在,当用户在某个控制器中调用某个动作时,我想对Microsoft Graph API进行一些调用。 As I understand, since I'm already logged in as an authenticated AzureAD user, this should not be a problem, since I should be able to set the required Delgated
permissions and then use an instance of GraphServiceClient
(from the Microsoft.Graph
library) to make the calls: 据我了解,由于我已经以经过身份验证的AzureAD用户身份登录,因此这应该不会有问题,因为我应该能够设置所需的Delgated
权限,然后使用GraphServiceClient
的实例(来自Microsoft.Graph
库)拨打电话:
[HttpGet("[action]")]
public IActionResult Test()
{
GraphServiceClient graphClient = GetGraphServiceClient(); //HOW????
//... make calls etc.
return Ok("OK");
}
The problem is that, when searching online, I got completely lost on HOW to obtain a authenticated instance of GraphServiceClient
. 问题是,当在线搜索时,我完全不知道如何获得GraphServiceClient
经过身份验证的实例。 I found several samples, but all using completely different approaches, and often requiring dozens of extra classes and support methods. 我发现了几个示例,但是所有示例都使用完全不同的方法,并且通常需要数十个额外的类和支持方法。 Is it really that complicated? 真的那么复杂吗?
So my question is, what is the best/simplest way to call the Microsoft Graph API in my scenario? 所以我的问题是,在我的方案中调用Microsoft Graph API的最佳/最简单方法是什么? To recap: 回顾一下:
Can someone provide a minimal sample? 有人可以提供最少的样品吗?
You can get the GraphServiceClient
like this: 您可以像这样获得GraphServiceClient
:
var accessToken = "";
var graphserviceClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
(requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
return Task.FromResult(0);
}));
Here is the aspnetcore sample for your reference. 这是aspnetcore示例供您参考。
Update: 更新:
That's why I've asked if there was a more straightforward way. 这就是为什么我问是否有更直接的方法。
Yes, there is. 就在这里。 You can choose the appropriate authentication provider here to create the GraphServiceClient. 您可以在此处选择适当的身份验证提供程序来创建GraphServiceClient。
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.