1

I have this code:

app.UseWhen(context => context.User.Identity?.IsAuthenticated ?? false, applicationBuilder =>
{
    app
        .MapGet("/User", (HttpContext context) => Json(context.User.Identity, new JsonSerializerOptions()
        {
            ReferenceHandler = ReferenceHandler.Preserve,
            WriteIndented = true
        }));
});

I would expect that I could only call /User if the user is authenticated. As it turns out, if the user is not authenticated then this method still returns a value. I would have expected that it would not find this endpoint and thus generate an error. I was actually hoping for an error...
Why does this method still work when a user is not authenticated?

I would like to enable or disable endpoints based on various conditions. In this case, authenticated users. But in other cases the user role would also matter. And some other user claims would be checked this way, disabling endpoints if certain claims are missing. But it doesn't seem to work like this...

Wim ten Brink
  • 25,901
  • 20
  • 83
  • 149

1 Answers1

2

Problem is that you are setting up the "main" application (i.e. app) in the conditional branch. You need to setup the applicationBuilder. For example:

app.UseWhen(context => context.Request.Headers.ContainsKey("test"), applicationBuilder =>
{
    applicationBuilder.UseRouting();
    applicationBuilder.UseEndpoints(routeBuilder =>
    {
        routeBuilder.MapGet("/User", (HttpContext context) => new { Test = "Ok" });
    });
});

In the example above "/User" route will result in 404 Not Found HTTP Status when there is no test header provided and in 200 OK json result if there is one.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132