Skip to content

Commit f06c110

Browse files
committed
Improve authentication middleware and config structure
Added logic to handle cases where both API key and JWT token are provided, returning a 409 Conflict status. Refactored JWT token retrieval to use the `Authorization` header directly. Updated `ValidateApiKeyAsync` to check the new `Authorization:Enabled` flag and adjusted configuration keys from `Authentication` to `Authorization`. Enhanced `GetUserInfo` in `AuthenticateController` to handle potential null references. Updated `appsettings.json` to reflect the new `Authorization` section and added an `enabled` flag for feature toggling.
1 parent b20ca69 commit f06c110

File tree

3 files changed

+32
-11
lines changed

3 files changed

+32
-11
lines changed

src/Genocs.Auth/JwtOrApiKeyAuthenticationMiddleware.cs

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,22 @@ public class JwtOrApiKeyAuthenticationMiddleware(RequestDelegate next, IConfigur
3030

3131
public async Task Invoke(HttpContext context)
3232
{
33-
// Check for API key authentication first
33+
// Get the apiKey if any
3434
string? apiKey = context.Request.Headers["x-gnx-apikey"];
35+
36+
// Get JWT authentication if any
37+
string? jwt = context.Request.Headers.Authorization;
38+
39+
// Check if both authentication are in place
40+
if (!string.IsNullOrWhiteSpace(apiKey) && !string.IsNullOrWhiteSpace(jwt))
41+
{
42+
// Invalid API key
43+
context.Response.StatusCode = 409;
44+
await context.Response.WriteAsync("Invalid Configuration! ApiKey and JWT token cannot be on the same time!");
45+
return;
46+
}
47+
48+
// Check for API key authentication first
3549
if (!string.IsNullOrEmpty(apiKey))
3650
{
3751
if (await ValidateApiKeyAsync(apiKey))
@@ -60,11 +74,10 @@ public async Task Invoke(HttpContext context)
6074
}
6175
}
6276

63-
// Check for Firebase JWT authentication
64-
string? authHeader = context.Request.Headers.Authorization;
65-
if (authHeader?.StartsWith("Bearer ") == true)
77+
// Check for JWT authentication
78+
if (jwt?.StartsWith("Bearer ") == true)
6679
{
67-
string token = authHeader["Bearer ".Length..].Trim();
80+
string token = jwt["Bearer ".Length..].Trim();
6881

6982
try
7083
{
@@ -100,11 +113,18 @@ public async Task Invoke(HttpContext context)
100113
/// <returns>True if the API key is valid, false otherwise.</returns>
101114
private async Task<bool> ValidateApiKeyAsync(string apiKey)
102115
{
116+
// Check if enabled
117+
bool isEnabled = _configuration.GetValue<bool>("Authorization:Enabled");
118+
if (!isEnabled)
119+
{
120+
return await Task.FromResult(false);
121+
}
122+
103123
// Get valid API keys from configuration
104-
string[] validApiKeys = _configuration.GetSection("Authentication:ApiKeys").Get<string[]>() ?? [];
124+
string[] validApiKeys = _configuration.GetSection("Authorization:ApiKeys").Get<string[]>() ?? [];
105125

106126
// For development/testing
107-
string? devApiKey = _configuration["Authentication:DevApiKey"];
127+
string? devApiKey = _configuration["Authorization:DevApiKey"];
108128

109129
bool isOk = validApiKeys.Contains(apiKey) || (!string.IsNullOrWhiteSpace(devApiKey) && devApiKey == apiKey);
110130

src/demo/Genocs.Core.Demo.WebApi/Controllers/AuthenticateController.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ public IActionResult Authenticate()
9292
public IActionResult GetUserInfo()
9393
{
9494
var user = HttpContext.User;
95-
string? authType = user.Identity.AuthenticationType;
95+
string? authType = user.Identity?.AuthenticationType;
9696

9797
// Only allow JWT authentication for this endpoint
9898
if (authType != "AuthenticationTypes.Federation")

src/demo/Genocs.Core.Demo.WebApi/appsettings.json

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -162,9 +162,10 @@
162162
"endpoint": "http://localhost:5070"
163163
},
164164
"AllowedHosts": "*",
165-
"Authentication": {
166-
"DevApiKey": "abc_123",
167-
"ApiKeys": [
165+
"authorization": {
166+
"enabled": true,
167+
"devApiKey": "abc_123",
168+
"apiKeys": [
168169
"prod_api_key_1",
169170
"prod_api_key_2"
170171
]

0 commit comments

Comments
 (0)