[ Office 365 开发系列 ] Graph Service

前言

本文完全原创,转载请说明出处,希望对大家有用。

通过[ Office 365 开发系列 ] 开发模式分析[ Office 365 开发系列 ] 身份认证两篇内容的了解,我们可以开始使用Office 365提供的各项接口开发应用了,接下来会对其提供的主要接口一一分析并通过示例代码为大家讲解接口功能。

阅读目录

  1. Graph API介绍
  2. Graph API功能
  3. 示例分析

正文

Graph API介绍

最近Office 365发布了一项新的功能Delve,此项功能为用户提供了基于人员信息及搜索的发现,有点拗口,其实就是使用Graph API提供的一些列接口,如当前所处的组织、正在处理的文档以及与我相关的事件等等内容,让用户更快的发现与自己相关的内容。Office 365提供这样一个API集合有什么用呢,我们直接使用邮件、文件、AAD的接口也一样可以实现这些内容,事实上我们的确可以这么做,而Graph API是对这些更下层的API进行了封装,让我们不需要再深入了解每一项内容如何存储、如何获取,只需要关注业务本身的需求。下图是Graph API官方的结构图,我借用一下:

从上图所示的内容,我们可以发现Graph API是Office 365作为统一接口为我们提供服务访问的(主页中说:One endpoint to rule them all),我们可以不用了解Users信息是存放在哪里,Graph会帮你找到,我们可以不用了解如何从Outlook中获取邮件,Graph提供现成接口。这么一看,果然功能强大,不过值得注意的是,Graph API接口不是全能的,目前来说还是有一些限制,如对SharePoint Online的操作只局限于个人OneDrive站点。目前最新的版本的1.0,未来Graph API应该会增加更多功能。


Graph API功能

在我们使用者API前,先对API使用方法及提供的内容做一个简要的介绍。

在上一节[ Office 365 开发系列 ] 身份认证中我们讲解了如何获取资源Token,本节我们具体到使用Graph API,值得注意的是使用Graph API所用的终结点有国外版和中国版(21v运营)的区别,具体区别如下:

终结点

国际版Office 365

21Vianet Office 365

Azure AD终结点

https://login.microsoftonline.com

https://login.chinacloudapi.cn

Graph资源终结点

https://graph.microsoft.com

https://microsoftgraph.chinacloudapi.cn

Graph API是以Rest服务的方式提供,我们可以使用两种方式调用API,一种是使用JS AJAX方式调用API接口并将token包含在Authorization头中,另外一种是通过微软提供的Graph服务类来获取和解析数据。具体的调用方法我们在下面的Graph API示例分析中来分析,先来了解Graph目前能为我们提供什么。

目前Graph有两个版本(1.0/beta),区别在于我们调用时注意资源地址,API结构为

 https://graph.microsoft.com/{version}/{resource}?[odata_query_parameters]

对于Graph所提供的资源内容,请参阅官方文档


Graph API应用示例

为了更好的了解如何调用Graph API,我们以获取用户邮件为例,分别以AJAX和调用Graph服务类方式实现。

一、 使用Ajax调用Graph API

调用由一个html+js实现,如下所示:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Graph API Demo</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
</head>
<body role="document">
    <table class="table table-striped table-bordered table-condensed table-hover">
        <thead>
            <tr>
                <th>接收时间</th>
                <th>邮件主题</th>
            </tr>
        </thead>
        <tbody class="data-container">
            <tr>
                <td class="view-data-type"></td>
                <td class="view-data-name"></td>
            </tr>
        </tbody>
    </table>
  
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/adal.js"></script>
    <script src="App/Scripts/demo.js"></script>
</body>
</html>
(function () {
    var baseEndpoint = 'https://graph.microsoft.com';
    window.config = {
        tenant:  'bluepoint360.onmicrosoft.com',
        clientId: '08d87e99-f2dd-4b4d-b402-bcf7a5ea43ca',
        postLogoutRedirectUri: window.location.origin,
        cacheLocation: 'localStorage', // enable this for IE, as sessionStorage does not work for localhost.
    };
    var authContext = new AuthenticationContext(config);
    var $dataContainer = $(".data-container");
    authContext.acquireToken(baseEndpoint, function (error, token) {
        if (error || !token) {
            console.log('ADAL error occurred: ' + error);
            return;
        }

        $.ajax({
            type: "GET",
            url: baseEndpoint + "/v1.0/me/messages",
            headers: {
                'Authorization': 'Bearer ' + token,
            }
        }).done(function (response) {
            var $template = $(".data-container");
            var output = '';
            response.value.forEach(function (item) {
                var $entry = $template;
                $entry.find(".view-data-type").html(item.receivedDateTime);
                $entry.find(".view-data-name").html(item.subject);
                output += $entry.html();
            });
            $dataContainer.html(output);
        });
    });
}());
demo.js

OK,只要这两段代码就可以了,首先要运行起来,如果不知道如何注册应用到AAD,请参考[ Office 365 开发系列 ] 身份认证

上述代码的逻辑是通过调用graph api中的messages资源,获取用户邮件信息。

二、 使用Graph服务类调用

如果我们使用后台服务的方式为用户提供服务,则需要使用HttpWebRequest来发起rest请求,如果每个都由自己处理当然是可以,不过微软已经为我们提供了调用封装,那还是省点时间去做业务逻辑吧。

以MVC为例,我们为用户提供一个获取个人邮件的方法,示例代码基于Office Dev Center创建:

@model List<Tuple<string,string>>
<table class="table">
    <tr>
        <th>接收时间</th>
        <th>邮件主题</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Item1)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Item2)
            </td>
        </tr>
    }
</table>
显示页面
 public class DefaultController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public async Task<ActionResult> RetrieveUserEmails()
        {

            List<Tuple<string, string>> mailResults = new List<Tuple<string, string>>();
            try
            {
                GraphServiceClient exClient = new GraphServiceClient(new GraphAuthentication());
                QueryOption topcount = new QueryOption("$top", "10");
                var _Results = await exClient.Me.Messages.Request(new[] { topcount }).GetAsync();

                var mails = _Results.CurrentPage;
                foreach (var mail in mails)
                {
                    mailResults.Add(new Tuple<string, string>(mail.ReceivedDateTime.ToString(), mail.Subject));
                }
            }
            catch (Exception ex)
            {
                return View(ex.Message);
            }
            return View(mailResults);
        }
    }

    public class GraphAuthentication : IAuthenticationProvider
    {

        public async Task AuthenticateRequestAsync(System.Net.Http.HttpRequestMessage request)
        {
            AuthenticationResult authResult = null;
            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", "https://login.microsoftonline.com", tenantId), new ADALTokenCache(signInUserId));
            try
            {

                authResult = await authContext.AcquireTokenSilentAsync("https://graph.microsoft.com", new ClientCredential("your client ID", "your client secret"), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
                request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
            }
            catch (AdalException ex)
            {
                if (ex.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                   authContext.TokenCache.Clear();
                }
            }
        }
    }
MVC Controller

这里要注意,使用GraphServiceClient需要引用Microsoft.Graph程序集。


结束语

以上为Graph API的介绍,请继续关注后续博客。

 

转载于:https://www.cnblogs.com/renzh/p/5408258.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值