| | | 1 | | using System.Net.Http.Headers; |
| | | 2 | | using ArturRios.Util.Http; |
| | | 3 | | using ArturRios.Util.WebApi.Security.Records; |
| | | 4 | | |
| | | 5 | | namespace ArturRios.Util.WebApi.Client; |
| | | 6 | | |
| | | 7 | | /// <summary>Base class for a group of related routes (endpoints) on a remote web API, sharing a base URL and gateway.</ |
| | | 8 | | /// <param name="gateway">The HTTP gateway used to issue requests.</param> |
| | 1 | 9 | | public abstract class BaseWebApiClientRoute(HttpGateway gateway) |
| | | 10 | | { |
| | | 11 | | /// <summary>The HTTP gateway used to issue requests to this route group.</summary> |
| | 1 | 12 | | protected readonly HttpGateway Gateway = gateway; |
| | | 13 | | |
| | | 14 | | /// <summary>The base URL of the routes exposed by this class.</summary> |
| | | 15 | | public abstract string BaseUrl { get; } |
| | | 16 | | |
| | | 17 | | /// <summary>Authenticates against <paramref name="authRoute"/> using <paramref name="credentials"/> and returns the |
| | | 18 | | /// <param name="credentials">The credentials to authenticate with.</param> |
| | | 19 | | /// <param name="authRoute">The relative authentication route.</param> |
| | | 20 | | /// <returns>The <see cref="Authentication"/> response returned by the API.</returns> |
| | | 21 | | /// <exception cref="WebApiClientException">Thrown when the authentication response contains no body.</exception> |
| | | 22 | | protected async Task<Authentication> AuthenticateAsync(Credentials credentials, string authRoute) |
| | 0 | 23 | | { |
| | 0 | 24 | | var output = await Gateway.PostAsync<Authentication>(authRoute, credentials); |
| | | 25 | | |
| | 0 | 26 | | return output.Body ?? throw new WebApiClientException("Could not authenticate: the authentication response conta |
| | 0 | 27 | | } |
| | | 28 | | |
| | | 29 | | /// <summary>Sets the bearer token used for subsequent requests made through <see cref="Gateway"/>.</summary> |
| | | 30 | | /// <param name="authToken">The JWT to send as a Bearer token.</param> |
| | | 31 | | protected void Authorize(string authToken) => |
| | 2 | 32 | | Gateway.Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken); |
| | | 33 | | |
| | | 34 | | /// <summary>Authenticates against <paramref name="authRoute"/> and applies the resulting token to the gateway's def |
| | | 35 | | /// <param name="credentials">The credentials to authenticate with.</param> |
| | | 36 | | /// <param name="authRoute">The relative authentication route.</param> |
| | | 37 | | protected async Task AuthenticateAndAuthorizeAsync(Credentials credentials, string authRoute) |
| | 0 | 38 | | { |
| | 0 | 39 | | var authentication = await AuthenticateAsync(credentials, authRoute); |
| | | 40 | | |
| | 0 | 41 | | Authorize(authentication.Token!); |
| | 0 | 42 | | } |
| | | 43 | | } |