REST搜索API远程服务器返回错误:(401)未经授权

时间:2014-04-11 20:14:02

标签: c# rest sharepoint

我使用本教程创建了一个控制台应用程序:

http://blogs.msdn.com/b/kaevans/archive/2014/03/02/building-a-sharepoint-app-as-a-timer-job.aspx

当然,在我的控制台应用程序中有一些不同之处,我想对搜索API进行休息调用。

阅读本文:给予应用程序主体权限而不是像我在示例中那样使用租户管理:

 <AppPermissionRequests>
    <AppPermissionRequest Scope="https://sharepoint/search" Right="QueryAsUserIgnoreAppPrincipal" />
  </AppPermissionRequests>

然后我去了“_layouts / AppInv.aspx”。并使用客户端ID和上面的xml注册了应用程序。

然后我点击了Trust it。

我的app.config是这样的:

<xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="Sites"
             type="System.Configuration.NameValueSectionHandler"/>
  </configSections>
  <appSettings>
    <add key="ClientId" value="xx-1c6c-45e7-8a2a-7364a705c836"/>
    <add key="ClientSecret" value="+xx="/>
  </appSettings>
  <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <Sites>
    <add key="site1" value="https://xx.sharepoint.com/sites/developersitecollection"/>
  </Sites>
</configuration>

然后我的控制台应用程序因getresponse

上的Unauthorized Exception而失败
static void Main(string[] args)
        {
            var config = (NameValueCollection)ConfigurationManager.GetSection("Sites");


            foreach (var key in config.Keys)
            {
                Uri siteUri = new Uri(config.GetValues(key as string)[0]);

                using (ClientContext clientContext = new ClientContext(siteUri))
                {
                    string realm = TokenHelper.GetRealmFromTargetUrl(siteUri);
                    string accessToken =
                        TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal,
                        siteUri.Authority, realm).AccessToken;

                    HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(siteUri +"/_api/search/query?querytext=%27*.pptx%27");
                    endpointRequest.Method = "GET";
                    endpointRequest.Accept = "application/json;odata=verbose";
                    endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
                    HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
                    StreamReader reader = new StreamReader(endpointResponse.GetResponseStream());
                    var searchXml = new XmlDocument();
                    searchXml.LoadXml(reader.ReadToEnd()); 

                }
            }
        }

我想知道问题可能是什么

1 个答案:

答案 0 :(得分:1)

QueryAsUserIgnoreAppPrincipal权限正如它所说的那样......它将搜索作为当前用户进行查询,忽略应用程序权限。您的代码获得仅限应用程序的权限,该权限不提供用户信息。我希望401在这种情况下是未经授权的。

请记住,搜索查询是基于用户进行安全修整的。您可以尝试对仅限应用程序的上下文使用租户读取权限,删除QueryAsUserIgnoreAppOnly,但我还没有尝试查看是否可行。更好的选择可能是使用SharePointOnlineCredentials类来指定具有足够权限来访问内容的用户(如果用户无权访问内容,则内容将不会出现在搜索结果中)。

http://blogs.msdn.com/b/kaevans/archive/2014/02/23/call-o365-using-csom-with-a-console-application.aspx

相关问题