Switch to JWT authentication (#32)

* switch to jwt authentication

* update api to main/jwt

* bump version

Co-authored-by: rootdarkarchon <root.darkarchon@outlook.com>
This commit is contained in:
rootdarkarchon
2023-01-02 17:08:56 +01:00
committed by GitHub
parent 6aace54910
commit e2931c73ed
6 changed files with 38 additions and 14 deletions

View File

@@ -46,24 +46,26 @@ public partial class ApiController
private async Task<string> DownloadFileHttpClient(Uri url, IProgress<long> progress, CancellationToken ct)
{
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", SecretKey);
client.DefaultRequestHeaders.Add(AuthorizationJwtHeader.Key, AuthorizationJwtHeader.Value);
int attempts = 0;
bool failed = true;
const int maxAttempts = 10;
HttpResponseMessage response = null!;
HttpStatusCode? lastError = HttpStatusCode.OK;
var bypassUrl = new Uri(url, "?nocache=" + DateTime.UtcNow.Ticks);
while (failed && attempts < maxAttempts && !ct.IsCancellationRequested)
{
try
{
response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
response = await client.GetAsync(bypassUrl, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
failed = false;
}
catch (HttpRequestException ex)
{
Logger.Warn($"Attempt {attempts}: Error during download of {url}, HttpStatusCode: {ex.StatusCode}");
Logger.Warn($"Attempt {attempts}: Error during download of {bypassUrl}, HttpStatusCode: {ex.StatusCode}");
lastError = ex.StatusCode;
if (ex.StatusCode is HttpStatusCode.NotFound or HttpStatusCode.Unauthorized)
{
@@ -98,13 +100,13 @@ public partial class ApiController
progress.Report(bytesRead);
}
Logger.Debug($"{url} downloaded to {fileName}");
Logger.Debug($"{bypassUrl} downloaded to {fileName}");
return fileName;
}
}
catch (Exception ex)
{
Logger.Warn($"Error during file download of {url}", ex);
Logger.Warn($"Error during file download of {bypassUrl}", ex);
try
{
File.Delete(fileName);

View File

@@ -3,6 +3,8 @@ using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MareSynchronos.API;
@@ -29,6 +31,8 @@ public partial class ApiController : IDisposable, IMareHubClient
private readonly DalamudUtil _dalamudUtil;
private readonly FileCacheManager _fileDbManager;
private CancellationTokenSource _connectionCancellationTokenSource;
private string _jwtToken = string.Empty;
private KeyValuePair<string, string> AuthorizationJwtHeader => new("Authorization", "Bearer " + _jwtToken);
private HubConnection? _mareHub;
@@ -70,7 +74,7 @@ public partial class ApiController : IDisposable, IMareHubClient
private void DalamudUtilOnLogIn()
{
Task.Run(CreateConnections);
Task.Run(() => CreateConnections(true));
}
@@ -134,7 +138,7 @@ public partial class ApiController : IDisposable, IMareHubClient
}
}
public async Task CreateConnections()
public async Task CreateConnections(bool forceGetToken = false)
{
Logger.Debug("CreateConnections called");
@@ -169,6 +173,24 @@ public partial class ApiController : IDisposable, IMareHubClient
{
Logger.Debug("Building connection");
if (string.IsNullOrEmpty(_jwtToken) || forceGetToken)
{
Logger.Debug("Requesting new JWT token");
using HttpClient httpClient = new();
var postUri = new Uri(new Uri(ApiUri
.Replace("wss://", "https://", StringComparison.OrdinalIgnoreCase)
.Replace("ws://", "http://", StringComparison.OrdinalIgnoreCase)), MareAuth.AuthFullPath);
using var sha256 = SHA256.Create();
var auth = BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(SecretKey))).Replace("-", "", StringComparison.OrdinalIgnoreCase);
var result = await httpClient.PostAsync(postUri, new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("auth", auth)
})).ConfigureAwait(false);
result.EnsureSuccessStatusCode();
_jwtToken = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
Logger.Debug("JWT Token Success");
}
while (!_dalamudUtil.IsPlayerPresent && !token.IsCancellationRequested)
{
Logger.Debug("Player not loaded in yet, waiting");
@@ -253,7 +275,7 @@ public partial class ApiController : IDisposable, IMareHubClient
private Task MareHubOnReconnected(string? arg)
{
_ = Task.Run(CreateConnections);
_ = Task.Run(() => CreateConnections(false));
return Task.CompletedTask;
}
@@ -332,7 +354,7 @@ public partial class ApiController : IDisposable, IMareHubClient
return new HubConnectionBuilder()
.WithUrl(ApiUri + hubName, options =>
{
options.Headers.Add("Authorization", SecretKey);
options.Headers.Add(AuthorizationJwtHeader);
options.Transports = HttpTransportType.WebSockets | HttpTransportType.ServerSentEvents | HttpTransportType.LongPolling;
})
.WithAutomaticReconnect(new ForeverRetryPolicy())