Skip to content

Commit

Permalink
feat: implement api key authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
AlisaAkiron committed May 16, 2024
1 parent 31721e0 commit f3e5d47
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/NibiruConnector/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ public static class Configuration
public static readonly string DiscordNotificationChannel = Environment
.GetEnvironmentVariable("DISCORD_NOTIFICATION_CHANNEL") ?? "";

public static readonly string ApiKey = Environment
.GetEnvironmentVariable("API_KEY") ?? "";

public static readonly string LoggerFileOutput = Environment
.GetEnvironmentVariable("LOGGER_FILE_OUTPUT") ?? "";

Expand Down
8 changes: 8 additions & 0 deletions src/NibiruConnector/Configurator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Discord.WebSocket;
using MassTransit;
using NibiruConnector.Extensions;
using NibiruConnector.Middlewares;
using NibiruConnector.Services;
using Serilog;
using Serilog.Events;
Expand Down Expand Up @@ -74,6 +75,13 @@ public static IServiceCollection AddLocalTransit(this IServiceCollection service
return services;
}

public static WebApplication UseApiKeyAuthentication(this WebApplication app)
{
app.UseMiddleware<ApiKeyAuthenticationMiddleware>();

return app;
}

private const string LoggerOutputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}";

private static void ConfigureLogger(this ILoggingBuilder loggingBuilder)
Expand Down
35 changes: 35 additions & 0 deletions src/NibiruConnector/Middlewares/ApiKeyAuthenticationMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
namespace NibiruConnector.Middlewares;

public class ApiKeyAuthenticationMiddleware
{
private readonly RequestDelegate _next;

public ApiKeyAuthenticationMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task InvokeAsync(HttpContext context)
{
if (string.IsNullOrEmpty(Configuration.ApiKey))
{
await _next(context);
return;
}

context.Request.Headers.TryGetValue("ApiKey", out var apiKey);
if (apiKey.Count != 1)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}

if (apiKey[0] != Configuration.ApiKey)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}

await _next(context);
}
}
2 changes: 2 additions & 0 deletions src/NibiruConnector/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

var app = builder.Build();

app.UseApiKeyAuthentication();

app.MapControllers();

await app.RunAsync();

0 comments on commit f3e5d47

Please sign in to comment.