I would create a simple DelegatingHandler that will be called before each requests
public class AuthorizationDelegatingHandler : DelegatingHandler
{
private const string API_KEY = "8139E7541722F5D91ED8FB15165F4"
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request.Headers.Authorization == null)
return request.CreateResponse(HttpStatusCode.Unauthorized);
if (request.Headers.Authorization.Scheme != "Basic")
return request.CreateResponse(HttpStatusCode.Unauthorized);
var authToken = request.Headers.Authorization.Parameter;
var apiKey = Encoding.UTF8.GetString(Convert.FromBase64String(authToken))
.Split(':')
.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x));
if (string.IsNullOrWhiteSpace(apiKey) || apiKey != API_KEY)
return request.CreateResponse(HttpStatusCode.Unauthorized);
return await base.SendAsync(request, cancellationToken);
}
}
I know that using a static token is maybe not the best thing, but it should give you an idea.
In your application bootstrap, you will need to register this handler
GlobalFilters.Filters.Add(new AuthorizationDelegatingHandler());
Then when you will call this API, you can add the Authorization header using Basic
scheme.
Each request that does not have this header will return an Unauthorized response.
The client should call the API this way:
var client = new HttpClient
{
BaseAddress = new Uri(API_URL)
};
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes("8139E7541722F5D91ED8FB15165F4:")));