2

How to allow anonymous access to an endpoint when using MinimalAPIs?

Assume I have the code below in the Program.cs file of a web app, using the Minimal API syntax:

app.MapGet("/hello", () => "world");

When using non-minimal syntax, we could allow anonymous access to an endpoint by decorating a controller with an [AllowAnonymous] attribute.

How would I perform the same when using the minimal syntax?

derekbaker783
  • 8,109
  • 4
  • 36
  • 50

2 Answers2

4

You should be able to use AllowAnonymousAttribute on Minimal API handler too as described in the docs:

app.MapGet("/login", [AllowAnonymous] () => "This endpoint is for all roles.");

Or alternatively use the AllowAnonymous method from AuthorizationEndpointConventionBuilderExtensions:

app.MapGet("/login2", () => "This endpoint also for all roles.")
   .AllowAnonymous();
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Why does adding the [AllowAnonymous] give me "error CS0246: The type or namespace name 'AllowAnonymousAttribute' could not be found"? Is there a using I need to add? – David Mays Oct 04 '22 at 17:55
3

When using the minimal syntax, you could use a chained method call as opposed to an attribute.

app.MapGet("/hello", () => "world").AllowAnonymous();

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-6.0#allow-unauthenticated-users-to-access-an-endpoint

derekbaker783
  • 8,109
  • 4
  • 36
  • 50