Serilog middleware and custom middleware - asp.net-core

I have implemented some serilog middleware as described in the following blog :https://blog.datalust.co/smart-logging-middleware-for-asp-net-core I also have some other custom middleware that occurs after it in the pipeline. I also have some error handling middleware.
If my custom middleware throws an exception then somehow the status code returned from my API is different to the status code being logged. Eg I get back a 401 but the serilog middleware is logging both a 401 and also a 500.
Anyone any ideas what might be issue.

Related

How to insert middleware to run before FluentValidation?

We have a .net 7 web api, and are using FluentValidation to validate the incoming requests. Apparently FluentValidation hooks itself into the pipeline as middleware, not sure how since that is happening behind the scenes. We have middleware code that does some custom validation on a route to ensure the route itself is valid. That code works correctly, but it seems that FluentValidation is hooked in before our middleware, even if we insert the middleware immediately after app.UseAuthorization(); in program.cs.
The end result is: If the request is to an invalid route, and has validation errors that would be legit if the request itself was legit, then the response shows the validation errors instead of the invalid route message.
The preferred response message would be about the invalid route, not the validation errors.
Is there a way to get our middleware to run before FluentValidation?
Thanks for any pointers!

Does ASP.NET Core handle pre-flight requests even without CORS being added as a middleware

I'm reading the book API Security in Action by Neil Madden. In the book, there is a section about CORS and how to attach the proper headers in Java. I am aware that there is already an AddCors and UseCors built in to ASP.NET Core, but for my edification I wanted to roll my own middleware.
However, I found that I was unable to receive any sort of OPTIONS requests, they were automatically being rejected somehow, and I was unable to respond to them manually, even when it was the first middleware in the pipeline. Since the UseCors middleware is able to intercept these pre-flight requests, I'm curious whether or not it is hooking into a deeper level of ASP.NET Core than I am able to.
TL;DR: Is ASP.NET Core (or Kestrel) performing some sort of automatic preflight request checking even when UseCors is not called?
The answer in the end is no, ASP.NET does not do anything fancy when it comes to preflight requests. I looked into the source code and the CorsMiddleware (and associated extensions) are relatively simple; most of the logic is contained within the ICorsService, and doesn't impact the middleware pipeline directly.
I'm unsure what my original issue was being caused by, but it is now resolved.
See below for the source code:
https://github.com/dotnet/aspnetcore/blob/a450cb69b5e4549f5515cdb057a68771f56cefd7/src/Middleware/CORS/src/Infrastructure/CorsMiddleware.cs
It is worth noting that if you add the CORS headers manually, you will get the following exception
System.InvalidOperationException: Endpoint ProjectName.Controllers.SomeController.Login (ProjectName) contains CORS metadata, but a middleware was not found that supports CORS.
Configure your application startup by adding app.UseCors() inside the call to Configure(..) in the application startup code. The call to app.UseCors() must appear between app.UseRouting() and app.UseEndpoints(...).
You can avoid this error by setting a flag to true in the custom CORS handler
httpContext.Items["__CorsMiddlewareWithEndpointInvoked"] = true;
However, I feel it's important to stress that this should only be done for education purposes; you should be relying on built-in CorsMiddleware and not rolling your own whenever possible (and it should hopefully always be possible).

Asp.Net Core 3.1 - No Exception Middleware added in Startup - what happens?

What happens (in depth) when you dont specify an Exception Handler Middleware like UseExceptionHandler or UseDeveloperExceptionPage?
Why are the cors headers, set via the UseCors Middleware lost when an exception occurs?
https://learn.microsoft.com/de-de/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0

ASP.NET Core 2.2 - handling all exceptions with an error page

I have an ASP.NET Core (2.2) app, and I'm trying to figure out how to prevent the generic "An error occured...." message that shows very specific deatils about the error or even the stack trace and line numbers in my code.
Both upon starting up the app and any time later in the app.
I thought I could use:
app.UseExceptionHandler("/Home/Error");
and any unhandled exceptions will be caught by the middleware and then the user will be sent to my Home controller and Error view.
But this doesn't happen.
I forced errors to occur in my Startup.cs and later on in some of my Razor Pages, and I either see a blank page or I still see the very descriptive error page with error details and stack trace. Which I of course do not want in production.
Am I misunderstanding how this middleware works and how to accomplish what I'm looking to do?
Basically, asp.net core Configure method has following middleware by default
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{//for production
app.UseExceptionHandler("/Home/Error");
}
And you will find the Error.cshtml in Views/Shared/Error.cshtml which only shows the RequestId without detailed inforamtion in production by default.
If you want to use app.UseExceptionHandler("/Home/Error"); in development mode for a test, then just remove the above if/else block and use the code directly, then it will direct you to the error page in development.

Custom error message on failed authentication in IdentityServer4

I would like to display custom error message when authentication fails in IdentityServer4. Namely I want to show what went wrong, e.g. "invalid redirect url" or "invalid authentication flow". When authentication fails I see only that exception occured but for what happened I need to go into logs. In this case I would like to know that e.g. redirect url is wrong directly. How can I achieve that?
I'm thinking about some exception filter or custom middleware on ASP.NET Core. However it seems to me that exception filter won't work since that is MVC stuff and exception occurs in the IdentityServer middleware. And I am not sure how to create the middleware so it shows the error and also manages to use the same layout and ui parts as in MVC views. Is there another way? Maybe some extension points I did not see?