我花了几个小时处理一个奇怪的“错误”,该错误涉及来自 .NET Web 服务的请求 AD 信息用户权限的 Web 方法。
好消息是我修复了这个错误,但我会理解为什么更正是有效的。
有 bug 的 web 方法如下:
public bool ValidateTask(string originatingUser)
{
SPUserToken userToken = null;
// get the System account for impersonation
string userToken = site.SystemAccount.UserToken;
using (SPSite rootSite = new SPSite(site.ID, userToken))
{
using (SPWeb web = rootSite.OpenWeb())
{
// get the domain name of the application pool of the web app
string servicesDomain =
StringUtilities.GetDomain(site.WebApplication.ApplicationPool.ManagedAccount.Username);
// get the domain name of the user
string accountsDomain = StringUtilities.GetDomain(originatingUser);
PrincipalContext ServicesDomainContext =
new PrincipalContext(ContextType.Domain, servicesDomain);
PrincipalContext AccountsDomainContext =
new PrincipalContext(ContextType.Domain, accountsDomain);
// COMException when the FindByIdentity is called because
// AccountsDomainContext.connectedServer throw exception
using (UserPrincipal usr =
UserPrincipal.FindByIdentity(AccountsDomainContext, IdentityType.SamAccountName, originatingUser))
{
// get user groups memberships
}
}
// check groups memberships and return the true or false
}
}
带校正的 web 方法如下:
public bool ValidateTask(string originatingUser)
{
SPSecurity.RunWithElevatedPrivileges(
delegate ()
{
...
using (SPSite rootSite = new SPSite(site.ID))
{
using (SPWeb web = rootSite.OpenWeb())
{
// get the domain name of the application pool of the web app
string servicesDomain =
StringUtilities.GetDomain(site.WebApplication.ApplicationPool.ManagedAccount.Username);
// get the domain name of the user
string accountsDomain = StringUtilities.GetDomain(originatingUser);
PrincipalContext ServicesDomainContext =
new PrincipalContext(ContextType.Domain, servicesDomain);
PrincipalContext AccountsDomainContext =
new PrincipalContext(ContextType.Domain, accountsDomain);
using (UserPrincipal usr =
UserPrincipal.FindByIdentity(AccountsDomainContext, IdentityType.SamAccountName, originatingUser))
{
// get user groups memberships
}
}
}
// check groups memberships and return the true or false
}
); // end of delegate method
}
==================================================== ==========================
在 sharepoint 中,我认为 Impersonation 和 RunWithElevatedPrivilege 会产生相同的结果。所以我的问题是:
1- 那么为什么 RunWithElevatedPrivilege 有效?
2-当我们在 WebMethod 上下文中提升权限时,凭证是什么?这是 SharePoint Web Services Root 的身份池帐户?
3-我可以追踪这两种方法的凭据吗?