1

Trying to add role authorization to minimal api and I dont understand why this simple test is not working. I can confirm that the role works.

In my Program.cs

I have app.ConfigureApi();

in Api.cs

public static class Api
{
    public static void ConfigureApi(this WebApplication app)
    { 
   // This works
        app.MapGet("/Hello/", [Authorize(Roles = Roles.Manager)] () =>
        {
            return Results.Ok("hello test");

        });

        //this works
        app.MapGet("/HolaNoAutho/", GetHola);


        //This does not work. Errors out. 
        app.MapGet("/HelloAutho/", [Authorize(Roles = Roles.Manager)]() => GetHola);


    }
   private static async Task<IResult> GetHola()
    {
        try
        {
            return Results.Ok("Hola Test");

        }
        catch (Exception ex)
        {

            return Results.Problem(ex.Message);
        }
    }


}

Any idea how I can make this work role authorization with minimal api?

The error is:

System.NotSupportedException: Serialization and deserialization of 'System.Func1[[System.Threading.Tasks.Task1[[Microsoft.AspNetCore.Http.IResult, Microsoft.AspNetCore.Http.Abstractions, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]' instances are not supported. The unsupported member type is located on type 'System.Func1[System.Threading.Tasks.Task1[Microsoft.AspNetCore.Http.IResult]]'. Path: $.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
causita
  • 1,607
  • 1
  • 20
  • 32
  • Just move your attribute to GetHola method. – Hamlet Hakobyan May 25 '22 at 17:52
  • I don't understand the insistence on building full-blown applications on top of the minimal api. It was originally designed for quick poc apps and I've seen dozens of questions recently about all of the confusion and issues the minimal api has caused when using it for real-world applications. – David L May 25 '22 at 17:53

1 Answers1

2

Your handler for "/HelloAutho/" returns a function due to the compiler feature allowing it to convert function name (method group) into a delegate. So the following:

[Authorize(Roles = Roles.Manager)]() => GetHola

Can be viewed something like:

[Authorize(Roles = Roles.Manager)]() => {
    Func<Task<IResult>> func = GetHola;
    return func ;
}

So the only thing you need to make it work is to invoke the function by adding parenthesis:

app.MapGet("/HelloAutho/", [Authorize(Roles = Roles.Manager)]() => GetHola());
Guru Stron
  • 102,774
  • 10
  • 95
  • 132