fix(auth): API key acceptée en Bearer sur les hubs SignalR

Le client SignalR .NET envoie le token d'accès en header Authorization:
Bearer sur le POST negotiate HTTP (les WebSockets ne peuvent pas poser
de header custom) ; le navigateur l'envoie en query string access_token.
ConfigHub étant [Authorize(AuthenticationSchemes="ApiKey")], le handler
ApiKey doit lire les deux sur /hubs. Le fallback reste scoped aux hubs :
sur les endpoints API, un Bearer non-JWT renvoie toujours 401.

Tests : +2 intégration (Bearer sur ConfigHub OK, Bearer hors /hubs 401).
This commit is contained in:
Arnaud Dartois committed 2026-08-10 10:35:15 +02:00
1 parent 1e3322cd1a
commit bfe9dc6e56
2 files changed
+66 -6

No files matched your search

@@ -35,17 +35,26 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthentic
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
// X-API-Key header only (pas de Bearer — réservé au handler JWT).
// SignalR WebSocket clients cannot set custom headers, so the API key
// is also accepted via the access_token query string on hub paths
// (same convention as the JwtBearer handler).
// SignalR clients cannot set custom headers on WebSocket connections:
// the .NET client sends the access token as `Authorization: Bearer`
// on the HTTP negotiate POST, and browsers send it as the
// `access_token` query string. Accept both on hub paths (same
// convention as the JwtBearer handler's OnMessageReceived).
var apiKey = Request.Headers["X-API-Key"].FirstOrDefault();
if (string.IsNullOrEmpty(apiKey))
{
var path = Request.Path;
var queryToken = Request.Query["access_token"].FirstOrDefault();
if (!string.IsNullOrEmpty(queryToken) && path.StartsWithSegments("/hubs"))
apiKey = queryToken;
if (path.StartsWithSegments("/hubs"))
{
var queryToken = Request.Query["access_token"].FirstOrDefault();
var bearer = Request.Headers.Authorization.FirstOrDefault();
if (!string.IsNullOrEmpty(queryToken))
apiKey = queryToken;
else if (!string.IsNullOrEmpty(bearer) &&
bearer.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
apiKey = bearer["Bearer ".Length..].Trim();
}
}
if (string.IsNullOrEmpty(apiKey) || apiKey.Length < 8)
@@ -157,6 +157,57 @@ public class SignalRHubScenarios : PostgresTestBase
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task ConfigHub_ApiKeyInBearerHeader_ReturnsOk()
{
// The .NET SignalR client sends the access token as `Authorization:
// Bearer <apiKey>` on the HTTP negotiate POST (WebSocket can't set
// custom headers). ConfigHub is ApiKey-only, so the ApiKey handler
// must read the Bearer value on hub paths.
var admin = await Factory.CreateAdminClientAsync();
var siteResponse = await admin.PostAsJsonAsync("api/sites", new
{
name = "ConfigHub BearerSite",
timezone = "UTC"
});
var siteContent = await siteResponse.Content.ReadFromJsonAsync<JsonElement>();
var siteId = siteContent.GetProperty("id").GetGuid();
var tokenResponse = await admin.PostAsync($"api/sites/{siteId}/tokens", null);
var tokenContent = await tokenResponse.Content.ReadFromJsonAsync<JsonElement>();
var token = tokenContent.GetProperty("token").GetString()!;
var registerResponse = await admin.PostAsJsonAsync("api/agents/register", new
{
token,
hostname = "confighub-bearer-agent",
version = "1.0.0-test"
});
var agentContent = await registerResponse.Content.ReadFromJsonAsync<JsonElement>();
var apiKey = agentContent.GetProperty("apiKey").GetString()!;
var client = Factory.CreateClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", apiKey);
var response = await client.PostAsync(
"/hubs/config/negotiate?negotiateVersion=1", null);
response.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.Redirect);
}
[Fact]
public async Task ConfigHub_ApiKeyInBearerHeader_OnNonHubPath_Returns401()
{
// The Bearer fallback must be scoped to /hubs — an API key sent as
// Bearer on a regular API endpoint must not authenticate (it would
// clash with the JWT scheme otherwise).
var admin = await Factory.CreateAdminClientAsync();
var client = Factory.CreateClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "some-api-key-that-is-long-enough");
var response = await client.GetAsync("/api/sites");
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task EventsHub_ApiKeyInQueryString_StillRequiresJwt()
{