gpt4 book ai didi

c# - 将应用程序池凭据用于 WebClient 请求

转载 作者:太空狗 更新时间:2023-10-30 01:16:54 26 4
gpt4 key购买 nike

我想使用应用程序池凭据来避免 Web API 方法的双跳问题。但是,我不希望模拟所有请求,只希望模拟这个特定请求。代码目前看起来像这样:

[Route("api/mycontroller/mymethod")]
public string GetDataFromOtherInternalSystem(int id)
{
var client = new WebClient ( Credentials = CredentialCache.DefaultNetworkCredentials);

return client.DownloadString('http://internaldomain/api/method/id')

}

据我了解MSDN ,用户上下文是该浏览器 session 的登录用户(即我的帐户通过 Active Directory 而不是应用程序池的帐户)。

The credentials returned by DefaultNetworkCredentials represents the authentication credentials for the current security context in which the application is running. For a client-side application, these are usually the Windows credentials (user name, password, and domain) of the user running the application. For ASP.NET applications, the default network credentials are the user credentials of the logged-in user, or the user being impersonated.

这会产生双跳问题,如果请求完全来自作为服务帐户的 Web 应用程序(我不必即时构建凭据),则可以消除该问题。

关于如何在我不指定用户凭据的情况下模拟应用程序池的任何想法如下:

var cred = new NetworkCredential("myusername", "mypassword")

我再次尝试避免为 Kerberos 或 CORS 正确设置其他 Web 服务。

最佳答案

这可以通过将空指针 (IntPtr.Zero) 传递给 WindowsIdentity 类的静态 Impersonate 方法来实现。这是 MSDN document for the Impersonate method 中的描述方式:

Calling the Impersonate(IntPtr) method with a userToken value of Zero is equivalent to calling the Win32 RevertToSelf function. If another user is currently being impersonated, control reverts to the original user.

用法看起来像下面这样:

using (var impersonationContext = WindowsIdentity.Impersonate(IntPtr.Zero))
{
try
{
// this code is now using the application pool indentity
}
finally
{
if (impersonationContext != null)
{
impersonationContext.Undo();
}
}
}

关于c# - 将应用程序池凭据用于 WebClient 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33615126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com