C#模擬http請求增加驗證auth
阿新 • • 發佈:2018-12-30
適用post put 請求
最背景:近單位用elasticsearch升級從2.4X升級到5.X,增加了auth的許可權驗證。使用的PlainElastic.Net元件,該元件原始碼支援許可權有問題,下載了原始碼更改了下。
本質是把使用者名稱和密碼放到了head裡。
authString =“使用者名稱:密碼@127.0.0.1”;
string authUrl = url.Replace("http://","");
string authString = authUrl.Substring(0, authUrl.LastIndexOf("@"));
if (!string.IsNullOrWhiteSpace(authString))
{
var array = authString.Split(':');
string userName = array[0];
string password = array[1];
string encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{userName}:{password}" ));
request.Headers.Add("Authorization", $"Basic {encoded}");
}
或者
WebRequest request = WebRequest.Create(url);
request.Credentials = GetCredential();
request.PreAuthenticate = true;
private CredentialCache GetCredential(string url)
{
string authUrl = url.Replace ("http://","");
string authString = authUrl.Substring(0, authUrl.LastIndexOf("@"));
string userName = array[0];
string password = array[1];
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new System.Uri(url), "Basic", new NetworkCredential(userName, password ));
return credentialCache;
}