admin管理员组文章数量:1549363
博客地址:http://blog.csdn/FoxDave
本篇的跨度照前一篇有些大,我们将会构建一个.NET Core项目去向Microsoft Graph发起请求。
如果有人对Visual Studio或Visual Studio Code不熟悉也不用担心。我们这个示例项目的目标是构建一个基础的.NET Core命令行应用程序用于以最小的步骤去认证和调用Microsoft Graph。
先决条件
为了完成本示例,我们需要:
- 在开发机器上安装Visual Studio Code 或Visual Studio。如果使用VS Code那么再安装一个C#扩展。
- .NET Core SDK。
- 一个Microsoft账号
如果没有Microsoft账号,可以:
- 注册一个个人Microsoft账号。
- 注册Office 365开发者项目去获得一个免费的Office 365订阅账号。
本篇我会以Visual Studio为大家做演示。
第一步:创建一个.NET Core命令行应用程序
打开Visual Studio 2017,创建一个.NET Core命令行程序。
然后向项目中添加如下NuGet包:
- Microsoft.Identity.Client
- Microsoft.Graph
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.FileExtensions
- Microsoft.Extensions.Configuration.Json
第二步:通过Azure AD门户的应用程序注册来注册web应用程序
在前面的文章中我们已经阐述过如何注册应用程序,这里不再赘述只进行简要说明。
我们注册一个叫做 core graph test的应用,Redirect URI使用Web类型,填入https://localhost:8080。在创建完后的概览页面,将Application (client) ID和Directory (tenant) ID拷贝下来留存,之后需要。
然后新建一个client secret,仍然强调这个密钥创建完之后一定要拷贝出来,只能可见一次,如果遗失只能重新创建。
点击API permissions,添加Application permissions -> User.Read.All,然后对添加的权限进行Grant admin consent操作。
第三步:扩展应用程序以支持Azure AD认证
创建配置文件
在之前创建的.NET Core项目中,新建一个名为appsettings的JSON文件,用如下内容覆盖JSON文件:
{
"applicationId": "YOUR_APP_ID_HERE",
"applicationSecret": "YOUR_APP_SECRET_HERE",
"tenantId": "YOUR_TENANT_ID_HERE",
"redirectUri": "YOUR_REDIRECT_URI_HERE"
}
将上面每个字段的值替换为我们真实的值。添加完成后右键该文件,选择属性,确认一下是否设置了复制到输出目录。
创建帮助类
新建一个名为Helpers的文件夹,在文件夹内创建名为AuthHandler的CS类文件,并覆盖为如下内容:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Graph;
using Microsoft.Extensions.Configuration;
using System.Linq;
using System.Threading;
namespace ConsoleGraphTest
{
// This class allows an implementation of IAuthenticationProvider to be inserted into the DelegatingHandler
// pipeline of an HttpClient instance. In future versions of GraphSDK, many cross-cutting concernts will
// be implemented as DelegatingHandlers. This AuthHandler will come in the box.
public class AuthHandler : DelegatingHandler
{
private IAuthenticationProvider _authenticationProvider;
public AuthHandler(IAuthenticationProvider authenticationProvider, HttpMessageHandler innerHandler)
{
InnerHandler = innerHandler;
_authenticationProvider = authenticationProvider;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
await _authenticationProvider.AuthenticateRequestAsync(request);
return await base.SendAsync(request, cancellationToken);
}
}
}
同样,在Helpers文件夹内创建一个名为MsalAuthenticationProvider的CS类文件,并覆盖为如下内容:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Graph;
using Microsoft.Extensions.Configuration;
using System.Linq;
namespace ConsoleGraphTest
{
// This class encapsulates the details of getting a token from MSAL and exposes it via the
// IAuthenticationProvider interface so that GraphServiceClient or AuthHandler can use it.
// A significantly enhanced version of this class will in the future be available from
// the GraphSDK team. It will supports all the types of Client Application as defined by MSAL.
public class MsalAuthenticationProvider : IAuthenticationProvider
{
private ConfidentialClientApplication _clientApplication;
private string[] _scopes;
public MsalAuthenticationProvider(ConfidentialClientApplication clientApplication, string[] scopes)
{
_clientApplication = clientApplication;
_scopes = scopes;
}
/// <summary>
/// Update HttpRequestMessage with credentials
/// </summary>
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
{
var token = await GetTokenAsync();
request.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}
/// <summary>
/// Acquire Token
/// </summary>
public async Task<string> GetTokenAsync()
{
AuthenticationResult authResult = null;
authResult = await _clientApplication.AcquireTokenForClientAsync(_scopes);
return authResult.AccessToken;
}
}
}
第四步:将应用跟Microsoft Graph集成
在这个步骤中,我们将使用Microsoft Graph Client Library for .NET去调用Microsoft Graph。
从租户获取用户信息
打开Program.cs文件,使用如下using引用。
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Graph;
using Microsoft.Extensions.Configuration;
接下来在Program类中添加静态引用GraphServiceClient和HttpClient。这两个变量用来初始化调用Microsoft Graph的客户端。
private static GraphServiceClient _graphServiceClient;
private static HttpClient _httpClient;
在Program类中添加新的方法LoadAppSettings,定义如下。该方法获取配置文件中的属性值。
private static IConfigurationRoot LoadAppSettings()
{
try
{
var config = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false, true)
.Build();
// Validate required settings
if (string.IsNullOrEmpty(config["applicationId"]) ||
string.IsNullOrEmpty(config["applicationSecret"]) ||
string.IsNullOrEmpty(config["redirectUri"]) ||
string.IsNullOrEmpty(config["tenantId"]))
{
return null;
}
return config;
}
catch (System.IO.FileNotFoundException)
{
return null;
}
}
再添加一个新方法CreateAuthorizationProvider用来初始化调用Microsoft Graph的客户端。该方法使用类型为ConfidentialClientApplication的对象来使用配置数据。
private static IAuthenticationProvider CreateAuthorizationProvider(IConfigurationRoot config)
{
var clientId = config["applicationId"];
var clientSecret = config["applicationSecret"];
var redirectUri = config["redirectUri"];
var authority = $"https://login.microsoftonline/{config["tenantId"]}/v2.0";
List<string> scopes = new List<string>();
scopes.Add("https://graph.microsoft/.default");
var cca = new ConfidentialClientApplication(clientId, authority, redirectUri, new ClientCredential(clientSecret), null, null);
return new MsalAuthenticationProvider(cca, scopes.ToArray());
}
添加一个名为GetAuthenticatedGraphClient的方法,定义如下。该方法用于创建GraphServiceClient的实例,使用前面方法中返回的配置。
private static GraphServiceClient GetAuthenticatedGraphClient(IConfigurationRoot config)
{
var authenticationProvider = CreateAuthorizationProvider(config);
_graphServiceClient = new GraphServiceClient(authenticationProvider);
return _graphServiceClient;
}
添加一个名为GetAuthenticatedHTTPClient的方法,定义如下。该方法创建一个HTTPClient的实例。
private static HttpClient GetAuthenticatedHTTPClient(IConfigurationRoot config)
{
var authenticationProvider = CreateAuthorizationProvider(config);
_httpClient = new HttpClient(new AuthHandler(authenticationProvider, new HttpClientHandler()));
return _httpClient;
}
好,接下来在Main方法中添加如下代码去加载配置设置:
var config = LoadAppSettings();
if (null == config)
{
Console.WriteLine("Missing or invalid appsettings.json file. Please see README.md for configuration instructions.");
return;
}
继续在Main方法中添加如下代码,获得一个认证的GraphServiceClient实例并发送请求到"/Users"终结点去获取用户集合信息的第一个用户。
//Query using Graph SDK (preferred when possible)
GraphServiceClient graphClient = GetAuthenticatedGraphClient(config);
List<QueryOption> options = new List<QueryOption>
{
new QueryOption("$top", "1")
};
var graphResult = graphClient.Users.Request(options).GetAsync().Result;
Console.WriteLine("Graph SDK Result");
Console.WriteLine(graphResult[0].DisplayName);
最后,添加如下代码,获得一个认证的HttpClient实例并发送请求到"/Users"终结点去获取用户集合信息的第一个用户。
//Direct query using HTTPClient (for beta endpoint calls or not available in Graph SDK)
HttpClient httpClient = GetAuthenticatedHTTPClient(config);
Uri Uri = new Uri("https://graph.microsoft/v1.0/users?$top=1");
var httpResult = httpClient.GetStringAsync(Uri).Result;
Console.WriteLine("HTTP Result");
Console.WriteLine(httpResult);
以上是调用Microsoft Graph的两种方式,这样我们的测试项目就编写完了,接下来就可以编译然后运行了。
用哪种方式取决于我们在实际开发中的情况。个人推荐使用SDK,更加清晰。示例代码可以戳这里下载。
本文标签: 用户信息应用程序officeGraphMicrosoft
版权声明:本文标题:Microsoft Graph for Office 365 - 在.NET Core应用程序中调用Microsoft Graph获取Office 365用户信息 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1727229621a1103533.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论