Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

How do I get my ASP.NET Core minimal API to return a 401 if the user is not authenticated instead of redirecting to the log-in page

$
0
0

I have an ASP.NET Core Blazor web app, which uses Identity for authentication. The server project's Program.cs contains the following (rather trivial) endpoint...

app.MapGet("/testapi-time", [Authorize] () =>  DateTime.Now.ToLongTimeString());

If I try to access this in a browser when not authenticated, I get redirected to the app's log-in page. Given that an API endpoint is not usually expected to be accessed from a browser, this seems odd. I would have expected it to return a 401 instead.

I know I can do the following...

    app.MapGet("/testapi-time", (HttpContext httpContext) =>      !httpContext.User.Identity.IsAuthenticated        ? Results.Unauthorized()        : Results.Ok(DateTime.Now.ToLongTimeString()));

...however that's a lot of boilerplate code for something that I would have expected the framework to do for me.

Am I doing something wrong, or is this the way it's supposed to work?


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>