[英]How do I use C# REST API HttpClient for both Basic header authentication and for default AD credentials?
This code results in a bad request or "A task was canceled."此代码导致错误请求或“任务已取消”。 because it contains both type of authentication.
因为它包含两种类型的身份验证。
handler.UseDefaultCredentials = true;
AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
//Create the HttpClientHandler
HttpClientHandler handler = new HttpClientHandler();
//Add the AD Credentials
handler.UseDefaultCredentials = true;
if (Client == null)
{
Client = new HttpClient(handler);
Client.Timeout = TimeSpan.FromMinutes(0.5);
}
Client.DefaultRequestHeaders.Clear();
//Add Basic header credentials for the remote server
var authToken = Encoding.ASCII.GetBytes($"{userName}:{password}");
Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
if (ReqHeaders.Count != 0)
{
foreach (KeyValuePair<string, string> pair in ReqHeaders)
{
Client.DefaultRequestHeaders.Add(pair.Key, pair.Value);
}
}
I need to first authenticate locally to the ESB and then to a remote server.我需要先在本地对 ESB 进行身份验证,然后再对远程服务器进行身份验证。
Instead of setting the Authorization header using Client.DefaultRequestHeaders.Authorization
, try just setting the header directly:不要使用
Client.DefaultRequestHeaders.Authorization
设置授权 header ,而是直接设置 header :
Client.DefaultRequestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(authToken)}");
And are you sure the token should be in base 64 format?你确定令牌应该是 base 64 格式吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.