C
C#2mo ago
536b656c6c79

App returning "Bad Request" before Controller method is called or ServiceFilter is triggered.

Hi I have an issue where I'm trying to send some user data to an endpoint from my frontend blazor server app to an api. Inspecting breakpoints tells me that the payload send is 100% correct. And the api call is made. But it only reaches somewhere before the whole controller. When I use a debugging Middleware I see that the request is made but it ends there. No more logs from inside the filter or controller method are logged and I just get the response bad request. Controller
[HttpPost]
[Route("auth0")]
[AllowAnonymous]
[ServiceFilter(typeof(AuthenticatedFrontendFilter))]
public async Task<IActionResult> CreateNewAuth0User([FromBody] UserDTO user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = await _mediator.Send(new CreateUserCommand() { _user = user });
return Created("", result);
}
[HttpPost]
[Route("auth0")]
[AllowAnonymous]
[ServiceFilter(typeof(AuthenticatedFrontendFilter))]
public async Task<IActionResult> CreateNewAuth0User([FromBody] UserDTO user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = await _mediator.Send(new CreateUserCommand() { _user = user });
return Created("", result);
}
Filter
public class AuthenticatedFrontendFilter : IActionFilter
{
private readonly EnvironmentWrapper _environmentWrapper;
private readonly ILogger<AuthenticatedFrontendFilter> _logger;

public AuthenticatedFrontendFilter(EnvironmentWrapper environmentWrapper, ILogger<AuthenticatedFrontendFilter> logger)
{
_environmentWrapper = environmentWrapper;
_logger = logger;
}
public void OnActionExecuting(ActionExecutingContext context)
{
if (!context.HttpContext.Request.Headers.TryGetValue("X-Api-Key", out var apiKey) || string.IsNullOrEmpty(apiKey))
{
_logger.LogWarning("Authentication failed: X-Api-Key header missing.");
context.Result = new UnauthorizedResult();
return;
}

if (apiKey != _environmentWrapper.APIKEY)
{
_logger.LogWarning("Authentication failed: Invalid X-Api-Key.");
context.Result = new UnauthorizedResult();
return;
}

_logger.LogInformation("Authentication successful.");
}
...
}
public class AuthenticatedFrontendFilter : IActionFilter
{
private readonly EnvironmentWrapper _environmentWrapper;
private readonly ILogger<AuthenticatedFrontendFilter> _logger;

public AuthenticatedFrontendFilter(EnvironmentWrapper environmentWrapper, ILogger<AuthenticatedFrontendFilter> logger)
{
_environmentWrapper = environmentWrapper;
_logger = logger;
}
public void OnActionExecuting(ActionExecutingContext context)
{
if (!context.HttpContext.Request.Headers.TryGetValue("X-Api-Key", out var apiKey) || string.IsNullOrEmpty(apiKey))
{
_logger.LogWarning("Authentication failed: X-Api-Key header missing.");
context.Result = new UnauthorizedResult();
return;
}

if (apiKey != _environmentWrapper.APIKEY)
{
_logger.LogWarning("Authentication failed: Invalid X-Api-Key.");
context.Result = new UnauthorizedResult();
return;
}

_logger.LogInformation("Authentication successful.");
}
...
}
3 Replies
536b656c6c79
536b656c6c79OP2mo ago
Pogram.cs
internal class Program {
private static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.RegisterApplication();
builder.Services.RegisterInfrastructure();
builder.Services.AddControllers();
builder.Services.RegisterEncryption();
builder.Services.RegisterJWTAuthentication(builder);
builder.Services.RegisterPolicies();
//builder.Services.AddScoped<AuthenticatedFrontendFilter>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

using (AsyncServiceScope scope = app.Services.CreateAsyncScope())
{
ApplicationDbContext dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
dbContext.Database.EnsureCreated();
}
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseErrorHandlingMiddleware();
app.UseMiddleware<RequestLoggingMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});

app.Run();
}
}
internal class Program {
private static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.RegisterApplication();
builder.Services.RegisterInfrastructure();
builder.Services.AddControllers();
builder.Services.RegisterEncryption();
builder.Services.RegisterJWTAuthentication(builder);
builder.Services.RegisterPolicies();
//builder.Services.AddScoped<AuthenticatedFrontendFilter>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

using (AsyncServiceScope scope = app.Services.CreateAsyncScope())
{
ApplicationDbContext dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
dbContext.Database.EnsureCreated();
}
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseErrorHandlingMiddleware();
app.UseMiddleware<RequestLoggingMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});

app.Run();
}
}
glhays
glhays2mo ago
Reason why you have the AuthenticatedFrontendFilter commented out in the DI?
536b656c6c79
536b656c6c79OP2mo ago
I was testing out if that could have been the issue It was not So I just disabled it for now

Did you find this page helpful?