Fix jwt handling

This commit is contained in:
2025-11-08 02:33:39 +07:00
parent 60cd0816f4
commit 333a0cf734

View File

@@ -263,6 +263,31 @@ builder.Services
{
OnMessageReceived = context =>
{
// Skip token extraction for anonymous endpoints to avoid validation errors
var path = context.Request.Path.Value?.ToLower();
if (path != null && (path.EndsWith("/create-token") || path.EndsWith("/authenticate")))
{
// Clear any token to prevent validation on anonymous endpoints
context.Token = null;
return Task.CompletedTask;
}
// Handle tokens sent without "Bearer " prefix for authenticated endpoints
// The standard middleware expects "Bearer <token>" but some clients send just the token
if (string.IsNullOrEmpty(context.Token))
{
var authHeader = context.Request.Headers["Authorization"].FirstOrDefault();
if (!string.IsNullOrEmpty(authHeader))
{
// If header doesn't start with "Bearer ", treat the entire value as the token
if (!authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
context.Token = authHeader;
}
// Otherwise, let the default middleware extract it (it will strip "Bearer " automatically)
}
}
// If you want to get the token from a custom header or query string
// var accessToken = context.Request.Query["access_token"];
// if (!string.IsNullOrEmpty(accessToken) &&