代码之家  ›  专栏  ›  技术社区  ›  User.Anonymous

Sharepoint REST api和MVC AAD connect

  •  0
  • User.Anonymous  · 技术社区  · 7 年前

    我需要执行这个查询 https://<tenant>.sharepoint.com/_api/search/query?querytext=%27contenttype:articles%27 通过C#中服务器端的Sharepoint REST api。

    我有来自MVC门户的Oauth2连接,所以我的目标是从连接中检索令牌,并将其作为承载令牌发送到sharepoint端点。

    我是说这样的

      string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
      AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID));
      ClientCredential credential = new ClientCredential(clientId, appKey);
      AuthenticationResult result = await authContext.AcquireTokenSilentAsync("https://<tenant>.sharepoint.com/", credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
    
      HttpClient client = new HttpClient();
      HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://<tenant>.sharepoint.com/_api/search/query?querytext=%27contenttype:articles%27");
      request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
      HttpResponseMessage response = await client.SendAsync(request);
    

    但很明显,我找不到令牌。。。

    另一方面,我用ADv2和GraphServiceClient构建了一个运行良好的应用程序,但我不知道如何在图形模型中转换查询(而且我没有任何管理员同意)。

    因此,我有两种方法来解决我的问题,我希望更好地使用microsoft graph api的第二个选项,但欢迎提供任何帮助。

    非常感谢。

    1 回复  |  直到 7 年前
        1
  •  1
  •   baywet    7 年前

    围绕搜索
    这个 graph search API 功能有限,首先它只会在当前目标网站集(驱动器)中搜索,其次我不确定目前它是否支持按内容类型搜索(可能带有$过滤器…)
    但如果这符合你的限制,它可能是一个(更容易)的选择。

    围绕身份验证(&A);认证
    在这两种情况下(图形或SharePoint搜索),当人们访问您的应用程序(asp.net MVC)时,会发生什么情况?身份验证中间件负责将用户重定向到AAD,获取应用程序的访问令牌,将其重定向到应用程序,应用程序使用该访问令牌在应用程序上创建会话。
    我的观点是:在这一点上,你所拥有的是:

    • 应用程序的访问令牌(不是图形,不是SharePoint
    • 针对你的应用程序的会话

    要访问SharePoint/图表,您需要做几件事:

    • 拦截并保留令牌服务器端(是否将其添加到会话?)如果您的中间件实现还没有做到这一点
    • 使用该访问令牌+你的应用程序id/secret/certificate来获取对SharePoint/AAD的图形的访问令牌
    • 确保您的应用程序在AAD中具有与SharePoint/适当的图形API对话的权限

    下面是一个示例,介绍如何使用 MSAL .
    注意:我在这里使用证书,但您可以使用机密

    var cac = new ClientAssertionCertificate(ApplicationId, CertificateProvider.AppCertificate);
                var ua = new UserAssertion(apiAccessToken);
                authenticationResult = await authContext.AcquireTokenAsync(resource, cac, ua);
    

    我没有提供关于如何拦截令牌/在此处获取令牌的代码,因为您的问题不清楚您当前的身份验证和授权配置以及您使用的MVC“风格”(asp.net core+Middleware、classic+owin等)。我建议你从另一个问题开始,更详细地回答这一点。