![](/img/trans.png)
[英]Twitter Search API The remote server returned an error: (401) Unauthorized
[英]REST Search API The remote server returned an error: (401) Unauthorized
我通過使用本教程創建了一個控制台應用程序:
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注冊了應用。
然后,我單擊“信任它”。
我的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上顯示未經授權的異常
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());
}
}
}
我想知道問題可能是什么
QueryAsUserIgnoreAppPrincipal權限完全按照其說的進行操作...它以當前用戶身份查詢搜索,而忽略了應用程序權限。 您的代碼獲得僅應用程序權限,該權限不提供用戶信息。 我希望在這種情況下未經授權的401。
請記住,搜索查詢是根據用戶進行安全性修剪的。 您可能會嘗試對僅應用程序的上下文使用“租戶讀取”權限,刪除QueryAsUserIgnoreAppOnly,但是我還沒有嘗試過看看是否會起作用。 更好的選擇可能只是使用SharePointOnlineCredentials類來指定具有足夠權限來訪問內容的用戶(如果該用戶無權訪問該內容,則該內容將不會出現在搜索結果中)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.