我有以下代码:
var baseUrl = "https://" + GetIdentityProviderHost(environment) + "/oauth2/authorize";
var query = $"?scope=openid&response_type=code&redirect_uri={redirectUrl}&client_id={clientId}";
var combinedUrl = baseUrl + query;
var currentUser = WindowsIdentity.GetCurrent();
await WindowsIdentity.RunImpersonated(currentUser.AccessToken, async() =>
{
using (var client = new WebClient{ UseDefaultCredentials = true })
{
var response = client.DownloadString(combinedUrl);
Console.WriteLine(response);
}
});
它基本上构造一个 URL,然后调用它。
调用返回 401(未授权)。
但如果我拿
combinedUrl
并将其粘贴到 chrome 或 postman it 完美运行 .这告诉我我的通话可以正常工作,因为 Chrome 正在使用我的 Windows 凭据进行通话。我添加了
WindowsIdentity.RunImpersonated
尝试解决此问题的代码。但是好像没有什么效果。如何使用集成 Windows 身份验证 (IWA) 进行网络调用?
细节:
如果我运行以下 cURL 命令,它会起作用:
curl -L --negotiate -u : -b ~/cookiejar.txt "https://myIdp.domain.net/oauth2/authorize?scope=openid&response_type=code&redirect_uri=https://localhost:5001&client_id=my_client_id_here"
我不确定如何在 C# 代码中复制所有这些。
仅供引用:我在这个问题中专门询问了这个 cURL 命令(因为这个问题的重点是模拟):Replicate cURL Command Using Redirect and Cookies in .Net Core 3.1
最佳答案
我面前没有 Windows 盒子,所以我无法彻底验证这一点。但这似乎有点像蛇坑,基于讨论,例如在这里(尤其是从这条评论开始):
https://github.com/dotnet/runtime/issues/24009#issuecomment-544511572
关于如何在异步调用中保持身份,似乎有各种不同的意见。
但如果你看那个评论中的例子,
app.Use(async (context, next) =>
{
await WindowsIdentity.RunImpersonated(someToken, () => next());
});
它看起来不像你作为
WindowsIdentity.RunImpersonated
的第二个参数发送的函数应该是异步的。你有没有尝试过:
var baseUrl = "https://" + GetIdentityProviderHost(environment) + "/oauth2/authorize";
var query = $"?scope=openid&response_type=code&redirect_uri={redirectUrl}&client_id={clientId}";
var combinedUrl = baseUrl + query;
var currentUser = WindowsIdentity.GetCurrent();
await WindowsIdentity.RunImpersonated(currentUser.AccessToken, () =>
{
using (var client = new WebClient{ UseDefaultCredentials = true })
{
var response = client.DownloadString(combinedUrl);
Console.WriteLine(response);
}
});
您可以在
WindowsIdentity.RunImpersonated
上找到 Microsoft 文档这里:https://docs.microsoft.com/en-us/dotnet/api/system.security.principal.windowsidentity.runimpersonated?view=netcore-3.1
关于c# - .Net Core WindowsIdentity 模拟似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60839845/