Skip to content
This repository has been archived by the owner on Dec 3, 2024. It is now read-only.

Commit

Permalink
Merge pull request #59 from DFE-Digital/nw/add-health-endpoint
Browse files Browse the repository at this point in the history
Add health check endpoint to API
  • Loading branch information
nwarms authored May 17, 2024
2 parents ed80817 + 49de2e5 commit 1f1b6ae
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 19 deletions.
34 changes: 29 additions & 5 deletions Dfe.Identifiers.Api.Test/Middleware/ApiKeyMiddlewareTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public async Task No_ApiKey_Returns_NotAuthorized()
{
using var server = await SetupTestServer();

var request = new HttpRequestMessage(HttpMethod.Get, "/");
var request = new HttpRequestMessage(HttpMethod.Get, "/api");

var context = await server.SendAsync(request);

Expand All @@ -67,7 +67,7 @@ public async Task Random_ApiKey_Returns_NotAuthorized()
{
using var server = await SetupTestServer();

var request = new HttpRequestMessage(HttpMethod.Get, "/");
var request = new HttpRequestMessage(HttpMethod.Get, "/api");
request.Headers.Add(AuthenticationConstants.APIKEYNAME, "random key");

var context = await server.SendAsync(request);
Expand All @@ -82,13 +82,37 @@ public async Task Correct_ApiKey_Returns_NotFound()
{
using var server = await SetupTestServer();

var request = new HttpRequestMessage(HttpMethod.Get, "/");
var request = new HttpRequestMessage(HttpMethod.Get, "/api");
request.Headers.Add(AuthenticationConstants.APIKEYNAME, validUser.ApiKey);

var context = await server.SendAsync(request);

context.StatusCode.Should().Be(HttpStatusCode.NotFound);
var content = await context.Content.ReadAsStringAsync();
content.Should().Be("");
}

[Fact]
public async Task No_ApiKey_without_ApiRoute_Returns_Unauthorized()
{
using var server = await SetupTestServer();

var request = new HttpRequestMessage(HttpMethod.Get, "/");

var context = await server.SendAsync(request);

context.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}

[Fact]
public async Task No_ApiKey_with_healthRoute_Returns_NotFound()
{
using var server = await SetupTestServer();

var request = new HttpRequestMessage(HttpMethod.Get, "/health");

var context = await server.SendAsync(request);

// Look for not found as we don't have the health endpoint setup
// 404 proves that we don't need auth to reach the endpoint
context.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
}
36 changes: 22 additions & 14 deletions Dfe.Identifiers.Api/Middleware/ApiKeyMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,33 @@ public class ApiKeyMiddleware(RequestDelegate next, ILogger<ApiKeyMiddleware> lo

public async Task InvokeAsync(HttpContext context, IApiKeyService apiKeyService)
{
if (!context.Request.Headers.TryGetValue(AuthenticationConstants.APIKEYNAME, out var extractedApiKey))
// Exclude the health endpoint from API key authentication
if (context.Request.Path.StartsWithSegments("/health"))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Api Key was not provided.");
return;
}

var user = apiKeyService.Execute(extractedApiKey!);

if (user is null)
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized client.");
await next(context);
}
else
{
using (_logger.BeginScope("requester: {requester}", user.UserName))
if (!context.Request.Headers.TryGetValue(AuthenticationConstants.APIKEYNAME, out var extractedApiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Api Key was not provided.");
return;
}

var user = apiKeyService.Execute(extractedApiKey!);

if (user is null)
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized client.");
}
else
{
await next(context);
using (_logger.BeginScope("requester: {requester}", user.UserName))
{
await next(context);
}
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions Dfe.Identifiers.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

app.UseHttpsRedirection();

app.MapHealthChecks("/health");

app.UseMiddleware<ApiKeyMiddleware>();

app.UseAuthorization();
Expand Down
1 change: 1 addition & 0 deletions Dfe.Identifiers.Api/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public void ConfigureServices(IServiceCollection services)
services.AddApplicationInsightsTelemetry();
services.AddControllers();
services.AddEndpointsApiExplorer();
services.AddHealthChecks();
services.AddSwaggerGen(c =>
{
c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
Expand Down

0 comments on commit 1f1b6ae

Please sign in to comment.