语境。使用凭证缓存来提升代码执行

虽然服务器端代码可以使用提升的权限运行,但是没有一种等效方法来提升客户端代码中的权限(出于明显的安全原因)。或者,你可以指定凭据以模拟特定用户或服务帐户的访问权限。

要指定凭据,请构建并填充 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 中授予应用程序池帐户提升权限是违反最佳做法的,但可以在其位置使用任何相关的网络凭据。