Fix credentials on websocket

This commit is contained in:
Alexander Horner
2022-12-07 23:28:09 +00:00
parent ecbde9509f
commit 2b298d6e19

View File

@@ -140,7 +140,7 @@ namespace ntfysh_client
} }
} }
private async Task ListenToTopicWithWebsocketAsync(Uri uri, NetworkCredential credentials, CancellationToken cancellationToken, SubscribedTopic topic) private async Task ListenToTopicWithWebsocketAsync(Uri uri, string? credentials, CancellationToken cancellationToken, SubscribedTopic topic)
{ {
int connectionAttempts = 0; int connectionAttempts = 0;
@@ -158,7 +158,8 @@ namespace ntfysh_client
{ {
//Establish connection //Establish connection
using ClientWebSocket socket = new(); using ClientWebSocket socket = new();
socket.Options.Credentials = credentials;
if (!string.IsNullOrWhiteSpace(credentials)) socket.Options.SetRequestHeader("Authorization", "Basic " + credentials);
await socket.ConnectAsync(uri, cancellationToken); await socket.ConnectAsync(uri, cancellationToken);
@@ -269,7 +270,7 @@ namespace ntfysh_client
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, $"{serverUrl}/{HttpUtility.UrlEncode(topicId)}/json"); HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, $"{serverUrl}/{HttpUtility.UrlEncode(topicId)}/json");
if (username != null && password != null) if (username is not null && password is not null)
{ {
byte[] boundCredentialsBytes = Encoding.UTF8.GetBytes($"{username}:{password}"); byte[] boundCredentialsBytes = Encoding.UTF8.GetBytes($"{username}:{password}");
@@ -295,8 +296,17 @@ namespace ntfysh_client
SubscribedTopic newTopic = new(topicId, serverUrl, username, password); SubscribedTopic newTopic = new(topicId, serverUrl, username, password);
string? credentials = null;
if (username is not null && password is not null)
{
byte[] boundCredentialsBytes = Encoding.UTF8.GetBytes($"{username}:{password}");
credentials = Convert.ToBase64String(boundCredentialsBytes);
}
CancellationTokenSource listenCanceller = new(); CancellationTokenSource listenCanceller = new();
Task listenTask = ListenToTopicWithWebsocketAsync(new Uri($"{serverUrl}/{HttpUtility.UrlEncode(topicId)}/ws"), new NetworkCredential(username, password), listenCanceller.Token, newTopic); Task listenTask = ListenToTopicWithWebsocketAsync(new Uri($"{serverUrl}/{HttpUtility.UrlEncode(topicId)}/ws"), credentials, listenCanceller.Token, newTopic);
newTopic.SetAssociatedRunner(listenTask, listenCanceller); newTopic.SetAssociatedRunner(listenTask, listenCanceller);