'Basic authentication with CouchDB in C#
I'm having issues with CouchDB getting authentication Working i use this GET request (http://Admin:[email protected]:5984/_all_dbs) and i get back that i am not a Server Admin.
The Request Method i use!
public string request_GET(string URL)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex);
Console.ResetColor();
Console.ReadKey();
return "Error";
}
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
The Solution to the probleme!
public HttpClient Client { get; set; } = new HttpClient();
private static AuthenticationHeaderValue GetBasicAuthorizationHeader(string username, string password)
{
Span<byte> bytes = Encoding.UTF8.GetBytes($"{username}:{password}");
string encoded = Convert.ToBase64String(bytes);
return new AuthenticationHeaderValue("Basic", encoded);
}
public async Task<string> GetRequestAsync(string URL, String Username, String Password)
{
try
{
using HttpRequestMessage request = new(HttpMethod.Get, URL);
request.Headers.Authorization = GetBasicAuthorizationHeader(Username,Password);
using HttpResponseMessage response = await Client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"Error in request [{response.StatusCode}]";
}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex);
Console.ResetColor();
Console.ReadKey();
return "Error";
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
