* Added Authorization which is not working

This commit is contained in:
2025-02-23 21:19:04 +01:00
parent 6774311433
commit 5bcf406465
29 changed files with 407 additions and 210 deletions

View File

@@ -0,0 +1,52 @@
using Microsoft.AspNetCore.Components.Authorization;
namespace OrdersManagement.Services;
public class ServiceBase<T> where T : class
{
private readonly AuthenticationStateProvider _authenticationStateProvider;
private readonly HttpClient _httpClient;
protected ServiceBase(IHttpClientFactory httpClientFactory, AuthenticationStateProvider authenticationStateProvider)
{
_authenticationStateProvider = authenticationStateProvider;
_httpClient = httpClientFactory.CreateClient("FaKrosnoApi");
_ = Configure();
}
protected async Task<IEnumerable<T>?> GetListAsync(string request)
{
var response = await _httpClient.GetAsync(request);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<IEnumerable<T>>();
}
protected async Task<T?> GetByIdAsync(string request)
{
var response = await _httpClient.GetAsync(request);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<T>();
}
protected async Task<HttpResponseMessage> PostAsync(string request)
{
var response = await _httpClient.PostAsync(request, null);
response.EnsureSuccessStatusCode();
return response;
}
private async Task Configure()
{
var token = await GetToken();
_httpClient.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
}
private async Task<string?> GetToken()
{
await ((CustomAuthenticationStateProvider)_authenticationStateProvider).InitializeAsync();
return ((CustomAuthenticationStateProvider)_authenticationStateProvider).GetToken();
}
}