語境。使用憑證快取來提升程式碼執行

雖然伺服器端程式碼可以使用提升的許可權執行,但是沒有一種等效方法來提升客戶端程式碼中的許可權(出於明顯的安全原因)。或者,你可以指定憑據以模擬特定使用者或服務帳戶的訪問許可權。

要指定憑據,請構建並填充 CredentialCache 物件,然後將其分配給 ClientContext 物件的 Credentials 屬性。

下面的示例模擬應用程式池帳戶,並假定使用 NTLM 的本地 SharePoint 2013 環境。

using System.Net;
using Microsoft.SharePoint.Client;

using (ClientContext ctx = new ClientContext("https://onpremises.local/sites/demo/"))
{
    // need the web object
    ctx.Load(ctx.Web);
    ctx.ExecuteQuery();

    // here the default network credentials relate to the identity of the account
    // running the App Pool of your web application.
    CredentialCache credCache = new CredentialCache();        
    cc.Add(new Uri(ctx.Web.Url), "NTLM", CredentialCache.DefaultNetworkCredentials);

    ctx.Credentials = credCache;
    ctx.AuthenticationMode = ClientAuthentication.Default;
    ctx.ExecuteQuery();

    // do stuff as elevated app pool account
}

請注意,在 SharePoint 中授予應用程式池帳戶提升許可權是違反最佳做法的,但可以在其位置使用任何相關的網路憑據。