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:
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)
|
||||
|
||||
Reference in new issue
Block a user