代码之家  ›  专栏  ›  技术社区  ›  Mark Priem

使用托管服务标识调用SharePoint Online。可能吗?

  •  0
  • Mark Priem  · 技术社区  · 6 年前

    使用Logic Apps,我为我的应用程序生成了托管服务标识,并在SharePoint应用程序上授予它Sites.readwrite.All。当使用HTTP操作时,我能够调用REST端点,同时使用托管服务标识作为身份验证并使用https://.sharepoint.com as 观众。

    然后我想我会更进一步,创建一个函数应用程序,并遵循相同的模式。我创建了应用程序,生成了MSI,并将其添加到Sites.readwrite.All角色中,就像我使用Logic应用程序一样。

    然后,我使用下面的代码检索访问令牌并尝试生成clientcontext:

    #r "Newtonsoft.Json"
    using Newtonsoft.Json;
    using System;
    using System.Net; 
    using System.Net.Http;
    using System.Net.Http.Headers;
    using Microsoft.SharePoint.Client;
    public static void Run(string input, TraceWriter log)
    {
        string resource = "https://<tenant>.sharepoint.com";
        string apiversion = "2017-09-01";
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Secret", Environment.GetEnvironmentVariable("MSI_SECRET"));
            var response = client.GetAsync(String.Format("{0}/?resource={1}&api-version={2}", Environment.GetEnvironmentVariable("MSI_ENDPOINT"), resource, apiversion)).Result;
                var responseContent = response.Content; 
                string responseString = responseContent.ReadAsStringAsync().Result.ToString();
                var json = JsonConvert.DeserializeObject<dynamic>(responseString);
                string accesstoken = json.access_token.ToString()
                ClientContext ctx = new ClientContext("<siteurl>");
                ctx.AuthenticationMode = ClientAuthenticationMode.Anonymous;
                ctx.FormDigestHandlingEnabled = false;
                ctx.ExecutingWebRequest += delegate (object sender, WebRequestEventArgs e){ 
                    e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accesstoken;
                };
                Web web = ctx.Web;
                ctx.Load(web);
                ctx.ExecuteQuery();
                log.Info(web.Id.ToString());
        }
    }
    

    生成承载令牌,但请求失败,401访问被拒绝(reason=“验证请求时出错。”;category=“无效的\u客户端”)

    我尝试将访问群体更改为00000003-0000-0ff1-ce00-000000000000/.sharepoint.com@“但这会产生不同的401错误,基本上说明它无法验证访问群体uri。(”error_description“:”引发了“Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException”类型的异常。)。我还将CSOM调用替换为REST调用,模仿我使用Logic应用程序所做的调用。

    我对OAuth2的理解还不足以理解我为什么会遇到问题以及下一步该去哪里。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Razvan    6 年前

    非常基本的问题:你有没有试过在资源字符串的末尾加一个“/”。 https://[tenant].sharepoint.com/

    这个问题也存在于其他端点中,因此它可能在这里也会造成干扰。