好的……我的理论是,当提出 Web 请求时 IPrincipal 上下文发生了变化,这证明是准确的,这使得这个修复变得非常容易。最好的部分是,我可以继续使用我构建的 api 来发出这个请求,而无需复制 Sql Server 实体框架部分。
我对我的 api 库有以下调用:
proxyRequestResultDetails = ProxyApiWrapper.GetProxies(
adUserInfo.AssociateId,
context.User);
此代码由授权过滤器属性调用。方法原型看起来像
public void OnAuthorization(AuthorizationContext filterContext)
在内部,调用会在调用之后生成 GetProxies 方法:
public static StreamReader GetWebRequestStream(
string url,
string contentType,
bool useDefaultCredentials,
IPrincipal user)
{
var impersonationContext = ((WindowsIdentity)user.Identity).Impersonate();
var request = WebRequest.Create(url);
try
{
request.ContentType = contentType;
//request.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
//request.UseDefaultCredentials = useDefaultCredentials;
//IWebProxy p = new WebProxy();
//request.Proxy = p.
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
var response = (HttpWebResponse)request.GetResponse();
return new StreamReader(response.GetResponseStream());
}
catch (Exception e)
{
impersonationContext.Undo();
throw e;
}
finally
{
impersonationContext.Undo();
}
}
当调用方法返回时,用户的身份不再是应用程序模拟的那一套。修复非常简单:
//Track current identity before proxy call
IPrincipal user = context.User;
proxyRequestResultDetails = ProxyApiWrapper.GetProxies(
adUserInfo.AssociateId,
context.User);
//Undo any impersonating done in the GetProxies call
context.User = user;
2 行代码解决了 12 小时的头痛问题。它本来会更糟。无论如何。感谢您成为一个共鸣板。我尝试与鸭子进行这种转换,但鸭子很困惑。